"use client";

import { useEffect, useMemo, useRef, 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 { Input } from "@/components/ui/input";
import { Progress } from "@/components/ui/progress";
import { Kpi, KpiStrip } from "@/components/ui/kpi";
import { EmptyState } from "@/components/ui/empty-state";
import { useAlertConfirm } from "@/components/ui/alert-dialog";
import { useToast } from "@/components/ui/toast";
import { useLocalStorage } from "@/lib/hooks/use-local-storage";
import {
  ONBOARDING_ITEMS,
  type CompType,
  type Employee,
  type EmploymentStatus,
} from "@/lib/sag/employees-seed";
import { ALL_ORGANIZATIONS } from "@/lib/sag/entities";
import { formatCurrency, formatDate } from "@/lib/utils";
import { snapshotForAgentCall } from "@/lib/agents/context-snapshot";
import {
  markOfferLetterSigned,
  saveOfferLetterToDocs,
} from "@/lib/docs/save-offer-letter";
import { logActivity } from "@/lib/activity/log";

export function HrDirectory() {
  const { toast } = useToast();
  const [employees, setEmployees] = useLocalStorage<Employee[]>("sag.hr.employees", []);
  const [showAdd, setShowAdd] = useState(false);
  const [filterEntity, setFilterEntity] = useState<string>("all");
  const [filterStatus, setFilterStatus] = useState<"all" | EmploymentStatus>("Active");
  const [expandedId, setExpandedId] = useState<string | null>(null);
  const [drafting, setDrafting] = useState<string | null>(null);
  const [drafts, setDrafts] = useLocalStorage<Record<string, string>>("sag.hr.drafts", {});
  // Per-employee tracking of the saved offer-letter doc id + signed state.
  // Persisted so a reload doesn't re-enable "Save to docs" on a draft that
  // already lives in the docs vault.
  const [savedLetters, setSavedLetters] = useLocalStorage<
    Record<string, { docId: string; signedAt?: string }>
  >("sag.hr.offerLetters.saved", {});
  const [justSavedId, setJustSavedId] = useState<string | null>(null);
  const justSavedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const { confirm: confirmAlert, AlertConfirmPortal } = useAlertConfirm();

  useEffect(() => {
    return () => {
      if (justSavedTimerRef.current) clearTimeout(justSavedTimerRef.current);
    };
  }, []);

  const filtered = useMemo(() => {
    return employees.filter((e) => {
      if (filterEntity !== "all" && e.organizationSlug !== filterEntity) return false;
      if (filterStatus !== "all" && e.status !== filterStatus) return false;
      return true;
    });
  }, [employees, filterEntity, filterStatus]);

  function addEmployee(e: Omit<Employee, "id">) {
    setEmployees([{ ...e, id: `emp-${Date.now()}` }, ...employees]);
    setShowAdd(false);
    try {
      logActivity({
        source: "hr",
        verb: "created",
        title: `Added employee ${e.fullName}`,
        entitySlug: e.organizationSlug,
        href: "/app/hr",
        meta: { role: e.role, status: e.status },
      });
    } catch {
      // fire-and-forget
    }
  }

  function updateEmployee(id: string, patch: Partial<Employee>) {
    setEmployees(employees.map((e) => (e.id === id ? { ...e, ...patch } : e)));
  }

  async function deleteEmployee(id: string) {
    const ok = await confirmAlert({
      title: "Delete this employee record?",
      description: "This permanently removes the record. Cannot be undone.",
      actionLabel: "Delete",
      destructive: true,
    });
    if (!ok) return;
    const target = employees.find((e) => e.id === id);
    setEmployees(employees.filter((e) => e.id !== id));
    if (expandedId === id) setExpandedId(null);
    try {
      if (target) {
        logActivity({
          source: "hr",
          verb: "deleted",
          title: `Deleted employee ${target.fullName}`,
          entitySlug: target.organizationSlug,
          href: "/app/hr",
          meta: { role: target.role },
        });
      }
    } catch {
      // fire-and-forget
    }
  }

  function toggleOnboard(employeeId: string, itemId: string) {
    const e = employees.find((x) => x.id === employeeId);
    if (!e) return;
    const onb = { ...(e.onboarding ?? {}), [itemId]: !(e.onboarding?.[itemId] ?? false) };
    updateEmployee(employeeId, { onboarding: onb });
  }

  async function generateOfferLetter(e: Employee) {
    setDrafting(e.id);
    try {
      const org = ALL_ORGANIZATIONS.find((o) => o.slug === e.organizationSlug);
      const prompt = `Draft a North Carolina employment offer letter.

Employer: ${org?.name ?? e.organizationSlug} (a subsidiary of South Armz Global, LLC).
Position: ${e.role}
Candidate: ${e.fullName}
Start date: ${e.startDate ?? "TBD"}
Compensation: ${e.compType === "salary" ? `$${e.compAmount?.toLocaleString()} annual salary` : e.compType === "hourly" ? `$${e.compAmount}/hour` : e.compType === "commission" ? `commission-based, base ${e.compAmount ?? "TBD"}` : "see notes"}
Notes: ${e.notes ?? "none"}

Format: a complete, signable offer letter. Include: greeting, position + reporting line, comp details, benefits eligibility note (placeholder if unknown), at-will employment language (NC is an at-will state), contingencies (background check, I-9), start date, signature block. ~300-450 words.`;
      const resp = await fetch("/api/agents/hr", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          messages: [{ role: "user", content: prompt }],
          contextSnapshot: snapshotForAgentCall(),
        }),
      });
      const data = await resp.json();
      if (!resp.ok) throw new Error(data.error || "Generation failed");
      setDrafts({ ...drafts, [e.id]: data.message });
      // A regenerate invalidates the prior save — the new body needs to
      // be re-saved before "Saved to docs" applies.
      if (savedLetters[e.id]) {
        setSavedLetters((prev) => {
          const next = { ...prev };
          delete next[e.id];
          return next;
        });
      }
    } catch (err) {
      alert("Offer letter failed: " + (err instanceof Error ? err.message : "unknown"));
    } finally {
      setDrafting(null);
    }
  }

  function handleSaveOfferLetter(e: Employee, draft: string) {
    if (savedLetters[e.id]) return;
    try {
      const doc = saveOfferLetterToDocs(
        {
          body: draft,
          generatedAt: new Date().toISOString(),
          agentModel: "hr-agent",
          metadata: {
            role: e.role,
            startDate: e.startDate,
            salary:
              e.compType === "salary" || e.compType === "hourly"
                ? e.compAmount
                : undefined,
          },
        },
        {
          name: e.fullName,
          role: e.role,
          entitySlug: e.organizationSlug,
        },
      );
      setSavedLetters((prev) => ({ ...prev, [e.id]: { docId: doc.id } }));
      setJustSavedId(e.id);
      if (justSavedTimerRef.current) clearTimeout(justSavedTimerRef.current);
      justSavedTimerRef.current = setTimeout(() => {
        setJustSavedId((current) => (current === e.id ? null : current));
        justSavedTimerRef.current = null;
      }, 5000);
      toast({
        title: "Saved to docs vault",
        description: `${e.fullName}'s offer letter is now in the docs vault.`,
        variant: "success",
      });
    } catch (err) {
      alert(
        "Save to docs failed: " +
          (err instanceof Error ? err.message : "unknown"),
      );
    }
  }

  function handleMarkSigned(employeeId: string) {
    const entry = savedLetters[employeeId];
    if (!entry) return;
    if (entry.signedAt) return;
    const signedAt = new Date().toISOString();
    const updated = markOfferLetterSigned(entry.docId, signedAt);
    if (!updated) {
      alert("Couldn't find the saved letter in the docs vault.");
      return;
    }
    setSavedLetters((prev) => ({
      ...prev,
      [employeeId]: { docId: entry.docId, signedAt },
    }));
  }

  const stats = {
    total: employees.length,
    active: employees.filter((e) => e.status === "Active").length,
    onLeave: employees.filter((e) => e.status === "On Leave").length,
  };

  return (
    <>
    <div className="space-y-6">
      <KpiStrip cols={3}>
        <Kpi label="Headcount" value={String(stats.total)} />
        <Kpi label="Active" value={String(stats.active)} tone="emerald" />
        <Kpi label="On leave" value={String(stats.onLeave)} />
      </KpiStrip>

      <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" | EmploymentStatus)}
            className="h-10 rounded-md border border-input bg-background px-3 text-sm"
          >
            <option value="all">All</option>
            <option value="Active">Active</option>
            <option value="On Leave">On Leave</option>
            <option value="Terminated">Terminated</option>
          </select>
          <span className="text-xs text-muted-foreground tabular-nums">
            {filtered.length} of {employees.length}
          </span>
          <Button variant="brand" size="sm" className="ml-auto" onClick={() => setShowAdd((v) => !v)}>
            {showAdd ? "Cancel" : "+ Add employee"}
          </Button>
        </CardContent>
      </Card>

      {showAdd && <AddEmployeeForm onAdd={addEmployee} onCancel={() => setShowAdd(false)} />}

      {filtered.length === 0 ? (
        <EmptyState
          icon="👥"
          title="No employees yet"
          description="Add your first hire — onboarding checklist + offer letter generator auto-attach."
        />
      ) : (
        <div className="space-y-3">
          {filtered.map((e) => {
            const org = ALL_ORGANIZATIONS.find((o) => o.slug === e.organizationSlug);
            const isExpanded = expandedId === e.id;
            const done = Object.values(e.onboarding ?? {}).filter(Boolean).length;
            const pct = Math.round((done / ONBOARDING_ITEMS.length) * 100);
            const draft = drafts[e.id];

            return (
              <Card key={e.id}>
                <CardContent className="p-5">
                  <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 mb-1">
                        <Badge variant={e.status === "Active" ? "success" : e.status === "On Leave" ? "warning" : "outline"}>
                          {e.status}
                        </Badge>
                        <span className="text-xs text-muted-foreground inline-flex items-center gap-1">
                          {org?.emoji ?? "🏢"} {org?.name ?? e.organizationSlug}
                        </span>
                      </div>
                      <h3 className="text-base font-semibold">{e.fullName}</h3>
                      <div className="text-sm text-muted-foreground">{e.role}</div>
                      <div className="mt-2 text-xs text-muted-foreground space-x-3">
                        {e.email && <span>{e.email}</span>}
                        {e.phone && <span>{e.phone}</span>}
                        {e.startDate && <span>Started {formatDate(e.startDate)}</span>}
                        {e.compType && e.compAmount != null && (
                          <span>
                            {e.compType === "salary"
                              ? `${formatCurrency(e.compAmount)}/yr`
                              : e.compType === "hourly"
                              ? `${formatCurrency(e.compAmount)}/hr`
                              : `${formatCurrency(e.compAmount)} (${e.compType})`}
                          </span>
                        )}
                      </div>
                    </div>
                    <div className="flex items-center gap-2 shrink-0">
                      <div className="text-right">
                        <div className="section-label">Onboarding</div>
                        <div className="text-sm font-medium tabular-nums">{pct}%</div>
                      </div>
                      <Button variant="ghost" size="sm" onClick={() => setExpandedId(isExpanded ? null : e.id)}>
                        {isExpanded ? "Close" : "Details"}
                      </Button>
                      <Button variant="ghost" size="sm" onClick={() => deleteEmployee(e.id)}>×</Button>
                    </div>
                  </div>
                  {isExpanded && (
                    <div className="mt-5 grid lg:grid-cols-2 gap-5">
                      <div>
                        <h4 className="text-sm font-semibold mb-2">Onboarding checklist</h4>
                        <Progress value={pct} className="mb-3" />
                        <ul className="space-y-1.5">
                          {ONBOARDING_ITEMS.map((item) => {
                            const checked = e.onboarding?.[item.id] ?? false;
                            return (
                              <li key={item.id} className="flex items-center gap-2 text-sm">
                                <input
                                  type="checkbox"
                                  checked={checked}
                                  onChange={() => toggleOnboard(e.id, item.id)}
                                />
                                <span className={checked ? "line-through text-muted-foreground" : ""}>
                                  {item.label}
                                </span>
                                <span className="ml-auto text-[10px] text-muted-foreground">{item.category}</span>
                              </li>
                            );
                          })}
                        </ul>
                      </div>
                      <div>
                        <div className="flex items-center justify-between mb-2">
                          <h4 className="text-sm font-semibold">Offer letter</h4>
                          <Button
                            size="sm"
                            variant="brand"
                            disabled={drafting === e.id}
                            onClick={() => generateOfferLetter(e)}
                          >
                            {drafting === e.id ? "Drafting..." : draft ? "Regenerate" : "Generate via HR Agent"}
                          </Button>
                        </div>
                        {draft ? (
                          <>
                            <pre className="whitespace-pre-wrap text-xs bg-muted p-3 rounded-md max-h-96 overflow-y-auto">
                              {draft}
                            </pre>
                            {(() => {
                              const savedEntry = savedLetters[e.id];
                              const isSaved = Boolean(savedEntry);
                              const isSigned = Boolean(savedEntry?.signedAt);
                              const justSaved = justSavedId === e.id;
                              const savedLabel = isSigned
                                ? "Saved (Signed)"
                                : isSaved
                                ? "Saved (Draft)"
                                : "Save to docs";
                              return (
                                <div className="mt-3 flex items-center gap-2 flex-wrap">
                                  <Button
                                    variant="outline"
                                    size="sm"
                                    disabled={isSaved}
                                    onClick={() => handleSaveOfferLetter(e, draft)}
                                  >
                                    {savedLabel}
                                  </Button>
                                  {isSaved && !isSigned && (
                                    <Button
                                      variant="brand"
                                      size="sm"
                                      onClick={() => handleMarkSigned(e.id)}
                                    >
                                      Mark signed
                                    </Button>
                                  )}
                                  {justSaved && (
                                    <Badge variant="success" className="text-[10px]">
                                      Saved to docs vault
                                    </Badge>
                                  )}
                                  {justSaved && (
                                    <Link
                                      href={`/app/docs?entity=${encodeURIComponent(e.organizationSlug)}`}
                                      className="text-[11px] text-muted-foreground underline hover:text-foreground"
                                    >
                                      View in docs
                                    </Link>
                                  )}
                                  {isSigned && savedEntry?.signedAt && (
                                    <span className="text-[11px] text-muted-foreground">
                                      Signed {formatDate(savedEntry.signedAt)}
                                    </span>
                                  )}
                                </div>
                              );
                            })()}
                          </>
                        ) : (
                          <p className="text-xs text-muted-foreground">
                            Click Generate to ask the HR Agent for a complete NC-compliant offer letter draft using this employee’s details.
                          </p>
                        )}
                      </div>
                    </div>
                  )}
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}
    </div>
    <AlertConfirmPortal />
    </>
  );
}

function AddEmployeeForm({ onAdd, onCancel }: { onAdd: (e: Omit<Employee, "id">) => void; onCancel: () => void }) {
  const [form, setForm] = useState<Omit<Employee, "id">>({
    organizationSlug: ALL_ORGANIZATIONS[0]?.slug ?? "south-armz-global",
    fullName: "",
    role: "",
    status: "Active",
  });

  function submit(ev: React.FormEvent) {
    ev.preventDefault();
    if (!form.fullName.trim() || !form.role.trim()) return;
    onAdd(form);
  }

  return (
    <Card>
      <CardContent className="p-6">
        <form onSubmit={submit} className="grid gap-3 md:grid-cols-2">
          <Field label="Full name">
            <Input value={form.fullName} onChange={(e) => setForm({ ...form, fullName: e.target.value })} required />
          </Field>
          <Field label="Role">
            <Input value={form.role} onChange={(e) => setForm({ ...form, role: e.target.value })} placeholder="e.g. Bartender, Manager" required />
          </Field>
          <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="Status">
            <select
              value={form.status}
              onChange={(e) => setForm({ ...form, status: e.target.value as EmploymentStatus })}
              className="w-full h-10 rounded-md border border-input bg-background px-3 text-sm"
            >
              <option value="Active">Active</option>
              <option value="On Leave">On Leave</option>
              <option value="Terminated">Terminated</option>
            </select>
          </Field>
          <Field label="Email">
            <Input type="email" value={form.email ?? ""} onChange={(e) => setForm({ ...form, email: e.target.value })} />
          </Field>
          <Field label="Phone">
            <Input value={form.phone ?? ""} onChange={(e) => setForm({ ...form, phone: e.target.value })} />
          </Field>
          <Field label="Start date">
            <Input type="date" value={form.startDate ?? ""} onChange={(e) => setForm({ ...form, startDate: e.target.value })} />
          </Field>
          <Field label="Comp type">
            <select
              value={form.compType ?? ""}
              onChange={(e) => setForm({ ...form, compType: (e.target.value || undefined) as CompType | undefined })}
              className="w-full h-10 rounded-md border border-input bg-background px-3 text-sm"
            >
              <option value="">—</option>
              <option value="salary">Salary (annual)</option>
              <option value="hourly">Hourly</option>
              <option value="commission">Commission</option>
              <option value="equity">Equity</option>
              <option value="other">Other</option>
            </select>
          </Field>
          <Field label="Comp amount">
            <Input
              type="number"
              step="0.01"
              value={form.compAmount ?? ""}
              onChange={(e) => setForm({ ...form, compAmount: parseFloat(e.target.value) || undefined })}
            />
          </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" type="button" onClick={onCancel}>Cancel</Button>
            <Button variant="brand" size="sm" type="submit">Add employee</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>
  );
}

