import { Link, useRouter } from "@tanstack/react-router";
import { useState, type ReactNode } from "react";
import { toast } from "sonner";
import { StatusPill } from "@/components/hub-dashboard";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Dialog, DialogContent } from "@/components/ui/dialog";
import { Input, NativeSelect, Textarea } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { APPROVAL_LABEL, INVESTMENT_TYPES, VEHICLE_LABEL, supporterPhrase, tombstoneCta } from "@/lib/privileges";
import {
  setCapstoneSeat,
  setCapstoneStatus,
  updateTombstone,
  type CapstoneDeal,
  type TombstonePatch,
} from "@/lib/server/api-hub";
import { SeatPerson } from "@/components/seat-bio";
import { seatDossierFromRoles } from "@/lib/rbac";
import { useRoleStore } from "@/lib/role-store";
import { cn, daysUntil, formatDate, moneyCents } from "@/lib/utils";

function dollars(cents: number) {
  return moneyCents(cents);
}

export function DaysLeftBadge({ closesAt }: { closesAt: string | null }) {
  const n = daysUntil(closesAt);
  if (n == null) return null;
  const label = n < 0 ? "Closed" : `${n} days left`;
  return (
    <span className="absolute top-3 left-3 rounded-full bg-navy px-2.5 py-1 text-[11px] font-semibold tracking-wide text-primary uppercase">
      {label}
    </span>
  );
}

export function TombstoneCard({
  project,
  canEdit = false,
  onEdit,
}: {
  project: CapstoneDeal;
  canEdit?: boolean;
  onEdit?: () => void;
}) {
  const [preview, setPreview] = useState(false);
  const rosterFull = (project.seats?.length ?? 0) > 0 && project.seats.every((s) => s.filled);
  const detailsReady = rosterFull && project.status === "live";
  const blurb = project.summary.length > 140 ? `${project.summary.slice(0, 137).trim()}…` : project.summary;
  const cta = tombstoneCta(project.vehicle, project.category);

  return (
    <>
      <Card className="overflow-hidden p-0">
        <div className="relative aspect-[16/10] bg-navy">
          {project.banner_src ? (
            <img
              src={project.banner_src}
              alt=""
              className="size-full object-cover outline outline-1 -outline-offset-1 outline-black/10"
            />
          ) : (
            <div className="flex size-full items-center justify-center font-display text-lg text-primary">
              {project.company ?? "CFL"}
            </div>
          )}
          <DaysLeftBadge closesAt={project.closes_at} />
          <span className="absolute right-3 bottom-3 flex size-12 items-center justify-center overflow-hidden rounded-full border-2 border-card bg-card shadow-sm">
            <img src="/cfl-mark.png" alt="" className="size-10 object-contain" />
          </span>
        </div>
        <CardContent className="flex flex-1 flex-col pt-4">
          <p className="text-xs text-muted-foreground">{project.location}</p>
          <h2 className="mt-1 font-display text-xl font-semibold leading-snug">{project.title}</h2>
          <p className="mt-2 flex-1 text-sm leading-relaxed text-muted-foreground">
            {blurb}{" "}
            <button type="button" className="font-semibold text-primary hover:underline" onClick={() => setPreview(true)}>
              View more
            </button>
          </p>
          <div className="mt-4 grid grid-cols-2 gap-3 border-t border-border pt-4">
            <div>
              <p className="font-display text-lg tabular leading-none">{dollars(project.funded_cents)}</p>
              <p className="mt-1 text-xs text-muted-foreground">{supporterPhrase(project.investors, project.vehicle)}</p>
            </div>
            <div className="text-right">
              <p className="font-display text-lg tabular leading-none">{dollars(project.max_raise_cents)}</p>
              <p className="mt-1 text-xs text-muted-foreground">
                {project.min_investment_cents > 0
                  ? `Minimum donation needed: ${dollars(project.min_investment_cents)}`
                  : "Donor-sponsored · no equity"}
              </p>
            </div>
          </div>
          <div className="mt-4 flex flex-col gap-2">
            <Button className="w-full bg-navy text-sidebar-foreground hover:bg-navy/90" onClick={() => setPreview(true)}>
              {cta}
            </Button>
            <div className="flex flex-wrap gap-2">
              {detailsReady ? (
                <Button asChild variant="outline" className="flex-1">
                  <Link to="/capstone/$slug" params={{ slug: project.slug }}>
                    Open packet
                  </Link>
                </Button>
              ) : (
                <Button variant="outline" className="flex-1" disabled>
                  Packet locked
                </Button>
              )}
              {canEdit && onEdit ? (
                <Button variant="outline" className="flex-1" onClick={onEdit}>
                  Edit
                </Button>
              ) : null}
            </div>
          </div>
        </CardContent>
      </Card>
      <TombstonePreview project={project} open={preview} onOpenChange={setPreview} />
    </>
  );
}

