"use client";

import { useMemo, useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Kpi, KpiStrip } from "@/components/ui/kpi";
import { EmptyState } from "@/components/ui/empty-state";
import { useAlertConfirm } from "@/components/ui/alert-dialog";
import { useLocalStorage } from "@/lib/hooks/use-local-storage";
import { ALL_ORGANIZATIONS } from "@/lib/sag/entities";
import { logActivity } from "@/lib/activity/log";

// ──────────────────────────────────────────────────────────────────────────
// Data model
// ──────────────────────────────────────────────────────────────────────────

export type AbcPermitType =
  | "On-Premises Malt Beverage"
  | "On-Premises Unfortified Wine"
  | "On-Premises Fortified Wine"
  | "On-Premises Mixed Beverage"
  | "Off-Premises Malt Beverage"
  | "Off-Premises Unfortified Wine"
  | "Brown-Bagging"
  | "Brewery"
  | "Winery"
  | "Distillery"
  | "Other";

export interface AbcPermit {
  id: string;
  entitySlug: string;
  permitType: AbcPermitType;
  permitNumber: string;
  issuedDate: string; // YYYY-MM-DD
  expiresDate: string; // YYYY-MM-DD
  premisesAddress: string;
  abcBoardContact: string;
  renewalNotes: string;
  notes: string;
  updatedAt: string;
}

const PERMIT_TYPES: AbcPermitType[] = [
  "On-Premises Malt Beverage",
  "On-Premises Unfortified Wine",
  "On-Premises Fortified Wine",
  "On-Premises Mixed Beverage",
  "Off-Premises Malt Beverage",
  "Off-Premises Unfortified Wine",
  "Brown-Bagging",
  "Brewery",
  "Winery",
  "Distillery",
  "Other",
];

// Default entities that need NC ABC permits.
const DEFAULT_ENTITY_SLUGS = new Set<string>([
  "koshu-sake",
  "trap-sours",
  "metal-brixx-cafe",
  "carolina-cannabar",
]);

const LS_KEY = "sag.compliance.abc_permits";

// ──────────────────────────────────────────────────────────────────────────
// Helpers
// ──────────────────────────────────────────────────────────────────────────

function getDefaultEntities() {
  return ALL_ORGANIZATIONS.filter((o) => DEFAULT_ENTITY_SLUGS.has(o.slug));
}

function todayIso(): string {
  return new Date().toISOString().slice(0, 10);
}

function daysUntil(dateIso: string, fromIso: string = todayIso()): number {
  if (!dateIso) return Number.POSITIVE_INFINITY;
  const to = Date.UTC(
    parseInt(dateIso.slice(0, 4), 10),
    parseInt(dateIso.slice(5, 7), 10) - 1,
    parseInt(dateIso.slice(8, 10), 10)
  );
  const from = Date.UTC(
    parseInt(fromIso.slice(0, 4), 10),
    parseInt(fromIso.slice(5, 7), 10) - 1,
    parseInt(fromIso.slice(8, 10), 10)
  );
  return Math.round((to - from) / 86_400_000);
}

function expiryTone(days: number): { variant: "destructive" | "warning" | "success" | "outline"; label: string } {
  if (days < 0) return { variant: "destructive", label: `Expired ${Math.abs(days)}d ago` };
  if (days < 30) return { variant: "destructive", label: `${days}d left` };
  if (days < 90) return { variant: "warning", label: `${days}d left` };
  return { variant: "success", label: `${days}d left` };
}

// ──────────────────────────────────────────────────────────────────────────
// Main component
// ──────────────────────────────────────────────────────────────────────────

