"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 { useLocalStorage } from "@/lib/hooks/use-local-storage";
import {
  ALL_ORGANIZATIONS,
  EXTERNAL_EMPLOYERS,
  getPayrollSources,
} from "@/lib/sag/entities";
import { formatCurrency, formatDate } from "@/lib/utils";

type PayCadence = "weekly" | "biweekly" | "semimonthly" | "monthly" | "irregular";

const CADENCE_LABEL: Record<PayCadence, string> = {
  weekly: "Weekly",
  biweekly: "Bi-weekly",
  semimonthly: "Semi-monthly",
  monthly: "Monthly",
  irregular: "Irregular",
};

interface Paystub {
  id: string;
  date: string; // YYYY-MM-DD
  gross: number;
  net?: number;
  hours?: number;
  notes?: string;
}

interface IncomeSource {
  id: string;
  /** Slug from ALL_ORGANIZATIONS — covers external employers + SAG subsidiaries. */
  employerSlug: string;
  role?: string;
  cadence: PayCadence;
  payRate?: number;
  startedAt?: string;
  notes?: string;
  paystubs: Paystub[];
}

export function IncomeBoard() {
  const [sources, setSources] = useLocalStorage<IncomeSource[]>("sag.income.sources", []);
  const [addingFor, setAddingFor] = useState<string | null>(null);
  const [showAddSource, setShowAddSource] = useState(false);

  const currentYear = new Date().getFullYear();

  const suggestedSlugs = useMemo(() => {
    const haveSlugs = new Set(sources.map((s) => s.employerSlug));
    return getPayrollSources()
      .filter((p) => !haveSlugs.has(p.slug))
      .map((p) => p.slug);
  }, [sources]);

  const ytdGross = useMemo(() => {
    let total = 0;
    for (const s of sources) {
      for (const p of s.paystubs) {
        if (p.date.startsWith(String(currentYear))) total += p.gross;
      }
    }
    return total;
  }, [sources, currentYear]);

  function addSource(slug: string) {
    setSources((prev) => [
      ...prev,
      {
        id: `src-${Date.now()}`,
        employerSlug: slug,
        cadence: "biweekly",
        paystubs: [],
      },
    ]);
    setShowAddSource(false);
  }

  function updateSource(id: string, patch: Partial<IncomeSource>) {
    setSources(sources.map((s) => (s.id === id ? { ...s, ...patch } : s)));
  }

  function removeSource(id: string) {
    if (!confirm("Remove this income source and all its paystubs?")) return;
    setSources(sources.filter((s) => s.id !== id));
  }

  function addPaystub(sourceId: string, stub: Omit<Paystub, "id">) {
    setSources(
      sources.map((s) =>
        s.id === sourceId
          ? {
              ...s,
              paystubs: [
                ...s.paystubs,
                { ...stub, id: `stub-${Date.now()}-${Math.random().toString(36).slice(2, 6)}` },
              ].sort((a, b) => b.date.localeCompare(a.date)),
            }
          : s
      )
    );
    setAddingFor(null);
  }

  function removePaystub(sourceId: string, stubId: string) {
    setSources(
      sources.map((s) =>
        s.id === sourceId ? { ...s, paystubs: s.paystubs.filter((p) => p.id !== stubId) } : s
      )
    );
  }

  return (
    <div className="space-y-6 max-w-5xl">
      <Card>
        <CardContent className="p-6">
          <h2 className="text-base font-semibold">Personal W-2 income</h2>
          <p className="mt-2 text-sm text-foreground/85 max-w-3xl">
            Glenn’s paychecks from outside employers + any SAG subsidiary he draws payroll from.
            Separate from SAG’s holding-company cash flow. Use it to back into personal cash
            position, tax withholding, and an annual income picture across all employers.
          </p>
          <div className="mt-4 flex flex-wrap gap-3">
            <Stat label={`YTD gross ${currentYear}`} value={formatCurrency(ytdGross)} tone="success" />
            <Stat label="Active sources" value={String(sources.length)} />
            <Stat
              label="Paystubs logged"
              value={String(sources.reduce((a, s) => a + s.paystubs.length, 0))}
            />
          </div>
        </CardContent>
      </Card>

      {suggestedSlugs.length > 0 && (
        <Card className="border-dashed">
          <CardContent className="p-5">
            <h3 className="text-base font-semibold">Suggested employers</h3>
            <p className="mt-1 text-sm text-muted-foreground">
              Known payroll relationships not yet tracked here.
            </p>
            <div className="mt-3 flex flex-wrap gap-2">
              {suggestedSlugs.map((slug) => {
                const org = ALL_ORGANIZATIONS.find((o) => o.slug === slug);
                if (!org) return null;
                return (
                  <Button
                    key={slug}
                    variant="outline"
                    size="sm"
                    onClick={() => addSource(slug)}
                  >
                    + {org.emoji} {org.name}
                  </Button>
                );
              })}
            </div>
          </CardContent>
        </Card>
      )}

      <Card>
        <CardContent className="p-4 flex items-center justify-between flex-wrap gap-2">
          <div className="text-sm text-muted-foreground">
            Add any other employer — external or SAG-internal — that pays you a W-2.
          </div>
          <Button variant="brand" size="sm" onClick={() => setShowAddSource((v) => !v)}>
            {showAddSource ? "Cancel" : "+ Add income source"}
          </Button>
        </CardContent>
      </Card>

      {showAddSource && (
        <Card>
          <CardContent className="p-5">
            <label className="text-xs text-muted-foreground">
              Pick the employer (any registered entity — SAG subsidiary, owner-investment, or
              external employer)
            </label>
            <select
              defaultValue=""
              onChange={(e) => {
                if (e.target.value) addSource(e.target.value);
              }}
              className="mt-1 w-full h-10 rounded-md border border-input bg-background px-3 text-sm"
            >
              <option value="">— Select employer —</option>
              {ALL_ORGANIZATIONS.map((o) => (
                <option key={o.slug} value={o.slug}>
                  {o.emoji} {o.name}
                  {o.parentRelationship === "external-employer" ? " (external)" : ""}
                </option>
              ))}
            </select>
            <p className="mt-2 text-[11px] text-muted-foreground">
              Carson Communications is registered as an external employer. To add a brand-new
              employer not in the registry, first add it to{" "}
              <code className="text-[11px]">src/lib/sag/entities.ts → EXTERNAL_EMPLOYERS</code>.
            </p>
          </CardContent>
        </Card>
      )}

      {sources.length === 0 ? (
        <Card>
          <CardContent className="p-12 text-center">
            <div className="text-5xl mb-3">🧾</div>
            <p className="text-base font-medium">No income sources tracked yet</p>
            <p className="mt-1 text-sm text-muted-foreground max-w-md mx-auto">
              Add Carson Communications and Spectrum Recovery from the suggestions above, then
              log paystubs as they come in. Use this page to roll up annual W-2 totals across
              every employer.
            </p>
          </CardContent>
        </Card>
      ) : (
        sources.map((s) => {
          const org = ALL_ORGANIZATIONS.find((o) => o.slug === s.employerSlug);
          if (!org) return null;
          const ytdGrossSource = s.paystubs
            .filter((p) => p.date.startsWith(String(currentYear)))
            .reduce((a, p) => a + p.gross, 0);
          const lastStub = s.paystubs[0];
          const isExternal = org.parentRelationship === "external-employer";
          return (
            <Card key={s.id}>
              <CardContent className="p-6">
                <div className="flex items-start gap-4 flex-wrap">
                  <div
                    className="w-14 h-14 rounded-xl flex items-center justify-center text-3xl shrink-0"
                    style={{
                      backgroundColor: org.primaryColor ? `${org.primaryColor}25` : undefined,
                    }}
                  >
                    {org.emoji}
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 flex-wrap mb-1">
                      <Badge variant={isExternal ? "warning" : "info"}>
                        {isExternal ? "External employer" : "SAG subsidiary"}
                      </Badge>
                      <Badge variant="outline">{org.industry}</Badge>
                      <Badge variant="secondary">{CADENCE_LABEL[s.cadence]}</Badge>
                      {org.location && (
                        <Badge variant="outline">📍 {org.location}</Badge>
                      )}
                    </div>
                    <h2 className="text-xl font-semibold">{org.name}</h2>
                    {s.role && (
                      <p className="text-sm italic text-muted-foreground">{s.role}</p>
                    )}
                    <p className="mt-2 text-sm text-foreground/85">{org.blurb}</p>
                  </div>
                  <div className="flex flex-col items-end gap-2 shrink-0">
                    <div className="text-right">
                      <div className="section-label">
                        YTD {currentYear}
                      </div>
                      <div className="text-xl font-semibold tabular-nums text-green-700 dark:text-green-400">
                        {formatCurrency(ytdGrossSource)}
                      </div>
                    </div>
                    <Button variant="ghost" size="sm" onClick={() => removeSource(s.id)}>
                      Remove
                    </Button>
                  </div>
                </div>

                <div className="mt-5 grid gap-3 md:grid-cols-3">
                  <Field label="Role / title">
                    <Input
                      defaultValue={s.role ?? ""}
                      onBlur={(e) => updateSource(s.id, { role: e.target.value || undefined })}
                      placeholder="e.g. On-air talent"
                    />
                  </Field>
                  <Field label="Pay cadence">
                    <select
                      value={s.cadence}
                      onChange={(e) =>
                        updateSource(s.id, { cadence: e.target.value as PayCadence })
                      }
                      className="w-full h-10 rounded-md border border-input bg-background px-3 text-sm"
                    >
                      {(Object.keys(CADENCE_LABEL) as PayCadence[]).map((c) => (
                        <option key={c} value={c}>
                          {CADENCE_LABEL[c]}
                        </option>
                      ))}
                    </select>
                  </Field>
                  <Field label="Pay rate (gross / period)">
                    <Input
                      type="number"
                      defaultValue={s.payRate ?? ""}
                      onBlur={(e) =>
                        updateSource(s.id, {
                          payRate: e.target.value ? Number(e.target.value) : undefined,
                        })
                      }
                      placeholder="0.00"
                      step="0.01"
                    />
                  </Field>
                  <Field label="Started">
                    <Input
                      type="date"
                      defaultValue={s.startedAt ?? ""}
                      onBlur={(e) =>
                        updateSource(s.id, { startedAt: e.target.value || undefined })
                      }
                    />
                  </Field>
                  <Field label="Last paystub" className="md:col-span-2">
                    <div className="h-10 rounded-md border border-input bg-muted/30 px-3 text-sm flex items-center text-muted-foreground">
                      {lastStub
                        ? `${formatDate(lastStub.date)} — ${formatCurrency(lastStub.gross)} gross`
                        : "No paystubs logged yet"}
                    </div>
                  </Field>
                  <Field label="Notes" className="md:col-span-3">
                    <Input
                      defaultValue={s.notes ?? ""}
                      onBlur={(e) => updateSource(s.id, { notes: e.target.value || undefined })}
                      placeholder="Hours, contract terms, contact at HR…"
                    />
                  </Field>
                </div>

                <div className="mt-5 flex items-center justify-between flex-wrap gap-2">
                  <h3 className="text-sm font-semibold">
                    Paystubs ({s.paystubs.length})
                  </h3>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setAddingFor(addingFor === s.id ? null : s.id)}
                  >
                    {addingFor === s.id ? "Cancel" : "+ Log paystub"}
                  </Button>
                </div>

                {addingFor === s.id && (
                  <AddPaystubForm onAdd={(stub) => addPaystub(s.id, stub)} />
                )}

                {s.paystubs.length > 0 && (
                  <div className="mt-3 rounded-md border bg-background overflow-x-auto">
                    <table className="w-full text-sm">
                      <thead className="section-label border-b">
                        <tr>
                          <th className="px-3 py-2 text-left">Date</th>
                          <th className="px-3 py-2 text-right">Gross</th>
                          <th className="px-3 py-2 text-right">Net</th>
                          <th className="px-3 py-2 text-right">Hours</th>
                          <th className="px-3 py-2 text-left">Notes</th>
                          <th className="px-3 py-2 w-8" />
                        </tr>
                      </thead>
                      <tbody>
                        {s.paystubs.map((p) => (
                          <tr key={p.id} className="border-b last:border-0">
                            <td className="px-3 py-2 font-mono text-xs">{p.date}</td>
                            <td className="px-3 py-2 text-right tabular-nums">
                              {formatCurrency(p.gross)}
                            </td>
                            <td className="px-3 py-2 text-right tabular-nums text-muted-foreground">
                              {p.net != null ? formatCurrency(p.net) : "—"}
                            </td>
                            <td className="px-3 py-2 text-right tabular-nums text-muted-foreground">
                              {p.hours != null ? p.hours : "—"}
                            </td>
                            <td className="px-3 py-2 text-xs text-muted-foreground truncate max-w-xs">
                              {p.notes ?? ""}
                            </td>
                            <td className="px-3 py-2 text-right">
                              <button
                                onClick={() => removePaystub(s.id, p.id)}
                                className="text-xs text-muted-foreground hover:text-destructive"
                              >
                                ×
                              </button>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </CardContent>
            </Card>
          );
        })
      )}

      <Card className="border-dashed">
        <CardContent className="p-5 text-xs text-muted-foreground">
          External employers (e.g. {EXTERNAL_EMPLOYERS.map((e) => e.name).join(", ")}) are listed
          in the entity registry with <code className="text-[11px]">parentRelationship: &ldquo;external-employer&rdquo;</code> —
          they appear in dropdowns but never in the SAG portfolio. To add a brand-new external
          employer, edit{" "}
          <code className="text-[11px]">src/lib/sag/entities.ts → EXTERNAL_EMPLOYERS</code> and
          come back here.
        </CardContent>
      </Card>
    </div>
  );
}

function AddPaystubForm({ onAdd }: { onAdd: (stub: Omit<Paystub, "id">) => void }) {
  const [form, setForm] = useState({
    date: new Date().toISOString().slice(0, 10),
    gross: "",
    net: "",
    hours: "",
    notes: "",
  });

  function submit() {
    const gross = Number(form.gross);
    if (!form.date || !Number.isFinite(gross) || gross <= 0) {
      alert("Enter a date and a positive gross amount.");
      return;
    }
    onAdd({
      date: form.date,
      gross,
      net: form.net ? Number(form.net) : undefined,
      hours: form.hours ? Number(form.hours) : undefined,
      notes: form.notes || undefined,
    });
  }

  return (
    <div className="mt-3 rounded-md border bg-muted/30 p-4 space-y-3">
      <div className="grid gap-3 md:grid-cols-4">
        <Field label="Date">
          <Input
            type="date"
            value={form.date}
            onChange={(e) => setForm({ ...form, date: e.target.value })}
          />
        </Field>
        <Field label="Gross">
          <Input
            type="number"
            step="0.01"
            value={form.gross}
            onChange={(e) => setForm({ ...form, gross: e.target.value })}
            placeholder="0.00"
          />
        </Field>
        <Field label="Net (optional)">
          <Input
            type="number"
            step="0.01"
            value={form.net}
            onChange={(e) => setForm({ ...form, net: e.target.value })}
            placeholder="0.00"
          />
        </Field>
        <Field label="Hours (optional)">
          <Input
            type="number"
            step="0.25"
            value={form.hours}
            onChange={(e) => setForm({ ...form, hours: e.target.value })}
            placeholder="0"
          />
        </Field>
      </div>
      <Field label="Notes (optional)">
        <Input
          value={form.notes}
          onChange={(e) => setForm({ ...form, notes: e.target.value })}
          placeholder="Pay period, bonus, deductions…"
        />
      </Field>
      <div className="flex justify-end">
        <Button variant="brand" size="sm" onClick={submit}>
          Add paystub
        </Button>
      </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>
  );
}

function Stat({
  label,
  value,
  tone = "default",
}: {
  label: string;
  value: string;
  tone?: "default" | "success" | "info";
}) {
  const colorClass =
    tone === "success"
      ? "text-green-700 dark:text-green-400"
      : tone === "info"
        ? "text-blue-700 dark:text-blue-400"
        : "text-foreground";
  return (
    <Card>
      <CardContent className="p-4">
        <div className="section-label">
          {label}
        </div>
        <div className={`mt-1 text-xl font-semibold tabular-nums ${colorClass}`}>{value}</div>
      </CardContent>
    </Card>
  );
}