export function TombstonePreview({
  project,
  open,
  onOpenChange,
}: {
  project: CapstoneDeal;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}) {
  const rosterFull = (project.seats?.length ?? 0) > 0 && project.seats.every((s) => s.filled);
  const detailsReady = rosterFull && project.status === "live";
  const cta = tombstoneCta(project.vehicle, project.category);
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent
        title="Tombstone design"
        className="max-w-md overflow-y-auto"
        description="Public project card as it appears on the market."
      >
        <div className="overflow-hidden rounded-xl bg-muted/40">
          <div className="relative aspect-[16/10] bg-navy">
            {project.banner_src ? (
              <img src={project.banner_src} alt="" className="size-full object-cover" />
            ) : null}
            <DaysLeftBadge closesAt={project.closes_at} />
          </div>
          <div className="p-4">
            <p className="text-xs text-muted-foreground">{project.location}</p>
            <h3 className="mt-1 font-display text-xl font-semibold leading-snug">{project.title}</h3>
            <p className="mt-2 text-sm leading-relaxed text-muted-foreground">{project.summary}</p>
            <div className="mt-4 grid grid-cols-2 gap-3 border-t border-border pt-4 text-sm">
              <div>
                <p className="font-display text-xl tabular">{VEHICLE_LABEL[project.vehicle] ?? "Donation"}</p>
                <p className="text-xs text-muted-foreground">Vehicle</p>
              </div>
              <div className="text-right">
                <p className="font-display text-xl tabular">No equity</p>
                <p className="text-xs text-muted-foreground">501(c)(3) · CFL</p>
              </div>
              <div>
                <p className="text-xs text-muted-foreground">Support to date</p>
                <p className="font-medium tabular">{dollars(project.funded_cents)}</p>
                <p className="text-xs text-muted-foreground">{supporterPhrase(project.investors, project.vehicle)}</p>
              </div>
              <div className="text-right">
                <p className="text-xs text-muted-foreground">Project budget</p>
                <p className="font-medium tabular">{dollars(project.max_raise_cents)}</p>
                <p className="text-xs text-muted-foreground">
                  {project.min_investment_cents > 0
                    ? `Minimum donation needed: ${dollars(project.min_investment_cents)}`
                    : "Education — not an offering"}
                </p>
              </div>
            </div>
            {detailsReady ? (
              <Button asChild className="mt-5 w-full bg-navy text-sidebar-foreground hover:bg-navy/90">
                <Link to="/capstone/$slug" params={{ slug: project.slug }}>
                  {cta}
                </Link>
              </Button>
            ) : (
              <p className="mt-5 text-xs text-muted-foreground">
                Packet stays locked until Super Admin seats a full roster and marks the card live. Education — not a
                securities offering. CFL takes no equity.
              </p>
            )}
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}

