"use client";

import { useMemo, useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { useLocalStorage } from "@/lib/hooks/use-local-storage";
import { buildBudget, getEntityName, type Bill, type Employee } from "@/lib/sag/budget";
import { ALL_ORGANIZATIONS } from "@/lib/sag/entities";
import { formatCurrency } from "@/lib/utils";

export function BudgetProjection() {
  const [bills] = useLocalStorage<Bill[]>("sag.bills", []);
  const [employees] = useLocalStorage<Employee[]>("sag.hr.employees", []);
  const [filterEntity, setFilterEntity] = useState<string>("all");
  const [filterCategory, setFilterCategory] = useState<string>("all");

  const budget = useMemo(() => buildBudget(bills, employees), [bills, employees]);

  const filtered = budget.lines.filter((l) => {
    if (filterEntity !== "all" && l.entitySlug !== filterEntity) return false;
    if (filterCategory !== "all" && l.category !== filterCategory) return false;
    return true;
  });

  const monthlyEquivalent = budget.totalAnnual / 12;
  const dailyEquivalent = budget.totalAnnual / 365;

  return (
    <div className="space-y-6">
      <div className="grid gap-4 md:grid-cols-4">
        <Big label="Annual cost (modeled)" value={formatCurrency(budget.totalAnnual)} />
        <Big label="Monthly" value={formatCurrency(monthlyEquivalent)} tone="muted" />
        <Big label="Daily" value={formatCurrency(dailyEquivalent)} tone="muted" />
        <Big label="Line items" value={String(budget.lines.length)} tone="muted" />
      </div>

      <Card>
        <CardContent className="p-6">
          <h2 className="text-base font-semibold">By category</h2>
          <p className="text-xs text-muted-foreground">Where the annual dollars go.</p>
          <div className="mt-4 space-y-3">
            {Object.entries(budget.byCategory)
              .sort(([, a], [, b]) => b - a)
              .map(([cat, amount]) => (
                <div key={cat}>
                  <div className="flex items-center justify-between text-sm">
                    <span className="font-medium">{cat}</span>
                    <span className="tabular-nums">
                      {formatCurrency(amount)}{" "}
                      <span className="text-muted-foreground text-xs font-normal">
                        ({Math.round((amount / budget.totalAnnual) * 100)}%)
                      </span>
                    </span>
                  </div>
                  <Progress value={(amount / budget.totalAnnual) * 100} className="mt-1.5 h-1.5" />
                </div>
              ))}
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardContent className="p-6">
          <h2 className="text-base font-semibold">By entity</h2>
          <p className="text-xs text-muted-foreground">Annual cost burden per SAG subsidiary.</p>
          <div className="mt-4 space-y-2 text-sm">
            {Object.entries(budget.byEntity)
              .sort(([, a], [, b]) => b - a)
              .map(([slug, amount]) => {
                const org = ALL_ORGANIZATIONS.find((o) => o.slug === slug);
                return (
                  <div key={slug} className="flex items-center justify-between rounded-md border bg-background p-3">
                    <div className="flex items-center gap-2">
                      <span>{org?.emoji ?? "🏢"}</span>
                      <span>{org?.name ?? slug}</span>
                    </div>
                    <span className="font-mono tabular-nums">{formatCurrency(amount)}</span>
                  </div>
                );
              })}
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardContent className="p-6">
          <div className="flex flex-wrap items-center gap-3 mb-4">
            <h2 className="text-base font-semibold">All line items ({filtered.length})</h2>
            <select
              value={filterCategory}
              onChange={(e) => setFilterCategory(e.target.value)}
              className="h-9 rounded-md border border-input bg-background px-3 text-sm"
            >
              <option value="all">All categories</option>
              {Object.keys(budget.byCategory).map((c) => (
                <option key={c} value={c}>{c}</option>
              ))}
            </select>
            <select
              value={filterEntity}
              onChange={(e) => setFilterEntity(e.target.value)}
              className="h-9 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>
          </div>
          <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">Category</th>
                  <th className="text-left p-3 font-medium">Item</th>
                  <th className="text-left p-3 font-medium">Entity</th>
                  <th className="text-left p-3 font-medium">Note</th>
                  <th className="text-right p-3 font-medium">Annual</th>
                </tr>
              </thead>
              <tbody>
                {filtered
                  .sort((a, b) => b.amountAnnual - a.amountAnnual)
                  .slice(0, 200)
                  .map((line, i) => (
                    <tr key={`${line.label}-${i}`} className="border-b last:border-b-0 hover:bg-muted/20">
                      <td className="p-3 text-xs">
                        <Badge variant="outline" className="text-[10px]">{line.category}</Badge>
                      </td>
                      <td className="p-3">{line.label}</td>
                      <td className="p-3 text-xs text-muted-foreground">{line.entitySlug ? getEntityName(line.entitySlug) : "—"}</td>
                      <td className="p-3 text-xs text-muted-foreground">{line.note}</td>
                      <td className="p-3 text-right tabular-nums font-mono">{formatCurrency(line.amountAnnual)}</td>
                    </tr>
                  ))}
              </tbody>
            </table>
            {filtered.length > 200 && (
              <p className="mt-3 text-xs text-muted-foreground text-center">Showing first 200 of {filtered.length}.</p>
            )}
          </div>
        </CardContent>
      </Card>

      <p className="text-xs text-muted-foreground">
        Domain renewal estimates use $15/yr default for .com, $25/yr for alt TLDs (.io etc.), and $50/yr for premium-value domains (estValue ≥ $1,000). License estimates are conservative defaults — override real numbers in /app/compliance/licenses. Recurring bills extrapolate by cadence. Payroll uses 40hr/wk default for hourly employees.
      </p>
    </div>
  );
}

function Big({ label, value, tone = "default" }: { label: string; value: string; tone?: "default" | "muted" }) {
  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 ${tone === "muted" ? "text-foreground/80" : ""}`}>{value}</div>
      </CardContent>
    </Card>
  );
}
