"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 HempLicenseType =
  | "Industrial Hemp Grower"
  | "Industrial Hemp Processor"
  | "Hemp Retailer"
  | "Hemp Manufacturer"
  | "Hemp Distributor"
  | "Other";

export type HempThcTestSchedule =
  | "Pre-harvest only"
  | "Pre-harvest + Random"
  | "Monthly"
  | "Quarterly"
  | "Not required"
  | "Other";

export interface HempLicense {
  id: string;
  entitySlug: string;
  licenseType: HempLicenseType;
  licenseNumber: string;
  issuedDate: string; // YYYY-MM-DD
  expiresDate: string; // YYYY-MM-DD
  growingLocations: string; // free text, comma-separated addresses or county names
  thcTestSchedule: HempThcTestSchedule;
  thcTestNotes: string; // free text — last lab, contact, etc
  notes: string;
  updatedAt: string;
}

const LICENSE_TYPES: HempLicenseType[] = [
  "Industrial Hemp Grower",
  "Industrial Hemp Processor",
  "Hemp Retailer",
  "Hemp Manufacturer",
  "Hemp Distributor",
  "Other",
];

const THC_TEST_SCHEDULES: HempThcTestSchedule[] = [
  "Pre-harvest only",
  "Pre-harvest + Random",
  "Monthly",
  "Quarterly",
  "Not required",
  "Other",
];

// Industries that owe NC hemp licensing — defaults the entity picker.
const HEMP_INDUSTRIES = new Set(["Hemp & Cannabis"]);

const LS_KEY = "sag.compliance.hemp_licenses";

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

function getHempEntities() {
  return ALL_ORGANIZATIONS.filter(
    (o) => o.status !== "Dissolved" && HEMP_INDUSTRIES.has(o.industry)
  );
}

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

function daysUntil(iso: string): number {
  if (!iso) return Number.POSITIVE_INFINITY;
  const t = new Date(iso + "T00:00:00Z").getTime();
  const now = new Date(todayIso() + "T00:00:00Z").getTime();
  return Math.round((t - now) / (24 * 60 * 60 * 1000));
}

function formatDateShort(iso: string): string {
  if (!iso) return "—";
  return iso;
}

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

