"use client";

import { useMemo, useState } 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 { useAlertConfirm } from "@/components/ui/alert-dialog";
import { useLocalStorage } from "@/lib/hooks/use-local-storage";
import { KNOWN_LICENSES, type KnownLicense } from "@/lib/sag/licenses-seed";
import { ALL_ORGANIZATIONS } from "@/lib/sag/entities";
import { formatDate } from "@/lib/utils";

type LicenseStatus = KnownLicense["status"];

interface UserLicense extends KnownLicense {
  source?: "seed" | "user";
}

export function LicensesManager() {
  const [userLicenses, setUserLicenses] = useLocalStorage<UserLicense[]>("sag.licenses.user", []);
  const [overrides, setOverrides] = useLocalStorage<Record<string, Partial<UserLicense>>>(
    "sag.licenses.overrides",
    {}
  );
  const [showAdd, setShowAdd] = useState(false);
  const [filterEntity, setFilterEntity] = useState<string>("all");
  const [filterStatus, setFilterStatus] = useState<"all" | LicenseStatus>("all");
  const { confirm: confirmAlert, AlertConfirmPortal } = useAlertConfirm();

  const merged: UserLicense[] = useMemo(() => {
    const base: UserLicense[] = KNOWN_LICENSES.map((l) => ({ ...l, source: "seed" }));
    const withOverrides = base.map((l) => ({ ...l, ...(overrides[l.id] ?? {}) }));
    return [...withOverrides, ...userLicenses];
  }, [overrides, userLicenses]);

  const filtered = merged.filter((l) => {
    if (filterEntity !== "all" && l.organizationSlug !== filterEntity) return false;
    if (filterStatus !== "all" && l.status !== filterStatus) return false;
    return true;
  });

  // sort by expiry (nulls/missing last), then by entity
  const sorted = [...filtered].sort((a, b) => {
    if (!a.expiresDate && !b.expiresDate) return a.organizationSlug.localeCompare(b.organizationSlug);
    if (!a.expiresDate) return 1;
    if (!b.expiresDate) return -1;
    return a.expiresDate.localeCompare(b.expiresDate);
  });

  const stats = {
    total: merged.length,
    active: merged.filter((l) => l.status === "Active").length,
    pending: merged.filter((l) => l.status === "Pending" || l.status === "In Application").length,
    expiring: merged.filter((l) => l.expiresDate && daysUntil(l.expiresDate) <= 60 && daysUntil(l.expiresDate) >= 0)
      .length,
    expired: merged.filter((l) => l.expiresDate && daysUntil(l.expiresDate) < 0).length,
  };

  function updateLicense(id: string, patch: Partial<UserLicense>) {
    const isSeed = KNOWN_LICENSES.some((l) => l.id === id);
    if (isSeed) {
      setOverrides({ ...overrides, [id]: { ...overrides[id], ...patch } });
    } else {
      setUserLicenses(userLicenses.map((l) => (l.id === id ? { ...l, ...patch } : l)));
    }
  }

  async function deleteUserLicense(id: string) {
    const ok = await confirmAlert({
      title: "Delete this license?",
      description: "This permanently removes the record. Cannot be undone.",
      actionLabel: "Delete",
      destructive: true,
    });
    if (!ok) return;
    setUserLicenses(userLicenses.filter((l) => l.id !== id));
  }

  function addLicense(l: Omit<UserLicense, "id">) {
    setUserLicenses([{ ...l, id: `user-${Date.now()}`, source: "user" }, ...userLicenses]);
    setShowAdd(false);
  }

  return (
    <>
    <div className="space-y-6">
      <section className="grid gap-4 md:grid-cols-5">
        <Stat label="Total" value={String(stats.total)} />
        <Stat label="Active" value={String(stats.active)} tone="success" />
        <Stat label="Pending / in app" value={String(stats.pending)} tone="warning" />
        <Stat label="Expiring ≤60d" value={String(stats.expiring)} tone={stats.expiring > 0 ? "warning" : "default"} />
        <Stat label="Expired" value={String(stats.expired)} tone={stats.expired > 0 ? "destructive" : "default"} />
      </section>

      <Card>
        <CardContent className="p-4 flex flex-wrap items-center gap-3">
          <select
            value={filterEntity}
            onChange={(e) => setFilterEntity(e.target.value)}
            className="h-10 rounded-md border border-input bg-background px-3 text-sm"
          >
            <option value="all">All entities</option>
            {ALL_ORGANIZATIONS.map((o) => (
              <option key={o.slug} value={o.slug}>
                {o.emoji} {o.name}
              </option>
            ))}
          </select>
          <select
            value={filterStatus}
            onChange={(e) => setFilterStatus(e.target.value as "all" | LicenseStatus)}
            className="h-10 rounded-md border border-input bg-background px-3 text-sm"
          >
            <option value="all">All statuses</option>
            <option value="Active">Active</option>
            <option value="Pending">Pending</option>
            <option value="In Application">In Application</option>
            <option value="Renewing">Renewing</option>
            <option value="Expired">Expired</option>
          </select>
          <span className="text-xs text-muted-foreground tabular-nums">
            {sorted.length} of {merged.length}
          </span>
          <Button variant="brand" size="sm" className="ml-auto" onClick={() => setShowAdd((v) => !v)}>
            {showAdd ? "Cancel" : "+ Add license"}
          </Button>
        </CardContent>
      </Card>

      {showAdd && <AddLicenseForm onAdd={addLicense} onCancel={() => setShowAdd(false)} />}

      <Card>
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="border-b bg-muted/40">
                <tr>
                  <th className="text-left p-3 font-medium">Entity</th>
                  <th className="text-left p-3 font-medium">License</th>
                  <th className="text-left p-3 font-medium">License #</th>
                  <th className="text-left p-3 font-medium">Expires</th>
                  <th className="text-left p-3 font-medium">Status</th>
                  <th className="text-right p-3 font-medium">Actions</th>
                </tr>
              </thead>
              <tbody>
                {sorted.map((l) => {
                  const org = ALL_ORGANIZATIONS.find((o) => o.slug === l.organizationSlug);
                  return (
                    <LicenseRow
                      key={l.id}
                      license={l}
                      orgName={org?.name ?? l.organizationSlug}
                      orgEmoji={org?.emoji}
                      onUpdate={(patch) => updateLicense(l.id, patch)}
                      onDelete={l.source === "user" ? () => deleteUserLicense(l.id) : undefined}
                    />
                  );
                })}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
    <AlertConfirmPortal />
    </>
  );
}

