"use client";

import { useEffect, 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 { EmptyState } from "@/components/ui/empty-state";
import { Skeleton } from "@/components/ui/skeleton";
import { useAlertConfirm } from "@/components/ui/alert-dialog";
import { useToast } from "@/components/ui/toast";
import {
  loadOwnerDraws,
  saveOwnerDraw,
  deleteOwnerDraw,
  getTotalForMonth,
  getTotalForYear,
  getTotalTtm,
  OWNER_DRAWS_STORAGE_KEY,
  type OwnerDraw,
} from "@/lib/income/owner-draws";
import { ALL_ORGANIZATIONS } from "@/lib/sag/entities";
import { formatCurrency, formatDate } from "@/lib/utils";
import { logActivity } from "@/lib/activity/log";

const METHOD_OPTIONS = [
  "Owner distribution",
  "Salary advance",
  "Reimbursement",
  "Other",
] as const;

type Method = (typeof METHOD_OPTIONS)[number];

interface DraftState {
  date: string;
  amount: string;
  fromEntitySlug: string;
  method: Method;
  note: string;
}

function todayIso(): string {
  const now = new Date();
  return new Date(
    Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()),
  )
    .toISOString()
    .slice(0, 10);
}

function currentYearMonth(): string {
  const now = new Date();
  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`;
}

function emptyDraft(): DraftState {
  return {
    date: todayIso(),
    amount: "",
    fromEntitySlug: "",
    method: "Owner distribution",
    note: "",
  };
}

function newDrawId(): string {
  if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
    return `draw-${crypto.randomUUID()}`;
  }
  return `draw-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
}

/**
 * Owner-draw log — feeds the personal cash-flow rollup.
 *
 * Reads/writes `sag.income.owner_draws`. Each entry carries date, amount, and
 * the SAG entity it came from, so the personal cash-flow aggregator can build
 * real monthly numbers for the "Draws" row.
 */
