"use client";

import { useMemo } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useLocalStorage } from "@/lib/hooks/use-local-storage";
import { OWNER_INVESTMENTS } from "@/lib/sag/entities";
import { formatCurrency, formatDate, cn } from "@/lib/utils";

/**
 * P3 — Kingston 99 manager card.
 *
 * Surfaces Glenn's 10% interest in Kingston 99 on /app/investments. The card
 * lives outside the generic InvestmentsBoard editor because it carries
 * Kingston-specific bookkeeping that doesn't apply to the other personal
 * investments (yet): expected-distribution math and a manual distribution
 * register.
 *
 * Sources:
 *   - Entity record (slug "kingston99") from OWNER_INVESTMENTS for name +
 *     ownership %. No filings data on the Organization type today, so the
 *     annual-report status falls back to a fixed April 15 deadline.
 *
 * LocalStorage keys this component owns:
 *   - sag.investments.kingston99.expected_distribution  (number, YTD profit
 *     estimate the user types in; card derives 10% from it)
 *   - sag.investments.kingston99.distributions          (array of received
 *     distributions: { date, amount, note? })
 */

interface Distribution {
  id: string;
  date: string; // YYYY-MM-DD
  amount: number;
  note?: string;
}

const NC_SOS_LOOKUP_ROOT =
  "https://www.sosnc.gov/online_services/search/by_title/_Business_Registration";
const NC_SOS_KINGSTON_QUERY = `${NC_SOS_LOOKUP_ROOT}?Words=Kingston+99`;

/** Compute the next April 15 deadline relative to `today`. */
function nextAnnualReportDeadline(today: Date): Date {
  const year = today.getUTCFullYear();
  const apr15ThisYear = new Date(Date.UTC(year, 3, 15)); // April = month index 3
  if (today.getTime() <= apr15ThisYear.getTime()) return apr15ThisYear;
  return new Date(Date.UTC(year + 1, 3, 15));
}

function daysBetween(a: Date, b: Date): number {
  const ms = b.getTime() - a.getTime();
  return Math.ceil(ms / (1000 * 60 * 60 * 24));
}