function LicenseRow({
  license,
  orgName,
  orgEmoji,
  onUpdate,
  onDelete,
}: {
  license: UserLicense;
  orgName: string;
  orgEmoji?: string;
  onUpdate: (patch: Partial<UserLicense>) => void;
  onDelete?: () => void;
}) {
  const [editing, setEditing] = useState(false);
  const days = license.expiresDate ? daysUntil(license.expiresDate) : null;

  return (
    <>
      <tr className="border-b last:border-b-0 hover:bg-muted/20">
        <td className="p-3">
          <span className="inline-flex items-center gap-2">
            <span>{orgEmoji ?? "🏢"}</span>
            <span className="text-sm">{orgName}</span>
          </span>
        </td>
        <td className="p-3">
          <div className="font-medium">{license.licenseType}</div>
          <div className="text-xs text-muted-foreground">{license.agency}{license.cadence ? ` · ${license.cadence}` : ""}</div>
          {license.notes && <div className="text-[10px] text-muted-foreground mt-1 italic">{license.notes}</div>}
        </td>
        <td className="p-3 text-xs font-mono">{license.licenseNumber ?? "—"}</td>
        <td className="p-3 text-xs">
          {license.expiresDate ? (
            <>
              <div>{formatDate(license.expiresDate)}</div>
              {days !== null && (
                <Badge
                  variant={days < 0 ? "destructive" : days <= 60 ? "warning" : "outline"}
                  className="mt-1 text-[10px]"
                >
                  {days < 0 ? `Expired ${Math.abs(days)}d ago` : `${days}d left`}
                </Badge>
              )}
            </>
          ) : (
            <span className="text-muted-foreground">—</span>
          )}
        </td>
        <td className="p-3">
          <Badge
            variant={
              license.status === "Active"
                ? "success"
                : license.status === "Expired"
                ? "destructive"
                : license.status === "In Application" || license.status === "Pending"
                ? "warning"
                : "info"
            }
          >
            {license.status}
          </Badge>
        </td>
        <td className="p-3 text-right">
          <Button variant="ghost" size="sm" onClick={() => setEditing((v) => !v)}>
            {editing ? "Done" : "Edit"}
          </Button>
          {onDelete && (
            <Button variant="ghost" size="sm" onClick={onDelete}>
              ×
            </Button>
          )}
        </td>
      </tr>
      {editing && (
        <tr className="bg-muted/30 border-b">
          <td colSpan={6} className="p-4">
            <div className="grid gap-3 md:grid-cols-4">
              <Field label="License #">
                <Input
                  value={license.licenseNumber ?? ""}
                  onChange={(e) => onUpdate({ licenseNumber: e.target.value })}
                />
              </Field>
              <Field label="Issued">
                <Input
                  type="date"
                  value={license.issuedDate ?? ""}
                  onChange={(e) => onUpdate({ issuedDate: e.target.value })}
                />
              </Field>
              <Field label="Expires">
                <Input
                  type="date"
                  value={license.expiresDate ?? ""}
                  onChange={(e) => onUpdate({ expiresDate: e.target.value })}
                />
              </Field>
              <Field label="Status">
                <select
                  value={license.status}
                  onChange={(e) => onUpdate({ status: e.target.value as LicenseStatus })}
                  className="w-full h-10 rounded-md border border-input bg-background px-3 text-sm"
                >
                  <option value="Active">Active</option>
                  <option value="Expired">Expired</option>
                  <option value="Pending">Pending</option>
                  <option value="In Application">In Application</option>
                  <option value="Renewing">Renewing</option>
                </select>
              </Field>
              <Field label="Notes" className="md:col-span-4">
                <Input
                  value={license.notes ?? ""}
                  onChange={(e) => onUpdate({ notes: e.target.value })}
                />
              </Field>
            </div>
          </td>
        </tr>
      )}
    </>
  );
}