export function OwnerDrawsLog() {
  const [loaded, setLoaded] = useState(false);
  const [draws, setDraws] = useState<OwnerDraw[]>([]);
  const [draft, setDraft] = useState<DraftState>(() => emptyDraft());
  const [editingId, setEditingId] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [filterSlug, setFilterSlug] = useState<string>("");
  const { toast } = useToast();
  const { confirm, AlertConfirmPortal } = useAlertConfirm();

  // Hydrate from localStorage on mount + react to cross-tab writes.
  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect -- one-time hydration from localStorage
    setDraws(loadOwnerDraws());
    setLoaded(true);

    function onStorage(e: StorageEvent) {
      if (e.key === OWNER_DRAWS_STORAGE_KEY) {
        setDraws(loadOwnerDraws());
      }
    }
    window.addEventListener("storage", onStorage);
    return () => window.removeEventListener("storage", onStorage);
  }, []);

  // Entity dropdown options (ALL_ORGANIZATIONS sorted by name).
  const entityOptions = useMemo(() => {
    return [...ALL_ORGANIZATIONS]
      .map((o) => ({
        slug: o.slug,
        label: o.emoji ? `${o.emoji} ${o.name}` : o.name,
      }))
      .sort((a, b) => a.label.localeCompare(b.label));
  }, []);

  function entityLabel(slug: string): string {
    const org = ALL_ORGANIZATIONS.find((o) => o.slug === slug);
    if (!org) return slug;
    return org.emoji ? `${org.emoji} ${org.name}` : org.name;
  }

  // Filtered, sorted display list (already newest-first from the helper).
  const visibleDraws = useMemo(() => {
    if (!filterSlug) return draws;
    return draws.filter((d) => d.fromEntitySlug === filterSlug);
  }, [draws, filterSlug]);

  // KPI numbers — recomputed when draws change. Using helper for parity with
  // any consumer (e.g. personal cash-flow) that calls the helpers directly.
  const kpis = useMemo(() => {
    if (!loaded) {
      return { ttm: 0, ytd: 0, month: 0, count: 0 };
    }
    return {
      ttm: getTotalTtm(),
      ytd: getTotalForYear(new Date().getFullYear()),
      month: getTotalForMonth(currentYearMonth()),
      count: draws.length,
    };
    // We intentionally depend on `draws` so the helpers re-run after writes.
  }, [draws, loaded]);

  function resetDraft() {
    setDraft(emptyDraft());
    setEditingId(null);
    setError(null);
  }

  function beginEdit(d: OwnerDraw) {
    setEditingId(d.id);
    setError(null);
    setDraft({
      date: d.date,
      amount: String(d.amount),
      fromEntitySlug: d.fromEntitySlug,
      method: (METHOD_OPTIONS as readonly string[]).includes(d.method ?? "")
        ? (d.method as Method)
        : "Other",
      note: d.note ?? "",
    });
  }

  function handleSave() {
    setError(null);
    const amount = Number(draft.amount);
    if (!/^\d{4}-\d{2}-\d{2}$/.test(draft.date)) {
      setError("Pick a valid date (YYYY-MM-DD).");
      return;
    }
    if (!Number.isFinite(amount) || amount <= 0) {
      setError("Amount must be a positive number.");
      return;
    }
    if (!draft.fromEntitySlug) {
      setError("Pick the SAG entity this draw came from.");
      return;
    }

    const isEdit = editingId !== null;
    const existing = isEdit ? draws.find((d) => d.id === editingId) : null;
    const next: OwnerDraw = {
      id: isEdit && existing ? existing.id : newDrawId(),
      date: draft.date,
      amount,
      fromEntitySlug: draft.fromEntitySlug,
      method: draft.method,
      note: draft.note.trim() ? draft.note.trim() : undefined,
      createdAt: isEdit && existing ? existing.createdAt : new Date().toISOString(),
    };

    const updated = saveOwnerDraw(next);
    setDraws(updated);
    toast({
      title: isEdit ? "Draw updated" : "Draw logged",
      description: `${formatCurrency(amount)} from ${entityLabel(next.fromEntitySlug)} on ${formatDate(next.date)}`,
      variant: "success",
    });
    try {
      logActivity({
        source: "owner-draws",
        verb: isEdit ? "updated" : "created",
        title: isEdit
          ? `Updated owner draw on ${next.date}`
          : `Logged owner draw on ${next.date}`,
        entitySlug: next.fromEntitySlug,
        amount: next.amount,
        href: "/app/income",
        meta: { method: next.method },
      });
    } catch {
      // fire-and-forget
    }
    resetDraft();
  }

  async function handleDelete(d: OwnerDraw) {
    const ok = await confirm({
      title: "Delete this owner draw?",
      description: `${formatCurrency(d.amount)} from ${entityLabel(d.fromEntitySlug)} on ${formatDate(d.date)}. This cannot be undone.`,
      actionLabel: "Delete",
      destructive: true,
    });
    if (!ok) return;
    const updated = deleteOwnerDraw(d.id);
    setDraws(updated);
    if (editingId === d.id) resetDraft();
    toast({
      title: "Draw deleted",
      description: `${formatCurrency(d.amount)} on ${formatDate(d.date)} removed.`,
      variant: "info",
    });
    try {
      logActivity({
        source: "owner-draws",
        verb: "deleted",
        title: `Deleted owner draw on ${d.date}`,
        entitySlug: d.fromEntitySlug,
        amount: d.amount,
        href: "/app/income",
      });
    } catch {
      // fire-and-forget
    }
  }

  // First server render + first client render before useEffect: show skeleton.
  if (!loaded) {
    return (
      <Card>
        <CardContent className="p-6 space-y-4">
          <h2 className="text-base font-semibold">Owner draws</h2>
          <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
            {Array.from({ length: 4 }).map((_, i) => (
              <Skeleton key={i} className="h-20" />
            ))}
          </div>
          <Skeleton className="h-32" />
        </CardContent>
      </Card>
    );
  }

  return (
    <Card>
      <CardContent className="p-6 space-y-6">
        {/* Header */}
        <div>
          <h2 className="text-base font-semibold">Owner draws</h2>
          <p className="mt-1 text-xs text-muted-foreground max-w-2xl">
            Track owner draws across SAG entities. Used by the personal
            cash-flow rollup.
          </p>
        </div>

        {/* KPI strip */}
        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
          <Kpi
            label="TTM total"
            value={formatCurrency(kpis.ttm)}
            hint="Trailing 12 months"
            tone="success"
          />
          <Kpi
            label={`YTD ${new Date().getFullYear()}`}
            value={formatCurrency(kpis.ytd)}
            hint="Calendar year to date"
          />
          <Kpi
            label="This month"
            value={formatCurrency(kpis.month)}
            hint={currentYearMonth()}
          />
          <Kpi
            label="Count"
            value={String(kpis.count)}
            hint={kpis.count === 1 ? "draw logged" : "draws logged"}
          />
        </div>

        {/* Inline add/edit form */}
        <div className="rounded-md border bg-muted/20 p-4 space-y-3">
          <div className="flex items-center justify-between flex-wrap gap-2">
            <h3 className="text-sm font-semibold">
              {editingId ? "Edit draw" : "Add draw"}
            </h3>
            {editingId && (
              <Badge variant="info" className="text-[10px]">
                Editing
              </Badge>
            )}
          </div>

          <div className="grid gap-3 md:grid-cols-2 lg:grid-cols-5">
            <Field label="Date">
              <Input
                type="date"
                value={draft.date}
                onChange={(e) => setDraft({ ...draft, date: e.target.value })}
              />
            </Field>
            <Field label="Amount">
              <Input
                type="number"
                min="0"
                step="0.01"
                value={draft.amount}
                onChange={(e) => setDraft({ ...draft, amount: e.target.value })}
                placeholder="0.00"
              />
            </Field>
            <Field label="From entity">
              <select
                value={draft.fromEntitySlug}
                onChange={(e) =>
                  setDraft({ ...draft, fromEntitySlug: e.target.value })
                }
                className="w-full h-10 rounded-md border border-input bg-background px-3 text-sm"
              >
                <option value="">— Pick an entity —</option>
                {entityOptions.map((opt) => (
                  <option key={opt.slug} value={opt.slug}>
                    {opt.label}
                  </option>
                ))}
              </select>
            </Field>
            <Field label="Method">
              <select
                value={draft.method}
                onChange={(e) =>
                  setDraft({ ...draft, method: e.target.value as Method })
                }
                className="w-full h-10 rounded-md border border-input bg-background px-3 text-sm"
              >
                {METHOD_OPTIONS.map((m) => (
                  <option key={m} value={m}>
                    {m}
                  </option>
                ))}
              </select>
            </Field>
            <Field label="Note (optional)">
              <Input
                value={draft.note}
                onChange={(e) => setDraft({ ...draft, note: e.target.value })}
                placeholder="e.g. Q1 partner payout"
              />
            </Field>
          </div>

          {error && (
            <div className="rounded-md border border-destructive/40 bg-destructive/5 px-3 py-2 text-sm text-destructive">
              {error}
            </div>
          )}

          <div className="flex justify-end gap-2">
            {editingId && (
              <Button variant="ghost" size="sm" onClick={resetDraft}>
                Cancel
              </Button>
            )}
            <Button variant="brand" size="sm" onClick={handleSave}>
              {editingId ? "Save changes" : "Add draw"}
            </Button>
          </div>
        </div>

        {/* Filter + table */}
        {draws.length === 0 ? (
          <EmptyState
            icon="💵"
            size="compact"
            title="No draws logged yet"
            description="Use the form above to record your first owner draw. Each entry feeds the personal cash-flow rollup."
          />
        ) : (
          <div className="space-y-3">
            <div className="flex items-center justify-between flex-wrap gap-2">
              <h3 className="text-sm font-semibold">Logged draws</h3>
              <div className="flex items-center gap-2">
                <label htmlFor="owner-draws-filter" className="section-label">
                  Filter by entity
                </label>
                <select
                  id="owner-draws-filter"
                  value={filterSlug}
                  onChange={(e) => setFilterSlug(e.target.value)}
                  className="h-9 rounded-md border border-input bg-background px-2 text-xs"
                >
                  <option value="">All entities</option>
                  {entityOptions.map((opt) => (
                    <option key={opt.slug} value={opt.slug}>
                      {opt.label}
                    </option>
                  ))}
                </select>
              </div>
            </div>

            {visibleDraws.length === 0 ? (
              <p className="text-xs text-muted-foreground italic">
                No draws match this filter.
              </p>
            ) : (
              <div className="rounded-md border bg-background overflow-x-auto">
                <table className="w-full min-w-[640px] text-sm">
                  <thead className="section-label border-b bg-muted/20">
                    <tr>
                      <th className="px-3 py-2 text-left font-medium">Date</th>
                      <th className="px-3 py-2 text-left font-medium">From</th>
                      <th className="px-3 py-2 text-right font-medium">
                        Amount
                      </th>
                      <th className="px-3 py-2 text-left font-medium">Method</th>
                      <th className="px-3 py-2 text-left font-medium">Note</th>
                      <th className="px-3 py-2 text-right font-medium w-28">
                        Actions
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {visibleDraws.map((d) => (
                      <tr
                        key={d.id}
                        className="border-b last:border-0 hover:bg-muted/10 align-middle"
                      >
                        <td className="px-3 py-2 font-mono text-xs whitespace-nowrap">
                          {d.date}
                        </td>
                        <td className="px-3 py-2 text-xs">
                          {entityLabel(d.fromEntitySlug)}
                        </td>
                        <td className="px-3 py-2 text-right tabular-nums text-emerald-700 dark:text-emerald-400 font-medium">
                          {formatCurrency(d.amount)}
                        </td>
                        <td className="px-3 py-2 text-xs">{d.method ?? "—"}</td>
                        <td className="px-3 py-2 text-xs text-muted-foreground">
                          {d.note ?? "—"}
                        </td>
                        <td className="px-3 py-2 text-right whitespace-nowrap">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => beginEdit(d)}
                            aria-label={`Edit draw on ${d.date}`}
                          >
                            Edit
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleDelete(d)}
                            aria-label={`Delete draw on ${d.date}`}
                          >
                            Delete
                          </Button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        )}
        <AlertConfirmPortal />
      </CardContent>
    </Card>
  );
}

function Kpi({
  label,
  value,
  hint,
  tone = "default",
}: {
  label: string;
  value: string;
  hint?: string;
  tone?: "default" | "success";
}) {
  const colorClass =
    tone === "success"
      ? "text-green-700 dark:text-green-400"
      : "text-foreground";
  return (
    <div className="rounded-md border bg-background p-4">
      <div className="section-label">{label}</div>
      <div className={`mt-1 text-xl font-semibold tabular-nums ${colorClass}`}>
        {value}
      </div>
      {hint && (
        <div className="mt-0.5 text-[10px] text-muted-foreground">{hint}</div>
      )}
    </div>
  );
}

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