export function TombstoneEditDialog({
  project,
  open,
  onOpenChange,
}: {
  project: CapstoneDeal;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}) {
  const router = useRouter();
  const [form, setForm] = useState<TombstonePatch>(() => patchFrom(project));

  function set<K extends keyof TombstonePatch>(key: K, value: TombstonePatch[K]) {
    setForm((f) => ({ ...f, [key]: value }));
  }

  async function save() {
    const res = await updateTombstone({ data: form });
    if (res.ok) {
      toast.success("Tombstone saved. Last updated is now.");
      onOpenChange(false);
      await router.invalidate();
    } else {
      toast.error("Could not save tombstone.");
    }
  }

  return (
    <Dialog
      open={open}
      onOpenChange={(next) => {
        if (next) setForm(patchFrom(project));
        onOpenChange(next);
      }}
    >
      <DialogContent
        title="Edit tombstone ad"
        description="Super Admin and instructor can edit this public card. Last updated stamps when you save. CFL takes no equity in participant ventures."
        className="max-h-[90vh] max-w-2xl overflow-y-auto"
      >
        <div className="grid gap-3 sm:grid-cols-2">
          <Field label="Company name">
            <Input value={form.company} onChange={(e) => set("company", e.target.value)} />
          </Field>
          <Field label="Ads title">
            <Input value={form.title} onChange={(e) => set("title", e.target.value)} />
          </Field>
          <Field label="Location">
            <Input value={form.location} onChange={(e) => set("location", e.target.value)} />
          </Field>
          <Field label="Category">
            <Input value={form.category} onChange={(e) => set("category", e.target.value)} />
          </Field>
          <Field label="Subtitle">
            <Input value={form.subtitle} onChange={(e) => set("subtitle", e.target.value)} />
          </Field>
          <Field label="Banner image">
            <Input value={form.banner_src} onChange={(e) => set("banner_src", e.target.value)} />
          </Field>
        </div>
        <div className="mt-3">
          <Field label="Description">
            <Textarea value={form.summary} onChange={(e) => set("summary", e.target.value)} />
          </Field>
        </div>
        <div className="mt-3 grid gap-3 sm:grid-cols-2">
          <Field label="No. of donors">
            <Input type="number" min={0} value={form.investors} onChange={(e) => set("investors", Number(e.target.value) || 0)} />
          </Field>
          <Field label="Total funded ($)">
            <Input
              type="number"
              min={0}
              value={form.funded_cents / 100}
              onChange={(e) => set("funded_cents", Math.round(Number(e.target.value) * 100) || 0)}
            />
          </Field>
          <Field label="Min raise fund ($)">
            <Input
              type="number"
              min={0}
              value={form.min_raise_cents / 100}
              onChange={(e) => set("min_raise_cents", Math.round(Number(e.target.value) * 100) || 0)}
            />
          </Field>
          <Field label="Max raise fund ($)">
            <Input
              type="number"
              min={0}
              value={form.max_raise_cents / 100}
              onChange={(e) => set("max_raise_cents", Math.round(Number(e.target.value) * 100) || 0)}
            />
          </Field>
          <Field label="Authorized amount of sponsored research ($)">
            <Input
              type="number"
              min={0}
              value={form.authorized_shares}
              onChange={(e) => set("authorized_shares", Number(e.target.value) || 0)}
            />
          </Field>
          <Field label="Targeted foundations">
            <Input type="number" min={0} value={form.shares_offered} onChange={(e) => set("shares_offered", Number(e.target.value) || 0)} />
          </Field>
          <Field label="Suggested donation ($)">
            <Input
              type="number"
              min={0}
              step="0.01"
              value={form.price_per_share_cents / 100}
              onChange={(e) => set("price_per_share_cents", Math.round(Number(e.target.value) * 100) || 0)}
            />
          </Field>
          <Field label="Support type">
            <NativeSelect value={form.investment_type} onChange={(e) => set("investment_type", e.target.value)}>
              {INVESTMENT_TYPES.map((t) => (
                <option key={t.id} value={t.id}>
                  {t.label}
                </option>
              ))}
            </NativeSelect>
          </Field>
          <Field label="Vehicle">
            <NativeSelect value={form.vehicle} onChange={(e) => set("vehicle", e.target.value)}>
              {INVESTMENT_TYPES.map((t) => (
                <option key={t.id} value={t.id}>
                  {t.label}
                </option>
              ))}
            </NativeSelect>
          </Field>
          <Field label="Closes">
            <Input type="date" value={form.closes_at} onChange={(e) => set("closes_at", e.target.value)} />
          </Field>
          <Field label="Minimum donation needed ($)">
            <Input
              type="number"
              min={0}
              value={form.min_investment_cents / 100}
              onChange={(e) => set("min_investment_cents", Math.round(Number(e.target.value) * 100) || 0)}
            />
          </Field>
          <Field label="Approval status">
            <NativeSelect value={form.approval_status} onChange={(e) => set("approval_status", e.target.value)}>
              <option value="approved">Approved for donor campaign</option>
              <option value="pending">Pending review</option>
              <option value="not_approved">Not approved</option>
            </NativeSelect>
          </Field>
          <Field label="Publish status">
            <NativeSelect value={form.publish_status} onChange={(e) => set("publish_status", e.target.value)}>
              <option value="published">Published</option>
              <option value="unpublished">Unpublished</option>
            </NativeSelect>
          </Field>
        </div>
        <div className="mt-5 flex justify-end gap-2">
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          <Button onClick={() => void save()}>Save tombstone</Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}

function Field({ label, children }: { label: string; children: ReactNode }) {
  return (
    <div className="space-y-1.5">
      <Label>{label}</Label>
      {children}
    </div>
  );
}

function patchFrom(project: CapstoneDeal): TombstonePatch {
  return {
    id: project.id,
    title: project.title,
    subtitle: project.subtitle ?? "",
    location: project.location ?? "",
    company: project.company ?? "",
    category: project.category,
    summary: project.summary,
    vehicle: project.vehicle,
    investment_type: project.investment_type,
    share_type: project.share_type ?? "",
    investors: project.investors,
    funded_cents: project.funded_cents,
    min_raise_cents: project.min_raise_cents,
    max_raise_cents: project.max_raise_cents,
    min_investment_cents: project.min_investment_cents,
    authorized_shares: project.authorized_shares,
    shares_offered: project.shares_offered,
    price_per_share_cents: project.price_per_share_cents,
    banner_src: project.banner_src ?? "",
    closes_at: project.closes_at ?? "",
    approval_status: project.approval_status,
    publish_status: project.publish_status,
  };
}

export function TombstoneAdminTable({ projects, canEdit }: { projects: CapstoneDeal[]; canEdit: boolean }) {
  const [q, setQ] = useState("");
  const [edit, setEdit] = useState<CapstoneDeal | null>(null);
  const [preview, setPreview] = useState<CapstoneDeal | null>(null);
  const filtered = projects.filter((p) => {
    const hay = `${p.company} ${p.title} ${p.location}`.toLowerCase();
    return hay.includes(q.toLowerCase().trim());
  });

  return (
    <>
      <Card>
        <CardContent className="pt-5">
          <div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
            <p className="text-sm text-muted-foreground">
              Showing {filtered.length} of {projects.length} entries
            </p>
            <Input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search by company name" className="sm:max-w-xs" />
          </div>
          <div className="overflow-x-auto">
            <table className="w-full min-w-[56rem] text-left text-sm">
              <thead className="text-[11px] tracking-wide text-muted-foreground uppercase">
                <tr className="border-b border-border">
                  <th className="pb-2 font-medium">No.</th>
                  <th className="pb-2 font-medium">Company name</th>
                  <th className="pb-2 font-medium">Ads title</th>
                  <th className="pb-2 font-medium">Location</th>
                  <th className="pb-2 font-medium">Donors / supporters</th>
                  <th className="pb-2 font-medium">Publish status</th>
                  <th className="pb-2 font-medium">Approval status</th>
                  <th className="pb-2 font-medium">Last updated</th>
                  <th className="pb-2 font-medium">Actions</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map((p, i) => (
                  <tr key={p.id} className="border-b border-border/70">
                    <td className="py-2.5 tabular">{i + 1}</td>
                    <td className="py-2.5">{p.company}</td>
                    <td className="py-2.5 font-medium">{p.title}</td>
                    <td className="py-2.5">{p.location}</td>
                    <td className="py-2.5 tabular">{p.investors}</td>
                    <td className="py-2.5">
                      <StatusPill status={p.publish_status} />
                    </td>
                    <td className="py-2.5">
                      <Badge variant={p.approval_status === "approved" ? "success" : p.approval_status === "not_approved" ? "destructive" : "warning"}>
                        {APPROVAL_LABEL[p.approval_status] ?? p.approval_status}
                      </Badge>
                    </td>
                    <td className="py-2.5 text-xs text-muted-foreground">{formatDate(p.last_updated_at)}</td>
                    <td className="py-2.5">
                      <div className="flex flex-wrap gap-1">
                        <Button size="sm" variant="outline" onClick={() => setPreview(p)}>
                          View
                        </Button>
                        {canEdit ? (
                          <Button size="sm" variant="outline" onClick={() => setEdit(p)}>
                            Edit
                          </Button>
                        ) : null}
                      </div>
                    </td>
                  </tr>
                ))}
                {filtered.length === 0 ? (
                  <tr>
                    <td className="py-6 text-sm text-muted-foreground" colSpan={9}>
                      No tombstone ads match that search.
                    </td>
                  </tr>
                ) : null}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
      {preview ? <TombstonePreview project={preview} open onOpenChange={(o) => !o && setPreview(null)} /> : null}
      {edit ? <TombstoneEditDialog project={edit} open onOpenChange={(o) => !o && setEdit(null)} /> : null}
    </>
  );
}

