"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 { useAlertConfirm } from "@/components/ui/alert-dialog";
import { DOMAINS, getDaysUntilExpiration, urgencyFor, DOMAIN_CATEGORIES } from "@/lib/sag/domains";
import { bumpExpirationByYears, type DomainOverrides } from "@/lib/sag/domain-overrides";
import { useLocalStorage } from "@/lib/hooks/use-local-storage";
import { formatCurrency } from "@/lib/utils";

export function DomainsTable() {
  const [overrides, setOverrides] = useLocalStorage<DomainOverrides>("sag.domains.overrides", {});
  const [editing, setEditing] = useState<string | null>(null);
  const [filterCat, setFilterCat] = useState<string>("all");
  const [filterUrgency, setFilterUrgency] = useState<"all" | "needs-action" | "expiring" | "good">("all");
  const [search, setSearch] = useState("");
  const { confirm: confirmAlert, AlertConfirmPortal } = useAlertConfirm();

  const merged = useMemo(
    () =>
      DOMAINS.map((d) => {
        const o = overrides[d.domain];
        return {
          ...d,
          expirationIso: o?.expirationIso ?? d.expirationIso,
          status: o?.status ?? d.status,
          registrarUrl: o?.registrarUrl,
          notes: o?.notes,
          renewedAt: o?.renewedAt,
        };
      }),
    [overrides]
  );

  const filtered = merged.filter((d) => {
    if (filterCat !== "all" && d.category !== filterCat) return false;
    if (search && !d.domain.toLowerCase().includes(search.toLowerCase())) return false;
    if (filterUrgency !== "all") {
      const u = urgencyFor(d.expirationIso);
      if (filterUrgency === "needs-action" && !(u === "expired" || u === "urgent")) return false;
      if (filterUrgency === "expiring" && u !== "soon") return false;
      if (filterUrgency === "good" && (u === "expired" || u === "urgent" || u === "soon")) return false;
    }
    return true;
  });

  const sorted = [...filtered].sort(
    (a, b) => getDaysUntilExpiration(a.expirationIso) - getDaysUntilExpiration(b.expirationIso)
  );

  function setOverride(domain: string, patch: Partial<NonNullable<DomainOverrides[string]>>) {
    setOverrides({ ...overrides, [domain]: { ...overrides[domain], ...patch } });
  }

  function markRenewed(domain: string) {
    const d = DOMAINS.find((x) => x.domain === domain);
    if (!d) return;
    const current = overrides[domain]?.expirationIso ?? d.expirationIso;
    setOverride(domain, {
      expirationIso: bumpExpirationByYears(current, 1),
      status: "Active",
      renewedAt: new Date().toISOString().slice(0, 10),
    });
  }

  async function clearOverride(domain: string) {
    const ok = await confirmAlert({
      title: `Reset overrides for ${domain}?`,
      description: "Stored renewal/notes will revert to the seed values.",
      actionLabel: "Reset",
      destructive: true,
    });
    if (!ok) return;
    const next = { ...overrides };
    delete next[domain];
    setOverrides(next);
  }

  return (
    <>
    <div className="space-y-4">
      <Card>
        <CardContent className="p-4 flex flex-wrap items-center gap-3">
          <Input
            placeholder="Search domains..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="max-w-xs"
          />
          <select
            value={filterCat}
            onChange={(e) => setFilterCat(e.target.value)}
            className="h-10 rounded-md border border-input bg-background px-3 text-sm"
          >
            <option value="all">All categories</option>
            {DOMAIN_CATEGORIES.map((c) => (
              <option key={c} value={c}>{c}</option>
            ))}
          </select>
          <div className="flex items-center gap-1.5">
            <Chip active={filterUrgency === "all"} onClick={() => setFilterUrgency("all")}>All</Chip>
            <Chip active={filterUrgency === "needs-action"} onClick={() => setFilterUrgency("needs-action")}>
              Needs action
            </Chip>
            <Chip active={filterUrgency === "expiring"} onClick={() => setFilterUrgency("expiring")}>
              Expiring ≤90d
            </Chip>
            <Chip active={filterUrgency === "good"} onClick={() => setFilterUrgency("good")}>Healthy</Chip>
          </div>
          <span className="ml-auto text-xs text-muted-foreground tabular-nums">
            {sorted.length} of {DOMAINS.length}
          </span>
        </CardContent>
      </Card>

      <Card>
        <CardContent className="p-0">
          <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">Domain</th>
                  <th className="text-left p-3 font-medium">Category</th>
                  <th className="text-left p-3 font-medium">Expires</th>
                  <th className="text-right p-3 font-medium">Value</th>
                  <th className="text-left p-3 font-medium">Status</th>
                  <th className="text-right p-3 font-medium">Actions</th>
                </tr>
              </thead>
              <tbody>
                {sorted.map((d) => {
                  const days = getDaysUntilExpiration(d.expirationIso);
                  const urgency = urgencyFor(d.expirationIso);
                  const hasOverride = !!overrides[d.domain];
                  const isEditing = editing === d.domain;
                  return (
                    <>
                      <tr
                        key={d.domain}
                        className={`border-b last:border-b-0 hover:bg-muted/20 ${
                          hasOverride ? "bg-blue-50/40 dark:bg-blue-900/10" : ""
                        }`}
                      >
                        <td className="p-3">
                          <a
                            href={`https://${d.domain}`}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="font-mono font-medium hover:underline"
                          >
                            {d.domain}
                          </a>
                          {d.renewedAt && (
                            <div className="text-[10px] text-blue-700 dark:text-blue-300">
                              ↻ renewed {d.renewedAt}
                            </div>
                          )}
                          {d.notes && <div className="text-[10px] text-muted-foreground mt-0.5">{d.notes}</div>}
                        </td>
                        <td className="p-3 text-xs text-muted-foreground">{d.category}</td>
                        <td className="p-3 text-xs">
                          <div>{new Date(d.expirationIso).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}</div>
                          <DaysBadge days={days} urgency={urgency} />
                        </td>
                        <td className="p-3 text-right tabular-nums font-medium">
                          {d.estValue > 0 ? formatCurrency(d.estValue) : <span className="text-muted-foreground">{d.estValueLabel}</span>}
                        </td>
                        <td className="p-3">
                          <Badge variant={d.status === "Expired" ? "destructive" : d.status === "Pending Renewal" ? "warning" : "outline"}>
                            {d.status}
                          </Badge>
                        </td>
                        <td className="p-3 text-right">
                          <div className="flex items-center gap-1 justify-end">
                            {urgency === "expired" || urgency === "urgent" || urgency === "soon" ? (
                              <Button variant="brand" size="sm" onClick={() => markRenewed(d.domain)}>
                                Mark renewed +1y
                              </Button>
                            ) : null}
                            <Button variant="ghost" size="sm" onClick={() => setEditing(isEditing ? null : d.domain)}>
                              {isEditing ? "Done" : "Edit"}
                            </Button>
                          </div>
                        </td>
                      </tr>
                      {isEditing && (
                        <tr className="bg-muted/30 border-b">
                          <td colSpan={6} className="p-4">
                            <div className="grid gap-3 md:grid-cols-3">
                              <Field label="New expiration">
                                <Input
                                  type="date"
                                  value={d.expirationIso}
                                  onChange={(e) => setOverride(d.domain, { expirationIso: e.target.value })}
                                />
                              </Field>
                              <Field label="Registrar URL">
                                <Input
                                  placeholder="https://your-registrar.com/manage/..."
                                  value={d.registrarUrl ?? ""}
                                  onChange={(e) => setOverride(d.domain, { registrarUrl: e.target.value })}
                                />
                              </Field>
                              <Field label="Notes">
                                <Input
                                  value={d.notes ?? ""}
                                  onChange={(e) => setOverride(d.domain, { notes: e.target.value })}
                                />
                              </Field>
                            </div>
                            <div className="mt-3 flex items-center justify-between">
                              <div className="text-xs text-muted-foreground">
                                Original: {new Date(DOMAINS.find((x) => x.domain === d.domain)!.expirationIso).toLocaleDateString()}
                              </div>
                              <div className="flex gap-2">
                                {d.registrarUrl && (
                                  <Button asChild size="sm" variant="outline">
                                    <a href={d.registrarUrl} target="_blank" rel="noopener noreferrer">Open registrar ↗</a>
                                  </Button>
                                )}
                                {hasOverride && (
                                  <Button size="sm" variant="ghost" onClick={() => clearOverride(d.domain)}>
                                    Clear overrides
                                  </Button>
                                )}
                              </div>
                            </div>
                          </td>
                        </tr>
                      )}
                    </>
                  );
                })}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
    <AlertConfirmPortal />
    </>
  );
}

function Chip({ active, onClick, children }: { active: boolean; onClick: () => void; children: React.ReactNode }) {
  return (
    <button
      onClick={onClick}
      className={`text-xs px-3 py-1.5 rounded-full border transition-colors ${
        active ? "bg-foreground text-background border-foreground" : "border-input text-muted-foreground hover:bg-accent"
      }`}
    >
      {children}
    </button>
  );
}

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div>
      <label className="text-xs text-muted-foreground">{label}</label>
      <div className="mt-1">{children}</div>
    </div>
  );
}

function DaysBadge({ days, urgency }: { days: number; urgency: "expired" | "urgent" | "soon" | "monitor" | "good" }) {
  if (urgency === "expired") return <Badge variant="destructive" className="mt-1 text-[10px]">Expired {Math.abs(days)}d ago</Badge>;
  if (urgency === "urgent") return <Badge variant="destructive" className="mt-1 text-[10px]">{days}d left</Badge>;
  if (urgency === "soon") return <Badge variant="warning" className="mt-1 text-[10px]">{days}d left</Badge>;
  if (urgency === "monitor") return <Badge variant="info" className="mt-1 text-[10px]">{days}d left</Badge>;
  return <span className="text-[10px] text-muted-foreground">{days}d</span>;
}
