"use client";

import { useMemo, useState } from "react";
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 { SEED_FILINGS, AGENCIES, type FilingCadence } from "@/lib/sag/filings-seed";

const CADENCE_ORDER: FilingCadence[] = [
  "Semi-Monthly",
  "Monthly",
  "Quarterly",
  "Semi-Annual",
  "Annual",
  "Biennial",
  "One-Time",
];

export function ComplianceReference() {
  const [filterAgency, setFilterAgency] = useState<string>("all");

  // Build unique filing-types grouped by agency (collapsing per-entity dupes)
  const filingsByAgency = useMemo(() => {
    type Entry = { filingType: string; cadence: FilingCadence; description?: string; filingUrl?: string; entityCount: number };
    const map = new Map<string, Entry>();
    for (const f of SEED_FILINGS) {
      const key = `${f.agency}::${f.filingType}`;
      const existing = map.get(key);
      if (existing) {
        existing.entityCount++;
      } else {
        map.set(key, {
          filingType: f.filingType,
          cadence: f.cadence,
          description: f.description,
          filingUrl: f.filingUrl,
          entityCount: 1,
        });
      }
    }
    const groups = new Map<string, Entry[]>();
    for (const [key, value] of map) {
      const [agency] = key.split("::");
      const list = groups.get(agency) ?? [];
      list.push(value);
      groups.set(agency, list);
    }
    for (const list of groups.values()) {
      list.sort((a, b) => CADENCE_ORDER.indexOf(a.cadence) - CADENCE_ORDER.indexOf(b.cadence));
    }
    return groups;
  }, []);

  const visibleAgencies = AGENCIES.filter((a) => {
    if (filterAgency === "all") return true;
    return a.id === filterAgency;
  });

  const totalFilings = SEED_FILINGS.length;
  const uniqueFilingTypes = new Set(SEED_FILINGS.map((f) => f.filingType)).size;
  const agenciesCount = new Set(SEED_FILINGS.map((f) => f.agency)).size;

  return (
    <div className="space-y-6 max-w-6xl">
      <Card>
        <CardContent className="p-6">
          <p className="text-sm text-foreground/85 leading-relaxed">
            South Armz Global is a North Carolina LLC. Every NC-based operating subsidiary inherits the same compliance landscape: state-level filings with NC SoS, NCDOR, NC DES, and county tax offices, plus federal filings with the IRS, plus industry-specific agencies (TTB for sake/wine, USDA for hemp, FCC for broadcasting, FinCEN for beneficial ownership).
          </p>
          <p className="mt-3 text-sm text-foreground/85 leading-relaxed">
            This page enumerates every filing seeded into the system. Each entity gets the applicable subset on its <code className="text-xs">/app/entities/[slug]</code> Compliance tab and in the global filings tracker.
          </p>
          <div className="mt-5 flex flex-wrap gap-3">
            <Stat label="Tracked filings" value={String(totalFilings)} />
            <Stat label="Unique filing types" value={String(uniqueFilingTypes)} />
            <Stat label="Agencies" value={String(agenciesCount)} />
          </div>
          <div className="mt-5 flex gap-2">
            <Button asChild variant="brand" size="sm">
              <Link href="/app/compliance/filings">Open filings tracker →</Link>
            </Button>
            <Button asChild variant="outline" size="sm">
              <Link href="/app/calendar">Compliance calendar →</Link>
            </Button>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardContent className="p-4 flex flex-wrap gap-2 items-center">
          <span className="text-sm font-medium mr-2">Filter:</span>
          <Chip active={filterAgency === "all"} onClick={() => setFilterAgency("all")}>All agencies</Chip>
          {AGENCIES.map((a) => (
            <Chip key={a.id} active={filterAgency === a.id} onClick={() => setFilterAgency(a.id)}>
              {a.name}
            </Chip>
          ))}
        </CardContent>
      </Card>

      {visibleAgencies.map((agency) => {
        const filings = filingsByAgency.get(agency.name) ?? [];
        return (
          <Card key={agency.id}>
            <CardContent className="p-6">
              <div className="flex items-start justify-between gap-4 flex-wrap mb-4">
                <div>
                  <h2 className="text-lg font-semibold">{agency.name}</h2>
                  <p className="text-sm text-muted-foreground mt-0.5">{agency.scope}</p>
                  {agency.notes && (
                    <p className="mt-1 text-xs text-yellow-700 dark:text-yellow-400 italic">⚠ {agency.notes}</p>
                  )}
                </div>
                <Button asChild variant="outline" size="sm">
                  <a href={agency.url} target="_blank" rel="noopener noreferrer">
                    Agency website ↗
                  </a>
                </Button>
              </div>

              {filings.length === 0 ? (
                <p className="text-xs text-muted-foreground italic">No filings seeded yet for this agency.</p>
              ) : (
                <ul className="space-y-2.5">
                  {filings.map((f, i) => (
                    <li key={i} className="rounded-md border bg-background p-3">
                      <div className="flex items-start justify-between gap-3 flex-wrap">
                        <div className="min-w-0 flex-1">
                          <div className="flex items-center gap-2 flex-wrap">
                            <Badge variant="outline" className="text-[10px]">{f.cadence}</Badge>
                            <span className="text-sm font-medium">{f.filingType}</span>
                            <span className="text-[10px] text-muted-foreground">
                              · applies to {f.entityCount} entit{f.entityCount === 1 ? "y" : "ies"}
                            </span>
                          </div>
                          {f.description && (
                            <p className="mt-1.5 text-xs text-muted-foreground leading-relaxed">{f.description}</p>
                          )}
                        </div>
                        {f.filingUrl && (
                          <Button asChild variant="ghost" size="sm">
                            <a href={f.filingUrl} target="_blank" rel="noopener noreferrer">File ↗</a>
                          </Button>
                        )}
                      </div>
                    </li>
                  ))}
                </ul>
              )}
            </CardContent>
          </Card>
        );
      })}

      <Card>
        <CardContent className="p-6">
          <h2 className="text-lg font-semibold">Things this reference does not cover</h2>
          <ul className="mt-3 space-y-1.5 text-sm text-foreground/85">
            <li>· Local fire / health inspections (Metal Brixx, Koshu Bar — handled at the operations level)</li>
            <li>· Industry-specific certifications (kosher / organic / fair-trade) — track in /app/compliance/licenses</li>
            <li>· Trademark / IP registrations (USPTO) — track as licenses</li>
            <li>· Out-of-state filings if any SAG entity does business outside NC (foreign entity registration)</li>
            <li>· Sales tax in other states if Toast sells across state lines (nexus rules — verify with CPA)</li>
            <li>· Sales tax holiday + special-event temporary permits (event-by-event basis)</li>
            <li>· ACA reporting (Forms 1095-B/C) — only kicks in at 50+ FT-equivalent employees portfolio-wide</li>
            <li>· 401(k) Form 5500 — only if you sponsor a retirement plan</li>
          </ul>
          <p className="mt-4 text-xs text-muted-foreground italic">
            Always confirm specifics with a CPA + securities counsel. This reference is best-effort current as of Q2 2026 and laws change.
          </p>
        </CardContent>
      </Card>
    </div>
  );
}

function Chip({ active, onClick, children }: { active: boolean; onClick: () => void; children: React.ReactNode }) {
  return (
    <button
      onClick={onClick}
      className={`text-xs px-3 py-1.5 rounded-full border transition-colors ${
        active ? "bg-foreground text-background border-foreground" : "border-input text-muted-foreground hover:bg-accent"
      }`}
    >
      {children}
    </button>
  );
}

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>
  );
}