function newDistributionId(): string {
  // Crypto-safe IDs aren't required here — these never leave the browser.
  return `dist-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
}

export function Kingston99Card() {
  const org = useMemo(
    () => OWNER_INVESTMENTS.find((o) => o.slug === "kingston99"),
    []
  );

  const [expectedYtdProfit, setExpectedYtdProfit] = useLocalStorage<number>(
    "sag.investments.kingston99.expected_distribution",
    0
  );
  const [distributions, setDistributions] = useLocalStorage<Distribution[]>(
    "sag.investments.kingston99.distributions",
    []
  );

  const today = useMemo(() => new Date(), []);
  const deadline = useMemo(() => nextAnnualReportDeadline(today), [today]);
  const daysUntilDeadline = useMemo(
    () => daysBetween(today, deadline),
    [today, deadline]
  );

  const deadlineTone: "destructive" | "warning" | "success" =
    daysUntilDeadline < 30
      ? "destructive"
      : daysUntilDeadline < 90
        ? "warning"
        : "success";

  const ownershipPct = org?.ownershipPct ?? 10;
  const estimatedDistribution = (expectedYtdProfit * ownershipPct) / 100;

  const sortedDistributions = useMemo(
    () => [...distributions].sort((a, b) => a.date.localeCompare(b.date)),
    [distributions]
  );

  const totalReceived = useMemo(
    () => sortedDistributions.reduce((sum, d) => sum + (d.amount || 0), 0),
    [sortedDistributions]
  );

  function addDistribution() {
    const todayIso = new Date().toISOString().slice(0, 10);
    setDistributions([
      ...distributions,
      { id: newDistributionId(), date: todayIso, amount: 0, note: "" },
    ]);
  }

  function updateDistribution(id: string, patch: Partial<Distribution>) {
    setDistributions(
      distributions.map((d) => (d.id === id ? { ...d, ...patch } : d))
    );
  }

  function removeDistribution(id: string) {
    setDistributions(distributions.filter((d) => d.id !== id));
  }

  const displayName = org?.name ?? "Kingston 99";
  const displayEmoji = org?.emoji ?? "🇯🇲";

  return (
    <Card>
      <CardContent className="p-6 space-y-6">
        {/* Header */}
        <div className="flex items-start gap-4 flex-wrap">
          <div
            className="w-14 h-14 rounded-xl flex items-center justify-center text-3xl shrink-0"
            style={{
              backgroundColor: org?.primaryColor ? `${org.primaryColor}25` : undefined,
            }}
            aria-hidden
          >
            {displayEmoji}
          </div>
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 flex-wrap mb-1">
              <Badge variant="warning">Manager investment</Badge>
              <Badge variant="info">{ownershipPct}% interest</Badge>
              {org?.industry && <Badge variant="outline">{org.industry}</Badge>}
            </div>
            <h2 className="text-xl font-semibold">{displayName}</h2>
            <p className="text-xs text-muted-foreground">
              Manager investment · {ownershipPct}% interest
            </p>
          </div>
        </div>

        {/* 1. Annual report status */}
        <section className="border-t pt-4 space-y-2">
          <div className="flex items-center justify-between gap-2 flex-wrap">
            <h3 className="text-sm font-semibold">Annual report status</h3>
            <Badge
              variant={
                deadlineTone === "destructive"
                  ? "destructive"
                  : deadlineTone === "warning"
                    ? "warning"
                    : "success"
              }
              className="text-[10px]"
            >
              {daysUntilDeadline <= 0
                ? "Due today"
                : `${daysUntilDeadline} day${daysUntilDeadline === 1 ? "" : "s"} until ${formatDate(deadline)}`}
            </Badge>
          </div>
          <p className="text-xs text-muted-foreground">
            Due annually by April 15. Next deadline:{" "}
            <span className="font-mono text-foreground">{formatDate(deadline)}</span>.
            Confirm with the operating partner that the NC SoS Annual Report
            and any NCDOR filings get on the calendar — even at 10%, a late
            filing risks administrative dissolution.
          </p>
        </section>

        {/* 2. Estimated distribution (10%) */}
        <section className="border-t pt-4 space-y-3">
          <div>
            <h3 className="text-sm font-semibold">
              Estimated distribution ({ownershipPct}%)
            </h3>
            <p className="text-xs text-muted-foreground">
              Type the YTD profit estimate you&apos;re hearing from the
              operating partners. Card derives your {ownershipPct}% share.
              Persists locally only.
            </p>
          </div>
          <div className="grid gap-3 md:grid-cols-2">
            <div>
              <label
                htmlFor="kingston99-ytd-profit"
                className="section-label"
              >
                YTD profit estimate (full pool)
              </label>
              <Input
                id="kingston99-ytd-profit"
                type="number"
                min="0"
                step="0.01"
                value={Number.isFinite(expectedYtdProfit) ? expectedYtdProfit : 0}
                onChange={(e) =>
                  setExpectedYtdProfit(parseFloat(e.target.value) || 0)
                }
                placeholder="0.00"
                className="mt-1"
              />
            </div>
            <div className="rounded-md bg-muted/40 px-3 py-2">
              <div className="section-label">
                Your {ownershipPct}% share
              </div>
              <div className="mt-0.5 text-xl font-semibold tabular-nums">
                {formatCurrency(estimatedDistribution)}
              </div>
              <div className="mt-0.5 text-[10px] text-muted-foreground">
                Placeholder until partner statements arrive
              </div>
            </div>
          </div>
        </section>

        {/* 3. Actual distributions received */}
        <section className="border-t pt-4 space-y-3">
          <div className="flex items-center justify-between gap-2 flex-wrap">
            <div>
              <h3 className="text-sm font-semibold">
                Actual distributions received
              </h3>
              <p className="text-xs text-muted-foreground">
                Log each disbursement you actually receive. Running total
                feeds the tax-pack picture later.
              </p>
            </div>
            <Button variant="outline" size="sm" onClick={addDistribution}>
              + Add distribution
            </Button>
          </div>

          {sortedDistributions.length === 0 ? (
            <p className="text-xs text-muted-foreground italic">
              No distributions logged yet.
            </p>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full min-w-[640px] text-xs">
                <thead className="section-label border-b">
                  <tr>
                    <th className="py-2 pr-2 text-left font-medium w-40">Date</th>
                    <th className="py-2 px-2 text-right font-medium w-32">Amount</th>
                    <th className="py-2 px-2 text-left font-medium">Note</th>
                    <th className="py-2 pl-2 text-right font-medium w-16"> </th>
                  </tr>
                </thead>
                <tbody>
                  {sortedDistributions.map((d) => (
                    <tr key={d.id} className="border-b last:border-0 align-middle">
                      <td className="py-1.5 pr-2">
                        <Input
                          type="date"
                          value={d.date}
                          onChange={(e) =>
                            updateDistribution(d.id, { date: e.target.value })
                          }
                          className="h-8"
                        />
                      </td>
                      <td className="py-1.5 px-2">
                        <Input
                          type="number"
                          min="0"
                          step="0.01"
                          value={Number.isFinite(d.amount) ? d.amount : 0}
                          onChange={(e) =>
                            updateDistribution(d.id, {
                              amount: parseFloat(e.target.value) || 0,
                            })
                          }
                          className="h-8 text-right tabular-nums"
                        />
                      </td>
                      <td className="py-1.5 px-2">
                        <Input
                          value={d.note ?? ""}
                          onChange={(e) =>
                            updateDistribution(d.id, { note: e.target.value })
                          }
                          placeholder="e.g. Q1 partner check"
                          className="h-8"
                        />
                      </td>
                      <td className="py-1.5 pl-2 text-right">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => removeDistribution(d.id)}
                          aria-label={`Remove distribution dated ${d.date}`}
                        >
                          ×
                        </Button>
                      </td>
                    </tr>
                  ))}
                  <tr>
                    <td className="py-2 pr-2 section-label">
                      Running total
                    </td>
                    <td
                      className={cn(
                        "py-2 px-2 text-right text-sm font-semibold tabular-nums",
                        totalReceived > 0 ? "text-foreground" : "text-muted-foreground"
                      )}
                    >
                      {formatCurrency(totalReceived)}
                    </td>
                    <td className="py-2 px-2 text-[10px] text-muted-foreground" colSpan={2}>
                      Across {sortedDistributions.length} distribution
                      {sortedDistributions.length === 1 ? "" : "s"}
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          )}
        </section>

        {/* 4. Quick links */}
        <section className="border-t pt-4 space-y-2">
          <h3 className="text-sm font-semibold">Quick links</h3>
          <div className="flex flex-wrap gap-2">
            <Button asChild variant="outline" size="sm">
              <a
                href={NC_SOS_LOOKUP_ROOT}
                target="_blank"
                rel="noopener noreferrer"
              >
                NC SoS business lookup →
              </a>
            </Button>
            <Button asChild variant="outline" size="sm">
              <a
                href={NC_SOS_KINGSTON_QUERY}
                target="_blank"
                rel="noopener noreferrer"
              >
                View NC SoS Kingston 99 filing →
              </a>
            </Button>
          </div>
          <p className="text-[10px] text-muted-foreground">
            SoS search is Cloudflare-protected; the prefilled link opens the
            search form with &quot;Kingston 99&quot; staged — you may need to
            re-submit the form once the page loads.
          </p>
        </section>
      </CardContent>
    </Card>
  );
}