export function CapstoneStudioList({ projects, canEdit }: { projects: CapstoneDeal[]; canEdit: boolean }) {
  const [editId, setEditId] = useState<string | null>(null);
  const editing = projects.find((p) => p.id === editId) ?? null;
  return (
    <div className="space-y-8">
      {projects.map((p) => (
        <CapstoneStudioRow key={p.id} project={p} canEdit={canEdit} onEdit={() => setEditId(p.id)} />
      ))}
      {editing ? <TombstoneEditDialog project={editing} open onOpenChange={(o) => !o && setEditId(null)} /> : null}
    </div>
  );
}

function CapstoneStudioRow({
  project,
  canEdit,
  onEdit,
}: {
  project: CapstoneDeal;
  canEdit: boolean;
  onEdit: () => void;
}) {
  const router = useRouter();
  const role = useRoleStore((s) => s.role);
  const operatorRole = useRoleStore((s) => s.operatorRole);
  const canReplace = canEdit && seatDossierFromRoles(operatorRole, role).replaceSeat;
  const [seatId, setSeatId] = useState<string | null>(null);
  const [name, setName] = useState("");
  const filled = project.seats.filter((s) => s.filled).length;
  const total = project.seats.length;
  const rosterFull = total > 0 && filled === total;

  async function mark(status: "live" | "assembling") {
    const res = await setCapstoneStatus({ data: { id: project.id, status } });
    if (!res.ok) {
      toast.error(res.error);
      return;
    }
    toast.success(status === "live" ? "Marked live." : "Returned to assembling.");
    await router.invalidate();
  }

  async function seat() {
    if (!seatId) return;
    await setCapstoneSeat({ data: { id: seatId, person_name: name } });
    toast.success("Seat updated. Last updated stamped.");
    setSeatId(null);
    setName("");
    await router.invalidate();
  }

  return (
    <div className="grid gap-4 lg:grid-cols-5">
      <div className="lg:col-span-3">
        <TombstoneCard project={project} canEdit={canEdit} onEdit={onEdit} />
      </div>
      <Card className="lg:col-span-2">
        <CardContent className="pt-5">
          <div className="mb-3 flex flex-wrap items-center gap-2">
            <StatusPill status={project.status} />
            <Badge variant="outline">{VEHICLE_LABEL[project.vehicle] ?? project.vehicle}</Badge>
            <span className="text-xs text-muted-foreground">
              Team {filled}/{total} {rosterFull ? "complete" : "assembling"}
            </span>
          </div>
          <p className="text-[11px] font-medium tracking-[0.16em] text-muted-foreground uppercase">Roster</p>
          <ul className="mt-3 space-y-2">
            {project.seats.map((s) => (
              <li key={s.id} className="rounded-lg bg-muted/40 px-2 py-2">
                <SeatPerson
                  seat={s}
                  trailing={
                    canReplace ? (
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => {
                          setSeatId(s.id);
                          setName(s.filled ? s.person_name : "");
                        }}
                      >
                        {s.filled ? "Replace" : "Seat"}
                      </Button>
                    ) : (
                      <Badge variant={s.filled ? "success" : "muted"}>{s.filled ? "Seated" : "Open"}</Badge>
                    )
                  }
                />
              </li>
            ))}
          </ul>
          {seatId ? (
            <div className="mt-3 space-y-2 rounded-lg bg-muted p-3">
              <Label htmlFor={`seat-${seatId}`}>Person</Label>
              <Input id={`seat-${seatId}`} value={name} onChange={(e) => setName(e.target.value)} placeholder="Name, or Open" />
              <div className="flex gap-2">
                <Button size="sm" onClick={() => void seat()}>
                  Save seat
                </Button>
                <Button size="sm" variant="outline" onClick={() => setSeatId(null)}>
                  Cancel
                </Button>
              </div>
            </div>
          ) : null}
          {canEdit ? (
            <div className="mt-4 flex flex-wrap gap-2">
              <Button size="sm" disabled={!rosterFull || project.status === "live"} onClick={() => void mark("live")}>
                Mark live
              </Button>
              <Button size="sm" variant="outline" disabled={project.status === "assembling"} onClick={() => void mark("assembling")}>
                Return to assembling
              </Button>
            </div>
          ) : null}
          <p className="mt-3 text-xs text-muted-foreground">
            Last updated {formatDate(project.last_updated_at)}. Education packet — not a securities offering.
          </p>
        </CardContent>
      </Card>
    </div>
  );
}