function AddLicenseForm({
  onAdd,
  onCancel,
}: {
  onAdd: (l: Omit<UserLicense, "id">) => void;
  onCancel: () => void;
}) {
  const [form, setForm] = useState<Omit<UserLicense, "id">>({
    organizationSlug: ALL_ORGANIZATIONS[0]?.slug ?? "south-armz-global",
    licenseType: "",
    agency: "",
    status: "Active",
  });

  function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!form.licenseType.trim() || !form.agency.trim()) return;
    onAdd(form);
  }

  return (
    <Card>
      <CardContent className="p-6">
        <form onSubmit={submit} className="grid gap-3 md:grid-cols-2">
          <Field label="Entity">
            <select
              value={form.organizationSlug}
              onChange={(e) => setForm({ ...form, organizationSlug: e.target.value })}
              className="w-full h-10 rounded-md border border-input bg-background px-3 text-sm"
            >
              {ALL_ORGANIZATIONS.map((o) => (
                <option key={o.slug} value={o.slug}>
                  {o.emoji} {o.name}
                </option>
              ))}
            </select>
          </Field>
          <Field label="License type">
            <Input
              value={form.licenseType}
              onChange={(e) => setForm({ ...form, licenseType: e.target.value })}
              placeholder="e.g. NC ABC Wine Manufacturer Permit"
              required
            />
          </Field>
          <Field label="Agency">
            <Input
              value={form.agency}
              onChange={(e) => setForm({ ...form, agency: e.target.value })}
              placeholder="e.g. TTB, NCDOR, NC ABC, USDA"
              required
            />
          </Field>
          <Field label="License #">
            <Input
              value={form.licenseNumber ?? ""}
              onChange={(e) => setForm({ ...form, licenseNumber: e.target.value })}
            />
          </Field>
          <Field label="Issued">
            <Input
              type="date"
              value={form.issuedDate ?? ""}
              onChange={(e) => setForm({ ...form, issuedDate: e.target.value })}
            />
          </Field>
          <Field label="Expires">
            <Input
              type="date"
              value={form.expiresDate ?? ""}
              onChange={(e) => setForm({ ...form, expiresDate: e.target.value })}
            />
          </Field>
          <Field label="Status">
            <select
              value={form.status}
              onChange={(e) => setForm({ ...form, status: e.target.value as LicenseStatus })}
              className="w-full h-10 rounded-md border border-input bg-background px-3 text-sm"
            >
              <option value="Active">Active</option>
              <option value="Pending">Pending</option>
              <option value="In Application">In Application</option>
              <option value="Renewing">Renewing</option>
              <option value="Expired">Expired</option>
            </select>
          </Field>
          <Field label="Cadence">
            <Input
              value={form.cadence ?? ""}
              onChange={(e) => setForm({ ...form, cadence: e.target.value })}
              placeholder="Annual / Biennial / Quarterly"
            />
          </Field>
          <Field label="Notes" className="md:col-span-2">
            <Input
              value={form.notes ?? ""}
              onChange={(e) => setForm({ ...form, notes: e.target.value })}
            />
          </Field>
          <div className="md:col-span-2 flex justify-end gap-2">
            <Button variant="ghost" size="sm" onClick={onCancel} type="button">Cancel</Button>
            <Button variant="brand" size="sm" type="submit">Add license</Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}

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

function Stat({
  label,
  value,
  tone = "default",
}: {
  label: string;
  value: string;
  tone?: "default" | "success" | "warning" | "destructive";
}) {
  const colorClass =
    tone === "success"
      ? "text-green-700 dark:text-green-400"
      : tone === "warning"
      ? "text-yellow-700 dark:text-yellow-400"
      : tone === "destructive"
      ? "text-destructive"
      : "text-foreground";
  return (
    <Card>
      <CardContent className="p-5">
        <div className="text-xs uppercase tracking-wider text-muted-foreground">{label}</div>
        <div className={`mt-1 text-2xl font-semibold tabular-nums ${colorClass}`}>{value}</div>
      </CardContent>
    </Card>
  );
}

function daysUntil(iso: string): number {
  return Math.floor((new Date(iso).getTime() - new Date().getTime()) / 86400000);
}