export function AbcPermitTracker() {
  const [permits, setPermits] = useLocalStorage<AbcPermit[]>(LS_KEY, []);
  const [showAdd, setShowAdd] = useState(false);
  const [showAllEntities, setShowAllEntities] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [filterEntity, setFilterEntity] = useState<string>("all");
  const [filterType, setFilterType] = useState<string>("all");
  const { confirm: confirmAlert, AlertConfirmPortal } = useAlertConfirm();

  const defaultEntities = useMemo(() => getDefaultEntities(), []);
  const entityOptions = showAllEntities ? ALL_ORGANIZATIONS : defaultEntities;

  const today = todayIso();

  // Sort by expiresDate ascending. Permits with no date sink to the bottom.
  const sortedPermits = useMemo(() => {
    return [...permits].sort((a, b) => {
      if (!a.expiresDate && !b.expiresDate) return 0;
      if (!a.expiresDate) return 1;
      if (!b.expiresDate) return -1;
      return a.expiresDate.localeCompare(b.expiresDate);
    });
  }, [permits]);

  const filtered = useMemo(() => {
    return sortedPermits.filter((p) => {
      if (filterEntity !== "all" && p.entitySlug !== filterEntity) return false;
      if (filterType !== "all" && p.permitType !== filterType) return false;
      return true;
    });
  }, [sortedPermits, filterEntity, filterType]);

  // KPIs
  const totalPermits = permits.length;
  const expiringSoon = permits.filter((p) => {
    const d = daysUntil(p.expiresDate, today);
    return d >= 0 && d < 60;
  }).length;
  const expired = permits.filter((p) => {
    const d = daysUntil(p.expiresDate, today);
    return d < 0;
  }).length;
  const entitiesCovered = new Set(permits.map((p) => p.entitySlug)).size;

  // Reminders banner: permits expiring within 60 days (including already expired).
  const reminderRows = useMemo(() => {
    return sortedPermits.filter((p) => {
      if (!p.expiresDate) return false;
      const d = daysUntil(p.expiresDate, today);
      return d < 60;
    });
  }, [sortedPermits, today]);

  function addPermit(data: Omit<AbcPermit, "id" | "updatedAt">) {
    setPermits((prev) => [
      ...prev,
      {
        ...data,
        id: `abc-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
        updatedAt: new Date().toISOString(),
      },
    ]);
    try {
      logActivity({
        source: "abc",
        verb: "created",
        title: `Added ${data.permitType}${data.permitNumber ? ` #${data.permitNumber}` : ""}`,
        entitySlug: data.entitySlug,
        href: "/app/compliance/abc-permits",
        meta: { permitType: data.permitType, expiresDate: data.expiresDate },
      });
    } catch {
      // fire-and-forget
    }
  }

  function updatePermit(id: string, patch: Partial<AbcPermit>) {
    const existing = permits.find((p) => p.id === id);
    setPermits((prev) =>
      prev.map((p) =>
        p.id === id ? { ...p, ...patch, updatedAt: new Date().toISOString() } : p
      )
    );
    if (!existing) return;
    try {
      const next = { ...existing, ...patch };
      logActivity({
        source: "abc",
        verb: "updated",
        title: `Updated ${next.permitType}${next.permitNumber ? ` #${next.permitNumber}` : ""}`,
        entitySlug: next.entitySlug,
        href: "/app/compliance/abc-permits",
        meta: { expiresDate: next.expiresDate },
      });
    } catch {
      // fire-and-forget
    }
  }

  async function deletePermit(id: string) {
    const ok = await confirmAlert({
      title: "Delete this permit?",
      description: "This permanently removes the record. Cannot be undone.",
      actionLabel: "Delete",
      destructive: true,
    });
    if (!ok) return;
    const existing = permits.find((p) => p.id === id);
    setPermits((prev) => prev.filter((p) => p.id !== id));
    try {
      if (existing) {
        logActivity({
          source: "abc",
          verb: "deleted",
          title: `Deleted ${existing.permitType}${existing.permitNumber ? ` #${existing.permitNumber}` : ""}`,
          entitySlug: existing.entitySlug,
          href: "/app/compliance/abc-permits",
        });
      }
    } catch {
      // fire-and-forget
    }
  }

  const defaultEntitySlug =
    defaultEntities[0]?.slug ?? entityOptions[0]?.slug ?? "koshu-sake";

  return (
    <>
    <div className="space-y-6">
      <KpiStrip cols={4}>
        <Kpi label="Active permits" value={String(totalPermits)} />
        <Kpi
          label="Expiring <60d"
          value={String(expiringSoon)}
          tone={expiringSoon > 0 ? "amber" : "neutral"}
        />
        <Kpi
          label="Expired"
          value={String(expired)}
          tone={expired > 0 ? "rose" : "neutral"}
        />
        <Kpi label="Entities covered" value={String(entitiesCovered)} />
      </KpiStrip>

      {reminderRows.length > 0 && (
        <Card className="border-destructive/50 bg-destructive/5">
          <CardContent className="p-4">
            <div className="flex items-start gap-3">
              <div className="text-2xl">⚠️</div>
              <div className="flex-1">
                <div className="text-sm font-semibold text-destructive">
                  {reminderRows.length} ABC permit
                  {reminderRows.length === 1 ? "" : "s"} expiring within 60 days
                </div>
                <p className="mt-1 text-xs text-muted-foreground">
                  NC ABC permits do not auto-renew. Start the renewal application well before
                  the expiration date — the ABC Commission recommends 60+ days lead time.
                </p>
                <ul className="mt-2 space-y-1">
                  {reminderRows.map((p) => {
                    const org = ALL_ORGANIZATIONS.find((o) => o.slug === p.entitySlug);
                    const d = daysUntil(p.expiresDate, today);
                    return (
                      <li key={p.id} className="text-xs">
                        <span className="font-mono text-muted-foreground">
                          {p.expiresDate}
                        </span>{" "}
                        — {org?.emoji} {org?.name} · {p.permitType}{" "}
                        <span
                          className={
                            d < 0
                              ? "text-destructive font-semibold"
                              : d < 30
                                ? "text-destructive"
                                : "text-yellow-700 dark:text-yellow-400"
                          }
                        >
                          ({d < 0 ? `expired ${Math.abs(d)}d ago` : `${d}d left`})
                        </span>
                      </li>
                    );
                  })}
                </ul>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      <Card>
        <CardContent className="p-4 flex items-center flex-wrap gap-3">
          <div className="flex items-center gap-2">
            <label className="text-xs text-muted-foreground">Entity</label>
            <select
              value={filterEntity}
              onChange={(e) => setFilterEntity(e.target.value)}
              className="h-9 rounded-md border border-input bg-background px-2 text-sm"
            >
              <option value="all">All</option>
              {entityOptions.map((o) => (
                <option key={o.slug} value={o.slug}>
                  {o.emoji} {o.name}
                </option>
              ))}
            </select>
          </div>
          <div className="flex items-center gap-2">
            <label className="text-xs text-muted-foreground">Type</label>
            <select
              value={filterType}
              onChange={(e) => setFilterType(e.target.value)}
              className="h-9 rounded-md border border-input bg-background px-2 text-sm"
            >
              <option value="all">All types</option>
              {PERMIT_TYPES.map((t) => (
                <option key={t} value={t}>
                  {t}
                </option>
              ))}
            </select>
          </div>
          <div className="text-xs text-muted-foreground">
            Showing {showAllEntities ? "all" : "default"} entities ·{" "}
            <button
              type="button"
              className="underline hover:text-foreground"
              onClick={() => setShowAllEntities((v) => !v)}
            >
              {showAllEntities ? "Show defaults only" : "Show all entities"}
            </button>
          </div>
          <div className="ml-auto">
            <Button
              size="sm"
              variant={showAdd ? "outline" : "brand"}
              onClick={() => setShowAdd((v) => !v)}
            >
              {showAdd ? "Cancel" : "+ Add permit"}
            </Button>
          </div>
        </CardContent>
      </Card>

      {showAdd && (
        <PermitForm
          entities={entityOptions}
          defaultEntitySlug={defaultEntitySlug}
          onSubmit={(data) => {
            addPermit(data);
            setShowAdd(false);
          }}
          onCancel={() => setShowAdd(false)}
        />
      )}

      <section className="space-y-2">
        <h2 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
          Permits — sorted by expiration
        </h2>
        {filtered.length === 0 ? (
          <EmptyState
            icon="🍷"
            title={permits.length === 0 ? "No ABC permits tracked yet" : "No permits match the current filters"}
            description={
              permits.length === 0
                ? "Click + Add permit to start."
                : "Try clearing or adjusting your filters."
            }
          />
        ) : (
          <div className="rounded-md border bg-card overflow-x-auto">
            <table className="w-full text-sm min-w-[720px]">
              <thead className="section-label border-b">
                <tr>
                  <th className="px-3 py-2 text-left">Entity</th>
                  <th className="px-3 py-2 text-left">Permit type</th>
                  <th className="px-3 py-2 text-left">Permit #</th>
                  <th className="px-3 py-2 text-left">Issued</th>
                  <th className="px-3 py-2 text-left">Expires</th>
                  <th className="px-3 py-2 text-left">Status</th>
                  <th className="px-3 py-2 text-right">Actions</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map((p) => {
                  const org = ALL_ORGANIZATIONS.find((o) => o.slug === p.entitySlug);
                  const d = daysUntil(p.expiresDate, today);
                  const tone = p.expiresDate
                    ? expiryTone(d)
                    : { variant: "outline" as const, label: "No expiry set" };
                  const isEditing = editingId === p.id;
                  const rowBg =
                    p.expiresDate && d < 30
                      ? "bg-destructive/5"
                      : p.expiresDate && d < 90
                        ? "bg-yellow-50 dark:bg-yellow-950/20"
                        : "";
                  return (
                    <tr key={p.id} className={`border-b last:border-0 ${rowBg}`}>
                      <td className="px-3 py-2">
                        <span className="inline-flex items-center gap-1">
                          {org?.emoji} {org?.name ?? p.entitySlug}
                        </span>
                      </td>
                      <td className="px-3 py-2 text-xs">{p.permitType}</td>
                      <td className="px-3 py-2 font-mono text-xs">
                        {p.permitNumber || "—"}
                      </td>
                      <td className="px-3 py-2 font-mono text-xs">
                        {p.issuedDate || "—"}
                      </td>
                      <td className="px-3 py-2 font-mono text-xs">
                        {p.expiresDate || "—"}
                      </td>
                      <td className="px-3 py-2">
                        <Badge variant={tone.variant}>{tone.label}</Badge>
                      </td>
                      <td className="px-3 py-2 text-right">
                        <div className="inline-flex items-center gap-1">
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => setEditingId(isEditing ? null : p.id)}
                          >
                            {isEditing ? "Close" : "Edit"}
                          </Button>
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => deletePermit(p.id)}
                          >
                            ×
                          </Button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </section>

      {editingId &&
        (() => {
          const p = permits.find((x) => x.id === editingId);
          if (!p) return null;
          return (
            <PermitForm
              key={editingId}
              entities={entityOptions}
              defaultEntitySlug={p.entitySlug}
              initial={p}
              onSubmit={(data) => {
                updatePermit(editingId, data);
                setEditingId(null);
              }}
              onCancel={() => setEditingId(null)}
              submitLabel="Save permit"
            />
          );
        })()}

      <p className="text-xs text-muted-foreground">
        NC ABC permits are issued by the NC Alcoholic Beverage Control Commission. Per-permit
        details are tracked locally in this browser. See{" "}
        <a
          href="https://abc.nc.gov"
          target="_blank"
          rel="noopener noreferrer"
          className="underline hover:text-foreground"
        >
          abc.nc.gov
        </a>{" "}
        for official permit applications and renewal forms.
      </p>
    </div>
    <AlertConfirmPortal />
    </>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Add / Edit Permit form
// ──────────────────────────────────────────────────────────────────────────

function PermitForm({
  entities,
  defaultEntitySlug,
  initial,
  onSubmit,
  onCancel,
  submitLabel = "Add permit",
}: {
  entities: typeof ALL_ORGANIZATIONS;
  defaultEntitySlug: string;
  initial?: AbcPermit;
  onSubmit: (data: Omit<AbcPermit, "id" | "updatedAt">) => void;
  onCancel: () => void;
  submitLabel?: string;
}) {
  const [entitySlug, setEntitySlug] = useState(initial?.entitySlug ?? defaultEntitySlug);
  const [permitType, setPermitType] = useState<AbcPermitType>(
    initial?.permitType ?? "On-Premises Malt Beverage"
  );
  const [permitNumber, setPermitNumber] = useState(initial?.permitNumber ?? "");
  const [issuedDate, setIssuedDate] = useState(initial?.issuedDate ?? "");
  const [expiresDate, setExpiresDate] = useState(initial?.expiresDate ?? "");
  const [premisesAddress, setPremisesAddress] = useState(initial?.premisesAddress ?? "");
  const [abcBoardContact, setAbcBoardContact] = useState(initial?.abcBoardContact ?? "");
  const [renewalNotes, setRenewalNotes] = useState(initial?.renewalNotes ?? "");
  const [notes, setNotes] = useState(initial?.notes ?? "");

  function submit(e: React.FormEvent) {
    e.preventDefault();
    onSubmit({
      entitySlug,
      permitType,
      permitNumber: permitNumber.trim(),
      issuedDate: issuedDate.trim(),
      expiresDate: expiresDate.trim(),
      premisesAddress: premisesAddress.trim(),
      abcBoardContact: abcBoardContact.trim(),
      renewalNotes: renewalNotes.trim(),
      notes: notes.trim(),
    });
  }

  return (
    <Card>
      <CardContent className="p-6">
        <form onSubmit={submit} className="grid gap-3 md:grid-cols-3">
          <Field label="Entity" className="md:col-span-2">
            <select
              value={entitySlug}
              onChange={(e) => setEntitySlug(e.target.value)}
              className="w-full h-10 rounded-md border border-input bg-background px-3 text-sm"
              required
            >
              {entities.map((o) => (
                <option key={o.slug} value={o.slug}>
                  {o.emoji} {o.name} ({o.industry})
                </option>
              ))}
            </select>
          </Field>
          <Field label="Permit type">
            <select
              value={permitType}
              onChange={(e) => setPermitType(e.target.value as AbcPermitType)}
              className="w-full h-10 rounded-md border border-input bg-background px-3 text-sm"
            >
              {PERMIT_TYPES.map((t) => (
                <option key={t} value={t}>
                  {t}
                </option>
              ))}
            </select>
          </Field>

          <Field label="Permit number">
            <Input
              value={permitNumber}
              onChange={(e) => setPermitNumber(e.target.value)}
              placeholder="e.g. 12345-6789"
            />
          </Field>
          <Field label="Issued date">
            <Input
              type="date"
              value={issuedDate}
              onChange={(e) => setIssuedDate(e.target.value)}
            />
          </Field>
          <Field label="Expires date">
            <Input
              type="date"
              value={expiresDate}
              onChange={(e) => setExpiresDate(e.target.value)}
            />
          </Field>

          <Field label="Premises address" className="md:col-span-3">
            <Input
              value={premisesAddress}
              onChange={(e) => setPremisesAddress(e.target.value)}
              placeholder="Street, city, NC ZIP"
            />
          </Field>

          <Field label="ABC Board contact" className="md:col-span-3">
            <Input
              value={abcBoardContact}
              onChange={(e) => setAbcBoardContact(e.target.value)}
              placeholder="Local ABC Board name, contact person, phone, email"
            />
          </Field>

          <Field label="Renewal notes" className="md:col-span-3">
            <textarea
              value={renewalNotes}
              onChange={(e) => setRenewalNotes(e.target.value)}
              className="w-full rounded-md border border-input bg-background p-2 text-sm"
              rows={2}
              placeholder="Renewal lead time, required inspections, fees, etc."
            />
          </Field>

          <Field label="Notes" className="md:col-span-3">
            <textarea
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              className="w-full rounded-md border border-input bg-background p-2 text-sm"
              rows={2}
              placeholder="Conditions, restrictions, related TTB permit #, etc."
            />
          </Field>

          <div className="md:col-span-3 flex items-center justify-end gap-2">
            <Button variant="ghost" size="sm" type="button" onClick={onCancel}>
              Cancel
            </Button>
            <Button variant="brand" size="sm" type="submit">
              {submitLabel}
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Shared primitives
// ──────────────────────────────────────────────────────────────────────────

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