export function TombstoneStats({ project }: { project: CapstoneDeal }) {
  return (
    <div className="mb-6 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
      <Stat
        label="Support to date"
        value={dollars(project.funded_cents)}
        hint={supporterPhrase(project.investors, project.vehicle)}
      />
      <Stat
        label="Project budget"
        value={dollars(project.max_raise_cents)}
        hint={`Floor ${dollars(project.min_raise_cents)}`}
      />
      <Stat
        label="Current donors"
        value={String(project.investors)}
        hint={
          project.min_investment_cents > 0
            ? `Minimum donation needed ${dollars(project.min_investment_cents)}`
            : "Nonprofit vehicle · no equity"
        }
      />
      <Stat
        label="Last updated"
        value={formatDate(project.last_updated_at)}
        hint={project.closes_at ? `Closes ${formatDate(project.closes_at)}` : "No close date"}
      />
    </div>
  );
}

function Stat({ label, value, hint }: { label: string; value: string; hint: string }) {
  return (
    <div className={cn("rounded-xl bg-card p-5 shadow-[var(--shadow-border)]")}>
      <p className="text-[11px] font-medium tracking-[0.16em] text-muted-foreground uppercase">{label}</p>
      <p className="mt-2 font-display text-2xl tabular leading-none">{value}</p>
      <p className="mt-2 text-xs text-muted-foreground">{hint}</p>
    </div>
  );
}
