"use client";

import Link from "next/link";
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 { formatDate } from "@/lib/utils";

interface InvestmentOverride {
  ein?: string;
  ncSosFileNumber?: string;
  registeredAgent?: string;
  registeredAgentAddress?: string;
  formationDate?: string;
  lastAnnualReportFiledIso?: string;
  ownershipPctOverride?: number;
  coOwnersOverride?: string;
  notes?: string;
}

export function InvestmentsBoard() {
  const [overrides, setOverrides] = useLocalStorage<Record<string, InvestmentOverride>>(
    "sag.investments.overrides",
    {}
  );

  function update(slug: string, patch: Partial<InvestmentOverride>) {
    setOverrides({ ...overrides, [slug]: { ...overrides[slug], ...patch } });
  }

  const equityStakes = OWNER_INVESTMENTS.filter((o) => o.parentRelationship !== "managed-artist");
  const totalPersonalStakes = equityStakes.length;
  const avgStake = equityStakes.length
    ? Math.round(
        equityStakes.reduce((a, o) => a + (overrides[o.slug]?.ownershipPctOverride ?? o.ownershipPct ?? 0), 0) /
          equityStakes.length
      )
    : 0;

  return (
    <div className="space-y-6 max-w-5xl">
      <Card>
        <CardContent className="p-6">
          <h2 className="text-base font-semibold">Personal equity stakes outside SAG</h2>
          <p className="mt-2 text-sm text-foreground/85 max-w-2xl">
            These are companies Glenn owns part of in his personal capacity — not subsidiaries of South Armz Global. SAG has no claim. Track them here so the same alerts (annual report, NCDOR, etc.) surface alongside SAG’s.
          </p>
          <div className="mt-4 flex flex-wrap gap-3">
            <Stat label="Personal stakes" value={String(totalPersonalStakes)} />
            <Stat label="Average ownership" value={`${avgStake}%`} />
            <Stat label="State of record" value="NC" />
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardContent className="p-6">
          <h3 className="text-base font-semibold">📚 Look up each company at NC Secretary of State</h3>
          <p className="mt-2 text-sm text-muted-foreground max-w-2xl">
            NC SoS Business Registration is searchable here (Cloudflare-protected, so you have to use a browser):
          </p>
          <Button asChild variant="brand" size="sm" className="mt-3">
            <a
              href="https://www.sosnc.gov/online_services/search/by_title/_Business_Registration"
              target="_blank"
              rel="noopener noreferrer"
            >
              Search NC SoS Business Registration ↗
            </a>
          </Button>
          <p className="mt-3 text-xs text-muted-foreground">
            For each company you’ll get back: SOSID (file number), entity type, status, registered agent, formation date, and annual-report history. Paste those into the fields below.
          </p>
        </CardContent>
      </Card>

      {OWNER_INVESTMENTS.map((org) => {
        const o = overrides[org.slug] ?? {};
        const pct = o.ownershipPctOverride ?? org.ownershipPct ?? 0;
        const ein = o.ein ?? org.ein;
        const sosId = o.ncSosFileNumber ?? org.ncSosFileNumber;
        const formation = o.formationDate ?? org.formationDate;
        return (
          <Card key={org.slug}>
            <CardContent className="p-6">
              <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 }}
                >
                  {org.emoji}
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 flex-wrap mb-1">
                    <Badge variant="warning">
                      {org.parentRelationship === "managed-artist" ? "Managed artist" : "Personal investment"}
                    </Badge>
                    <Badge variant="outline">{org.industry}</Badge>
                    {org.parentRelationship === "managed-artist" ? (
                      <Badge variant="info">Managed on behalf of label</Badge>
                    ) : (
                      <Badge variant="info">{pct}% owned</Badge>
                    )}
                    <Badge variant="secondary">{org.entityType}</Badge>
                    <Badge variant="outline">{org.state}</Badge>
                  </div>
                  <h2 className="text-xl font-semibold">{org.name}</h2>
                  <p className="text-sm italic text-muted-foreground">{org.tagline}</p>
                  <p className="mt-2 text-sm text-foreground/85">{org.blurb}</p>
                </div>
                <div className="flex flex-col gap-2 shrink-0">
                  <Button asChild variant="outline" size="sm">
                    <a
                      href={`https://www.sosnc.gov/online_services/search/by_title/_Business_Registration?Word=${encodeURIComponent(org.name)}`}
                      target="_blank"
                      rel="noopener noreferrer"
                    >
                      Find on NC SoS ↗
                    </a>
                  </Button>
                  <Button asChild variant="outline" size="sm">
                    <Link href={`/portfolio/${org.slug}`}>Public bio →</Link>
                  </Button>
                </div>
              </div>

              <div className="mt-5 grid gap-3 md:grid-cols-2 border-t pt-4">
                <Field label="Ownership %">
                  <Input
                    type="number"
                    min="0"
                    max="100"
                    value={pct}
                    onChange={(e) =>
                      update(org.slug, { ownershipPctOverride: parseFloat(e.target.value) || 0 })
                    }
                  />
                </Field>
                <Field label="Co-owners / other equity holders">
                  <Input
                    value={o.coOwnersOverride ?? org.coOwners ?? ""}
                    onChange={(e) => update(org.slug, { coOwnersOverride: e.target.value })}
                    placeholder="e.g. Partner Name (51%)"
                  />
                </Field>
                <Field label="EIN (last 4 OK)">
                  <Input
                    value={ein ?? ""}
                    onChange={(e) => update(org.slug, { ein: e.target.value })}
                    placeholder="XX-XXXXXXX"
                  />
                </Field>
                <Field label="NC SoS file number (SOSID)">
                  <Input
                    value={sosId ?? ""}
                    onChange={(e) => update(org.slug, { ncSosFileNumber: e.target.value })}
                    placeholder="e.g. 1234567"
                  />
                </Field>
                <Field label="Registered agent">
                  <Input
                    value={o.registeredAgent ?? ""}
                    onChange={(e) => update(org.slug, { registeredAgent: e.target.value })}
                    placeholder="Agent name"
                  />
                </Field>
                <Field label="Registered agent address">
                  <Input
                    value={o.registeredAgentAddress ?? ""}
                    onChange={(e) => update(org.slug, { registeredAgentAddress: e.target.value })}
                    placeholder="123 Main St, City, NC 27..."
                  />
                </Field>
                <Field label="Formation date">
                  <Input
                    type="date"
                    value={formation ?? ""}
                    onChange={(e) => update(org.slug, { formationDate: e.target.value })}
                  />
                </Field>
                <Field label="Last annual report filed">
                  <Input
                    type="date"
                    value={o.lastAnnualReportFiledIso ?? ""}
                    onChange={(e) => update(org.slug, { lastAnnualReportFiledIso: e.target.value })}
                  />
                </Field>
                <Field label="Notes" className="md:col-span-2">
                  <textarea
                    className="mt-1 w-full text-sm rounded-md border border-input bg-background p-2"
                    rows={2}
                    value={o.notes ?? ""}
                    onChange={(e) => update(org.slug, { notes: e.target.value })}
                    placeholder="Partnership terms, key contacts, where the operating agreement lives, etc."
                  />
                </Field>
              </div>

              {o.lastAnnualReportFiledIso && (
                <p className="mt-3 text-xs text-green-700 dark:text-green-400">
                  ✓ Last annual report filed {formatDate(o.lastAnnualReportFiledIso)}
                </p>
              )}
            </CardContent>
          </Card>
        );
      })}

      <Card>
        <CardContent className="p-6">
          <h3 className="text-base font-semibold">What you need to file annually for each</h3>
          <p className="mt-2 text-sm text-muted-foreground">
            Even though Glenn isn’t the majority owner, NC SoS still requires the company itself to file. Make sure whichever partner is responsible is on it — confirm in writing each January.
          </p>
          <ul className="mt-3 space-y-1.5 text-sm">
            <li>• <strong>NC SoS Annual Report</strong> — every NC LLC or Corp, April 15 deadline. $200 (LLC) or $25 (Corp).</li>
            <li>• <strong>NCDOR Corporate Income & Franchise Tax (CD-405)</strong> — if Corp, April 15. Minimum $200 franchise tax.</li>
            <li>• <strong>NCDOR E-500 Sales & Use Tax</strong> — monthly if Kingston 99 sells food retail.</li>
            <li>• <strong>K-1 / 1099-DIV to you</strong> — partners issue these by Jan 31 so you can file your 1040.</li>
            <li>• <strong>Business personal property tax listing</strong> — county tax office, Jan 31.</li>
          </ul>
        </CardContent>
      </Card>
    </div>
  );
}

function Field({ label, children, className }: { label: string; children: React.ReactNode; className?: string }) {
  return (
    <div className={className}>
      <span className="text-xs text-muted-foreground">{label}</span>
      <div className="mt-1">{children}</div>
    </div>
  );
}

function Stat({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-md border bg-background px-4 py-3">
      <div className="section-label">{label}</div>
      <div className="mt-0.5 text-xl font-semibold tabular-nums">{value}</div>
    </div>
  );
}