export function HempLicenseTracker() {
  const [licenses, setLicenses] = useLocalStorage<HempLicense[]>(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 hempEntities = useMemo(() => getHempEntities(), []);
  const entityOptions = showAllEntities ? ALL_ORGANIZATIONS : hempEntities;

  // Sort by expiresDate ascending; empty/invalid dates sink to the bottom.
  const sortedLicenses = useMemo(() => {
    return [...licenses].sort((a, b) => {
      const ae = a.expiresDate || "9999-12-31";
      const be = b.expiresDate || "9999-12-31";
      return ae.localeCompare(be);
    });
  }, [licenses]);

  const filteredLicenses = useMemo(() => {
    return sortedLicenses.filter((l) => {
      if (filterEntity !== "__all__" && l.entitySlug !== filterEntity) return false;
      if (filterType !== "__all__" && l.licenseType !== filterType) return false;
      return true;
    });
  }, [sortedLicenses, filterEntity, filterType]);

  // Reminder rows: expiring in <60 days (and not already expired beyond a year).
  const reminderRows = useMemo(() => {
    return sortedLicenses.filter((l) => {
      const d = daysUntil(l.expiresDate);
      return Number.isFinite(d) && d < 60 && d > -365;
    });
  }, [sortedLicenses]);

  // KPIs
  const totalActive = licenses.length;
  const expiringSoon = sortedLicenses.filter((l) => {
    const d = daysUntil(l.expiresDate);
    return Number.isFinite(d) && d < 30 && d >= 0;
  }).length;
  const expired = sortedLicenses.filter((l) => {
    const d = daysUntil(l.expiresDate);
    return Number.isFinite(d) && d < 0;
  }).length;
  const distinctEntities = new Set(licenses.map((l) => l.entitySlug)).size;

  function addLicense(data: Omit<HempLicense, "id" | "updatedAt">) {
    setLicenses((prev) => [
      ...prev,
      {
        ...data,
        id: `hemp-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
        updatedAt: new Date().toISOString(),
      },
    ]);
    try {
      logActivity({
        source: "hemp",
        verb: "created",
        title: `Added ${data.licenseType}${data.licenseNumber ? ` #${data.licenseNumber}` : ""}`,
        entitySlug: data.entitySlug,
        href: "/app/compliance/hemp-licenses",
        meta: { expiresDate: data.expiresDate, licenseType: data.licenseType },
      });
    } catch {
      // fire-and-forget
    }
  }

  function updateLicense(id: string, patch: Partial<HempLicense>) {
    const existing = licenses.find((l) => l.id === id);
    setLicenses((prev) =>
      prev.map((l) =>
        l.id === id ? { ...l, ...patch, updatedAt: new Date().toISOString() } : l
      )
    );
    if (!existing) return;
    try {
      const next = { ...existing, ...patch };
      logActivity({
        source: "hemp",
        verb: "updated",
        title: `Updated ${next.licenseType}${next.licenseNumber ? ` #${next.licenseNumber}` : ""}`,
        entitySlug: next.entitySlug,
        href: "/app/compliance/hemp-licenses",
        meta: { expiresDate: next.expiresDate },
      });
    } catch {
      // fire-and-forget
    }
  }

  async function deleteLicense(id: string) {
    const ok = await confirmAlert({
      title: "Delete this hemp license?",
      description: "This permanently removes the record. Cannot be undone.",
      actionLabel: "Delete",
      destructive: true,
    });
    if (!ok) return;
    const existing = licenses.find((l) => l.id === id);
    setLicenses((prev) => prev.filter((l) => l.id !== id));
    try {
      if (existing) {
        logActivity({
          source: "hemp",
          verb: "deleted",
          title: `Deleted ${existing.licenseType}${existing.licenseNumber ? ` #${existing.licenseNumber}` : ""}`,
          entitySlug: existing.entitySlug,
          href: "/app/compliance/hemp-licenses",
        });
      }
    } catch {
      // fire-and-forget
    }
  }

  // Default entity for new license: first hemp entity not already on a license.
  const defaultEntitySlug = useMemo(() => {
    const used = new Set(licenses.map((l) => l.entitySlug));
    const needed = hempEntities.find((e) => !used.has(e.slug));
    return needed?.slug ?? hempEntities[0]?.slug ?? "sandhills-hemp";
  }, [hempEntities, licenses]);

  return (
    <>
    <div className="space-y-6">
      <KpiStrip cols={4}>
        <Kpi label="Licenses on file" value={String(totalActive)} />
        <Kpi
          label="Expiring <30 days"
          value={String(expiringSoon)}
          tone={expiringSoon > 0 ? "rose" : "neutral"}
        />
        <Kpi
          label="Expired"
          value={String(expired)}
          tone={expired > 0 ? "rose" : "neutral"}
        />
        <Kpi label="Entities covered" value={String(distinctEntities)} />
      </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} hemp license
                  {reminderRows.length === 1 ? "" : "s"} expiring soon
                </div>
                <p className="mt-1 text-xs text-muted-foreground">
                  NC Department of Agriculture hemp licenses must be renewed before
                  expiration. The following expire within 60 days or are already past due:
                </p>
                <ul className="mt-2 space-y-1">
                  {reminderRows.map((r) => {
                    const org = ALL_ORGANIZATIONS.find((o) => o.slug === r.entitySlug);
                    const d = daysUntil(r.expiresDate);
                    const label =
                      d < 0
                        ? `expired ${Math.abs(d)}d ago`
                        : d === 0
                          ? "expires today"
                          : `expires in ${d}d`;
                    return (
                      <li key={r.id} className="text-xs">
                        <span className="font-mono text-muted-foreground">
                          {r.expiresDate || "—"}
                        </span>{" "}
                        — {org?.emoji} {org?.name} · {r.licenseType}
                        {r.licenseNumber ? ` (#${r.licenseNumber})` : ""} ·{" "}
                        <span className="font-semibold">{label}</span>
                      </li>
                    );
                  })}
                </ul>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      <Card>
        <CardContent className="p-4 flex items-center flex-wrap gap-3">
          <div className="text-xs text-muted-foreground">
            Showing {showAllEntities ? "all" : "hemp"} entities ·{" "}
            <button
              type="button"
              className="underline hover:text-foreground"
              onClick={() => setShowAllEntities((v) => !v)}
            >
              {showAllEntities ? "Show hemp only" : "Show all entities"}
            </button>
          </div>

          <div className="flex items-center gap-2 ml-auto flex-wrap">
            <label className="section-label">
              Entity
            </label>
            <select
              value={filterEntity}
              onChange={(e) => setFilterEntity(e.target.value)}
              className="h-9 rounded-md border border-input bg-background px-2 text-xs"
            >
              <option value="__all__">All entities</option>
              {hempEntities.map((o) => (
                <option key={o.slug} value={o.slug}>
                  {o.emoji} {o.name}
                </option>
              ))}
            </select>

            <label className="section-label">
              Type
            </label>
            <select
              value={filterType}
              onChange={(e) => setFilterType(e.target.value)}
              className="h-9 rounded-md border border-input bg-background px-2 text-xs"
            >
              <option value="__all__">All types</option>
              {LICENSE_TYPES.map((t) => (
                <option key={t} value={t}>
                  {t}
                </option>
              ))}
            </select>

            <Button
              size="sm"
              variant={showAdd ? "outline" : "brand"}
              onClick={() => setShowAdd((v) => !v)}
            >
              {showAdd ? "Cancel" : "+ Add license"}
            </Button>
          </div>
        </CardContent>
      </Card>

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

      <section className="space-y-2">
        <h2 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
          Hemp licenses
        </h2>
        {filteredLicenses.length === 0 ? (
          <EmptyState
            icon="🌿"
            title={licenses.length === 0 ? "No hemp licenses tracked yet" : "No licenses match the current filters"}
            description={
              licenses.length === 0
                ? "Click “+ Add license” to record one."
                : "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">Type</th>
                  <th className="px-3 py-2 text-left">License #</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">Locations</th>
                  <th className="px-3 py-2 text-left">THC test</th>
                  <th className="px-3 py-2 text-right">Actions</th>
                </tr>
              </thead>
              <tbody>
                {filteredLicenses.map((l) => {
                  const org = ALL_ORGANIZATIONS.find((o) => o.slug === l.entitySlug);
                  const d = daysUntil(l.expiresDate);
                  const isEditing = editingId === l.id;
                  let badge: React.ReactNode = null;
                  if (Number.isFinite(d)) {
                    if (d < 0) {
                      badge = (
                        <Badge variant="destructive">Expired {Math.abs(d)}d</Badge>
                      );
                    } else if (d < 30) {
                      badge = <Badge variant="destructive">{d}d left</Badge>;
                    } else if (d < 90) {
                      badge = <Badge variant="warning">{d}d left</Badge>;
                    }
                  }
                  return (
                    <tr
                      key={l.id}
                      className={`border-b last:border-0 ${
                        Number.isFinite(d) && d < 30 ? "bg-destructive/5" : ""
                      }`}
                    >
                      <td className="px-3 py-2">
                        <span className="inline-flex items-center gap-1">
                          {org?.emoji} {org?.name ?? l.entitySlug}
                        </span>
                      </td>
                      <td className="px-3 py-2">{l.licenseType}</td>
                      <td className="px-3 py-2 font-mono text-xs">
                        {l.licenseNumber || "—"}
                      </td>
                      <td className="px-3 py-2 font-mono text-xs">
                        {formatDateShort(l.issuedDate)}
                      </td>
                      <td className="px-3 py-2 font-mono text-xs">
                        <div className="flex items-center gap-2">
                          {formatDateShort(l.expiresDate)}
                          {badge}
                        </div>
                      </td>
                      <td className="px-3 py-2 text-xs max-w-[200px] truncate" title={l.growingLocations}>
                        {l.growingLocations || "—"}
                      </td>
                      <td className="px-3 py-2 text-xs">
                        <div className="font-medium">{l.thcTestSchedule}</div>
                        {l.thcTestNotes && (
                          <div className="text-muted-foreground text-[11px] truncate max-w-[180px]" title={l.thcTestNotes}>
                            {l.thcTestNotes}
                          </div>
                        )}
                      </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 : l.id)}
                          >
                            {isEditing ? "Close" : "Edit"}
                          </Button>
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => deleteLicense(l.id)}
                          >
                            ×
                          </Button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </section>

      {editingId &&
        (() => {
          const l = licenses.find((x) => x.id === editingId);
          if (!l) return null;
          return (
            <LicenseForm
              key={editingId}
              entities={entityOptions}
              defaultEntitySlug={l.entitySlug}
              initial={l}
              onSubmit={(data) => {
                updateLicense(editingId, data);
                setEditingId(null);
              }}
              onCancel={() => setEditingId(null)}
              submitLabel="Save license"
            />
          );
        })()}

      <p className="text-xs text-muted-foreground">
        Hemp licensing is administered by the NC Department of Agriculture &amp; Consumer
        Services. Per-license details are tracked locally in this browser.{" "}
        <a
          href="https://www.ncagr.gov/divisions/plant-industry/plant-protection/industrial-hemp"
          target="_blank"
          rel="noopener noreferrer"
          className="underline hover:text-foreground"
        >
          NCDA&amp;CS Industrial Hemp ↗
        </a>
      </p>
    </div>
    <AlertConfirmPortal />
    </>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Add / Edit License form
// ──────────────────────────────────────────────────────────────────────────

function LicenseForm({
  entities,
  defaultEntitySlug,
  initial,
  onSubmit,
  onCancel,
  submitLabel = "Add license",
}: {
  entities: typeof ALL_ORGANIZATIONS;
  defaultEntitySlug: string;
  initial?: HempLicense;
  onSubmit: (data: Omit<HempLicense, "id" | "updatedAt">) => void;
  onCancel: () => void;
  submitLabel?: string;
}) {
  const [entitySlug, setEntitySlug] = useState(initial?.entitySlug ?? defaultEntitySlug);
  const [licenseType, setLicenseType] = useState<HempLicenseType>(
    initial?.licenseType ?? "Industrial Hemp Grower"
  );
  const [licenseNumber, setLicenseNumber] = useState(initial?.licenseNumber ?? "");
  const [issuedDate, setIssuedDate] = useState(initial?.issuedDate ?? "");
  const [expiresDate, setExpiresDate] = useState(initial?.expiresDate ?? "");
  const [growingLocations, setGrowingLocations] = useState(
    initial?.growingLocations ?? ""
  );
  const [thcTestSchedule, setThcTestSchedule] = useState<HempThcTestSchedule>(
    initial?.thcTestSchedule ?? "Pre-harvest only"
  );
  const [thcTestNotes, setThcTestNotes] = useState(initial?.thcTestNotes ?? "");
  const [notes, setNotes] = useState(initial?.notes ?? "");

  function submit(e: React.FormEvent) {
    e.preventDefault();
    onSubmit({
      entitySlug,
      licenseType,
      licenseNumber: licenseNumber.trim(),
      issuedDate: issuedDate.trim(),
      expiresDate: expiresDate.trim(),
      growingLocations: growingLocations.trim(),
      thcTestSchedule,
      thcTestNotes: thcTestNotes.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="License type">
            <select
              value={licenseType}
              onChange={(e) => setLicenseType(e.target.value as HempLicenseType)}
              className="w-full h-10 rounded-md border border-input bg-background px-3 text-sm"
            >
              {LICENSE_TYPES.map((t) => (
                <option key={t} value={t}>
                  {t}
                </option>
              ))}
            </select>
          </Field>

          <Field label="License number">
            <Input
              value={licenseNumber}
              onChange={(e) => setLicenseNumber(e.target.value)}
              placeholder="e.g. NCDA-HMP-2024-00123"
            />
          </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="Growing / operating locations" className="md:col-span-3">
            <textarea
              value={growingLocations}
              onChange={(e) => setGrowingLocations(e.target.value)}
              className="w-full rounded-md border border-input bg-background p-2 text-sm"
              rows={2}
              placeholder="Comma-separated counties or street addresses (e.g. Chatham County — 123 Farm Rd; Lee County — 5 acres back lot)"
            />
          </Field>

          <Field label="THC test schedule">
            <select
              value={thcTestSchedule}
              onChange={(e) =>
                setThcTestSchedule(e.target.value as HempThcTestSchedule)
              }
              className="w-full h-10 rounded-md border border-input bg-background px-3 text-sm"
            >
              {THC_TEST_SCHEDULES.map((s) => (
                <option key={s} value={s}>
                  {s}
                </option>
              ))}
            </select>
          </Field>
          <Field label="THC test notes" className="md:col-span-2">
            <Input
              value={thcTestNotes}
              onChange={(e) => setThcTestNotes(e.target.value)}
              placeholder="Last lab name / contact / last test date / result"
            />
          </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="Renewal contact, fee paid, USDA program ID, audit reminders, 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>
  );
}

