﻿"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import toast, { Toaster } from "react-hot-toast";
import { TablePagination } from "./TablePagination";
import { ReceiptDisplay, type InvoiceData } from "@/components/ReceiptDisplay";

const API = process.env.NEXT_PUBLIC_API_URL || "http://localhost:5000/api";

type ReceiptRow = {
  id: number;
  type: "donation" | "event" | "custom";
  receipt_no: string;
  donor_name: string;
  email: string | null;
  amount: number;
  purpose: string;
  receipt_path: string | null;
  email_sent: number;
  date: string;
};

type Stats = { donations: number; events: number; custom: number; total: number };

type ViewTarget = { type: string; id: number; name: string };
type ShareTarget = { type: string; id: number; name: string; email: string };

const typeColors: Record<string, string> = {
  donation: "bg-[var(--color-canvas-soft)] text-[var(--color-primary-deep)]",
  event: "bg-[var(--color-canvas-soft)] text-[var(--color-primary-deep)]",
  custom: "bg-[var(--color-canvas-soft)] text-[#b45309]",
};

const typeLabels: Record<string, string> = {
  donation: "Donation",
  event: "Event",
  custom: "Custom",
};

const PAGE_SIZE = 10;

export function AdminReceipts() {
  const [receipts, setReceipts] = useState<ReceiptRow[]>([]);
  const [stats, setStats] = useState<Stats>({ donations: 0, events: 0, custom: 0, total: 0 });
  const [loading, setLoading] = useState(true);
  const [filterType, setFilterType] = useState("all");
  const [fromDate, setFromDate] = useState("");
  const [toDate, setToDate] = useState("");
  const [search, setSearch] = useState("");
  const [showCustomModal, setShowCustomModal] = useState(false);
  const [generatingId, setGeneratingId] = useState<string | null>(null);
  const [page, setPage] = useState(1);
  const [viewModal, setViewModal] = useState<ViewTarget | null>(null);
  const [receiptData, setReceiptData] = useState<InvoiceData | null>(null);
  const [viewLoading, setViewLoading] = useState(false);
  const [viewError, setViewError] = useState("");
  const [viewPublicUrl, setViewPublicUrl] = useState("");
  const [printing, setPrinting] = useState(false);
  const [shareModal, setShareModal] = useState<ShareTarget | null>(null);
  const [shareEmail, setShareEmail] = useState("");
  const [sending, setSending] = useState(false);
  const [sentReceipts, setSentReceipts] = useState<Record<string, boolean>>({});

  const totalPages = Math.max(1, Math.ceil(receipts.length / PAGE_SIZE));
  const safePage = Math.min(page, totalPages);
  const pageStart = (safePage - 1) * PAGE_SIZE;
  const pageReceipts = receipts.slice(pageStart, pageStart + PAGE_SIZE);

  const token = useMemo(() => {
    if (typeof window === "undefined") return "";
    return localStorage.getItem("ngo_admin_token") || "";
  }, []);

  const authHeaders = useMemo(() => ({ Authorization: `Bearer ${token}` }), [token]);

  const loadReceipts = useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      if (filterType !== "all") params.set("type", filterType);
      if (fromDate) params.set("from", fromDate);
      if (toDate) params.set("to", toDate);
      if (search) params.set("search", search);
      const qs = params.toString();

      const [receiptsRes, statsRes] = await Promise.all([
        fetch(`${API}/admin/receipts${qs ? `?${qs}` : ""}`, { headers: authHeaders }),
        fetch(`${API}/admin/receipts/stats`, { headers: authHeaders }),
      ]);

      if (receiptsRes.ok) setReceipts(await receiptsRes.json());
      if (statsRes.ok) setStats(await statsRes.json());
    } catch {
      toast.error("Failed to load receipts");
    } finally {
      setLoading(false);
    }
  }, [filterType, fromDate, toDate, search, authHeaders]);

  useEffect(() => {
    const t = window.setTimeout(() => loadReceipts(), 0);
    return () => window.clearTimeout(t);
  }, [loadReceipts]);

  const changeFilter = (setter: (v: string) => void, value: string) => { setter(value); setPage(1); };

  const generateEventReceipt = async (id: number) => {
    setGeneratingId(`event-${id}`);
    try {
      const res = await fetch(`${API}/admin/receipts/generate-event/${id}`, {
        method: "POST",
        headers: authHeaders,
      });
      if (!res.ok) { toast.error("Failed to generate receipt"); return; }
      toast.success("Event receipt generated");
      await loadReceipts();
    } catch {
      toast.error("Failed to generate receipt");
    } finally {
      setGeneratingId(null);
    }
  };

  const openViewReceipt = async (type: string, id: number, name: string) => {
    setViewModal({ type, id, name });
    setReceiptData(null);
    setViewError("");
    setViewPublicUrl("");
    setViewLoading(true);
    try {
      const [viewRes, linkRes] = await Promise.all([
        fetch(`${API}/admin/receipts/${type}/${id}/view`, { headers: authHeaders }),
        fetch(`${API}/admin/receipts/${type}/${id}/share-link`, { headers: authHeaders }),
      ]);
      const json = await viewRes.json().catch(() => ({}));
      if (!viewRes.ok) {
        setViewError(json.message || "Could not load the receipt.");
        setViewLoading(false);
        return;
      }
      setReceiptData(json);
      if (linkRes.ok) {
        const link = await linkRes.json().catch(() => null);
        if (link && link.url) setViewPublicUrl(link.url);
      }
    } catch {
      setViewError("Network error. Please try again.");
    }
    setViewLoading(false);
  };

  const handlePrint = () => {
    if (!viewPublicUrl) return;
    setPrinting(true);
    const w = window.open(viewPublicUrl, "_blank");
    if (w) {
      window.setTimeout(() => {
        try {
          w.print();
        } catch {
          /* ignore */
        }
        setPrinting(false);
      }, 5000);
    } else {
      setPrinting(false);
      toast.error("Popup blocked. Allow popups and try again.");
    }
  };

  const shareReceipt = async () => {
    if (!shareModal) return;
    if (!shareEmail.trim()) {
      toast.error("Email is required");
      return;
    }
    setSending(true);
    const loadingToast = toast.loading("Sending receipt link...", { duration: Infinity });
    try {
      const res = await fetch(`${API}/admin/receipts/${shareModal.type}/${shareModal.id}/share`, {
        method: "POST",
        headers: { "Content-Type": "application/json", ...authHeaders },
        body: JSON.stringify({ email: shareEmail }),
      });
      toast.dismiss(loadingToast);
      if (!res.ok) {
        const err = await res.json();
        toast.error(err.message || "Failed to send");
        return;
      }
      toast.success("Receipt link sent to " + shareEmail);
      setSentReceipts((prev) => ({ ...prev, [shareModal.type + "-" + shareModal.id]: true }));
      setShareModal(null);
      setShareEmail("");
      await loadReceipts();
    } catch {
      toast.dismiss(loadingToast);
      toast.error("Failed to send email");
    } finally {
      setSending(false);
    }
  };

  return (
    <div className="mx-auto max-w-7xl">
      <div className="mb-5 flex flex-wrap items-end justify-between gap-3">
        <div>
          <p className="text-[10px] font-black uppercase tracking-[0.14em] text-[var(--color-primary)]">Finance</p>
          <h1 className="mt-0.5 text-xl font-black text-[var(--color-ink)] md:text-2xl">Receipt Management</h1>
          <p className="mt-1 max-w-2xl text-[11.5px] font-medium text-[var(--color-ink-mute)]">
            Receipts are rendered as a printable HTML invoice on the public website. View, print, download (via Save as PDF) and share receipts with donors.
          </p>
        </div>
        <button
          onClick={() => setShowCustomModal(true)}
          className="rounded-md bg-gradient-to-r from-[var(--color-primary)] to-[var(--color-primary-deep)] px-3 py-1.5 text-[11.5px] font-black text-white shadow-[0_8px_18px_rgba(93,111,241,0.28)] transition hover:brightness-105"
        >
          + Create Custom Receipt
        </button>
      </div>

      {/* Stats Cards */}
      <div className="mb-5 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
        {[
          { label: "Total Receipts", value: stats.total, color: "var(--color-primary)" },
          { label: "Donation Receipts", value: stats.donations, color: "var(--color-primary-deep)" },
          { label: "Event Receipts", value: stats.events, color: "#ea580c" },
          { label: "Custom Receipts", value: stats.custom, color: "var(--color-ink)" },
        ].map((s) => (
          <div key={s.label} className="overflow-hidden rounded-md border border-[var(--color-hairline)] bg-white p-3.5 shadow-sm">
            <p className="text-[10px] font-black uppercase tracking-wider text-[var(--color-ink-mute)]">{s.label}</p>
            <p className="mt-1 text-xl font-black" style={{ color: s.color }}>{s.value}</p>
          </div>
        ))}
      </div>

      {/* Filter Bar */}
      <section className="mb-5 overflow-hidden rounded-md border border-[var(--color-hairline)] bg-white p-4 shadow-sm">
        <div className="flex flex-wrap items-end gap-3">
          <div className="flex gap-1.5">
            {["all", "donation", "event", "custom"].map((t) => (
              <button
                key={t}
                onClick={() => changeFilter(setFilterType, t)}
                className={`rounded-md px-2.5 py-1.5 text-[11.5px] font-black transition ${
                  filterType === t
                    ? "bg-[var(--color-primary)] text-white shadow-[0_4px_10px_rgba(93,111,241,0.2)]"
                    : "border border-[var(--color-hairline)] bg-white text-[var(--color-ink)] hover:bg-[var(--color-canvas-soft)]"
                }`}
              >
                {t === "all" ? "All" : t === "donation" ? "Donations" : t === "event" ? "Events" : "Custom"}
              </button>
            ))}
          </div>
          <div className="min-w-[140px]">
            <label className="mb-1 block text-[10px] font-black text-[var(--color-ink)]">From</label>
            <input type="date" value={fromDate} onChange={(e) => changeFilter(setFromDate, e.target.value)}
              className="w-full rounded-md border border-[var(--color-hairline)] bg-[var(--color-canvas-soft)] px-2.5 py-1.5 text-[12px] font-medium outline-none focus:border-[var(--color-primary)]" />
          </div>
          <div className="min-w-[140px]">
            <label className="mb-1 block text-[10px] font-black text-[var(--color-ink)]">To</label>
            <input type="date" value={toDate} onChange={(e) => changeFilter(setToDate, e.target.value)}
              className="w-full rounded-md border border-[var(--color-hairline)] bg-[var(--color-canvas-soft)] px-2.5 py-1.5 text-[12px] font-medium outline-none focus:border-[var(--color-primary)]" />
          </div>
          <label className="flex min-h-9 flex-1 min-w-[200px] items-center gap-3 rounded-md border border-[var(--color-hairline)] bg-[var(--color-canvas-soft)] px-2.5">
            <span className="text-[11.5px] font-black text-[var(--color-primary)]">Q</span>
            <input value={search} onChange={(e) => changeFilter(setSearch, e.target.value)}
              className="w-full bg-transparent text-[12px] font-semibold text-[var(--color-ink)] outline-none placeholder:text-[var(--color-ink-mute)]"
              placeholder="Search by name or receipt no..." />
          </label>
        </div>
      </section>

      {/* Receipts Table */}
      <section className="overflow-hidden rounded-xl border border-[var(--color-hairline)] bg-white shadow-sm">
        <div className="flex items-center gap-2.5 border-b border-[var(--color-hairline)] bg-gradient-to-r from-[var(--color-canvas-soft)] to-[var(--color-canvas-soft)] px-4 py-3">
          <span className="grid h-7 w-7 place-items-center rounded-md bg-gradient-to-br from-[var(--color-primary)] to-[var(--color-primary-deep)] text-[12px] font-black text-white shadow-[0_4px_10px_rgba(91,98,240,0.3)]">R</span>
          <div>
            <h2 className="text-[13.5px] font-black text-[var(--color-ink)]">Receipts ({receipts.length})</h2>
            <p className="text-[10px] font-semibold text-[var(--color-ink-mute)]">View, print or share printable HTML receipts</p>
          </div>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full min-w-[900px] border-collapse text-left text-[12px]">
            <thead>
              <tr className="border-b border-[var(--color-hairline)] bg-[var(--color-canvas-soft)]">
                <th className="px-4 py-3 text-[10px] font-black uppercase tracking-[0.08em] text-[var(--color-ink-mute)]">Id</th>
                <th className="px-4 py-3 text-[10px] font-black uppercase tracking-[0.08em] text-[var(--color-ink-mute)]">Type</th>
                <th className="px-4 py-3 text-[10px] font-black uppercase tracking-[0.08em] text-[var(--color-ink-mute)]">Name</th>
                <th className="px-4 py-3 text-[10px] font-black uppercase tracking-[0.08em] text-[var(--color-ink-mute)]">Amount</th>
                <th className="px-4 py-3 text-[10px] font-black uppercase tracking-[0.08em] text-[var(--color-ink-mute)]">Purpose</th>
                <th className="px-4 py-3 text-[10px] font-black uppercase tracking-[0.08em] text-[var(--color-ink-mute)]">Date</th>
                <th className="px-4 py-3 text-[10px] font-black uppercase tracking-[0.08em] text-[var(--color-ink-mute)]">Email Sent</th>
                <th className="px-4 py-3 text-right text-[10px] font-black uppercase tracking-[0.08em] text-[var(--color-ink-mute)]">Actions</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr><td className="px-4 py-6 text-[12px] font-bold text-[var(--color-ink-mute)]" colSpan={8}>Loading receipts...</td></tr>
              ) : receipts.length ? pageReceipts.map((r) => (
                <tr key={`${r.type}-${r.id}`} className="border-b border-[var(--color-hairline)] bg-white align-middle transition last:border-b-0 hover:bg-[var(--color-canvas-soft)]">
                  <td className="px-4 py-3 text-[12px] font-black text-[var(--color-ink)]">{r.receipt_no || "-"}</td>
                  <td className="px-4 py-3">
                    <span className={`inline-flex rounded-full px-2.5 py-0.5 text-[11px] font-black ${typeColors[r.type]}`}>
                      {typeLabels[r.type]}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-[12px] font-medium text-[var(--color-ink)]">{r.donor_name}</td>
                  <td className="px-4 py-3 text-[12px] font-bold text-[var(--color-ink)]">Rs. {Number(r.amount).toLocaleString("en-IN")}</td>
                  <td className="px-4 py-3 max-w-[180px] truncate text-[12px] font-medium text-[var(--color-ink-mute)]">{r.purpose}</td>
                  <td className="px-4 py-3 text-[12px] font-medium text-[var(--color-ink-mute)]">
                    {r.date ? new Date(r.date).toLocaleDateString("en-IN") : "-"}
                  </td>
                  <td className="px-4 py-3">
                    {r.email_sent ? (
                      <span className="inline-flex rounded-full bg-[var(--color-canvas-soft)] px-2.5 py-0.5 text-[11px] font-black text-[var(--color-primary-deep)]">Sent</span>
                    ) : (
                      <span className="inline-flex rounded-full bg-[var(--color-canvas-soft)] px-2.5 py-0.5 text-[11px] font-black text-[var(--color-ink-mute)]">No</span>
                    )}
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex justify-end gap-1.5">
                      {r.type === "event" && !r.receipt_no ? (
                        <button
                          onClick={() => generateEventReceipt(r.id)}
                          disabled={generatingId === `event-${r.id}`}
                          className="rounded-md border border-[var(--color-primary)] bg-[var(--color-canvas-soft)] px-2.5 py-1.5 text-[11px] font-black text-[var(--color-primary)] transition hover:bg-[var(--color-primary)] hover:text-white disabled:opacity-50"
                        >
                          {generatingId === `event-${r.id}` ? "..." : "Generate"}
                        </button>
                      ) : null}
                      {r.receipt_no ? (
                        <>
                          <button
                            onClick={() => openViewReceipt(r.type, r.id, r.donor_name)}
                            className="flex items-center gap-1.5 rounded-md bg-[var(--color-primary-deep)] px-3 py-1.5 text-[11px] font-black text-white shadow-[0_4px_10px_rgba(15,107,79,0.2)] transition hover:bg-[var(--color-canvas-night)]"
                          >
                            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                              <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
                              <circle cx="12" cy="12" r="3" />
                            </svg>
                            View
                          </button>
                          <button
                            onClick={() => {
                              setShareModal({ type: r.type, id: r.id, name: r.donor_name, email: r.email || "" });
                              setShareEmail(r.email || "");
                            }}
                            className={"flex items-center gap-1.5 rounded-md border px-2.5 py-1.5 text-[11px] font-black transition " + (sentReceipts[`${r.type}-${r.id}`] || r.email_sent ? "border-[#d97706] bg-[#d97706] text-black hover:bg-[#b45309]" : "border-[var(--color-hairline)] bg-white text-[var(--color-ink)] hover:border-[var(--color-primary-deep)] hover:bg-[var(--color-canvas-soft)] hover:text-[var(--color-primary-deep)]")}
                          >
                            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                              <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z" />
                              <polyline points="22,6 12,13 2,6" />
                            </svg>
                            {sentReceipts[`${r.type}-${r.id}`] || r.email_sent ? "Share Again" : "Share"}
                          </button>
                        </>
                      ) : null}
                    </div>
                  </td>
                </tr>
              )) : (
                <tr><td className="px-4 py-6 text-[12px] font-bold text-[var(--color-ink-mute)]" colSpan={8}>No receipts found.</td></tr>
              )}
            </tbody>
          </table>
        </div>
        <TablePagination total={receipts.length} page={page} pageSize={PAGE_SIZE} onChange={setPage} label="receipts" />
      </section>

      {showCustomModal ? <CustomReceiptModal onClose={() => setShowCustomModal(false)} onCreated={async () => { setShowCustomModal(false); await loadReceipts(); }} token={token} /> : null}

      {viewModal ? (
        <div className="fixed inset-0 z-[80] grid place-items-center overflow-y-auto bg-black/45 p-4 backdrop-blur-sm" onClick={() => { setPrinting(false); setViewModal(null); }}>
          <section className="w-full max-w-[840px] rounded-md bg-[var(--color-canvas-soft)] p-4 shadow-2xl" onClick={(e) => e.stopPropagation()}>
            <div className="flex items-center justify-between gap-3">
              <div>
                <h2 className="text-[13.5px] font-black text-[var(--color-ink)]">Receipt â€” {viewModal.name}</h2>
                <p className="text-[11.5px] font-semibold text-[var(--color-ink-mute)]">{receiptData?.receipt_no || ""}</p>
              </div>
              <div className="flex items-center gap-2">
                <a
                  href={viewPublicUrl || ("/receipt?receiptNo=" + (receiptData?.receipt_no || ""))}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="rounded-md border border-[var(--color-hairline)] bg-white px-3 py-2 text-[11.5px] font-black text-[var(--color-ink)] transition hover:border-[var(--color-primary)] hover:text-[var(--color-primary)]"
                >
                  Open Direct Link
                </a>
                <button
                  onClick={handlePrint}
                  disabled={!receiptData || !viewPublicUrl || printing}
                  className="flex items-center gap-2 rounded-md bg-gradient-to-r from-[var(--color-primary-deep)] to-[var(--color-primary-deep)] px-4 py-2 text-[11.5px] font-black text-white shadow-[0_8px_18px_rgba(26,107,74,0.28)] transition hover:brightness-105 disabled:opacity-60"
                  title="Opens the invoice page, waits for it to load, then prints it on A4 portrait"
                >
                  {printing ? (
                    <>
                      <span className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-white/40 border-t-white" />
                      Preparing for print...
                    </>
                  ) : (
                    "Print"
                  )}
                </button>
                <button onClick={() => { setPrinting(false); setViewModal(null); }} className="rounded-md border border-[var(--color-hairline)] bg-white px-3 py-2 text-[11.5px] font-black text-[var(--color-ink)] transition hover:border-[var(--color-primary)] hover:text-[var(--color-primary)]">Close</button>
              </div>
            </div>

            <div className="mt-4 flex justify-center">
              {viewLoading ? (
                <div className="flex w-full items-center justify-center gap-2.5 rounded-md border border-[var(--color-hairline)] bg-white p-8 text-[11.5px] font-black text-[var(--color-ink)] shadow-sm">
                  <span className="h-3.5 w-3.5 animate-spin rounded-full border-2 border-[var(--color-hairline)] border-t-[var(--color-primary)]" />
                  Loading receipt...
                </div>
              ) : viewError ? (
                <p className="w-full rounded-md border border-[var(--color-hairline)] bg-[var(--color-canvas-soft)] p-4 text-[12px] font-bold text-[var(--color-ink)]">{viewError}</p>
              ) : receiptData ? (
                <ReceiptDisplay data={receiptData} />
              ) : null}
            </div>
          </section>
        </div>
      ) : null}

      {shareModal ? (
        <div className="fixed inset-0 z-[80] grid place-items-center bg-black/45 p-4 backdrop-blur-sm" onClick={() => setShareModal(null)}>
          <section className="w-full max-w-md rounded-md bg-white p-4 shadow-2xl" onClick={(e) => e.stopPropagation()}>
            <h2 className="text-[13.5px] font-black text-[var(--color-ink)]">Share Receipt</h2>
            <p className="mt-1 text-[12px] text-[var(--color-ink-mute)]">{"Send the public receipt link for " + shareModal.name + " via email"}</p>
            <div className="mt-3">
              <label className="mb-1 block text-[11.5px] font-black text-[var(--color-ink)]">Email Address</label>
              <input type="email" value={shareEmail} onChange={(e) => setShareEmail(e.target.value)} placeholder="Enter email address" className="w-full rounded-md border border-[var(--color-hairline)] bg-[var(--color-canvas-soft)] px-2.5 py-2 text-[12px] font-medium outline-none focus:border-[var(--color-primary)]" />
            </div>
            <p className="mt-3 rounded-md bg-[var(--color-canvas-soft)] px-3 py-2 text-[11px] font-semibold text-[var(--color-ink-mute)]">
              The recipient opens the link and can view and print the invoice instantly - no login needed.
            </p>
            <div className="mt-4 flex justify-end gap-2">
              <button onClick={() => setShareModal(null)} className="rounded-md border border-[var(--color-hairline)] px-3 py-2 text-[11.5px] font-black text-[var(--color-ink)] transition hover:border-[var(--color-primary)] hover:text-[var(--color-primary)]">Cancel</button>
              <button onClick={shareReceipt} disabled={sending} className="rounded-md bg-gradient-to-r from-[var(--color-primary-deep)] to-[var(--color-primary-deep)] px-4 py-2 text-[11.5px] font-black text-white shadow-[0_8px_18px_rgba(26,107,74,0.28)] transition hover:brightness-105 disabled:opacity-60">
                {sending ? "Sending..." : shareModal && sentReceipts[shareModal.type + "-" + shareModal.id] ? "Send Again" : "Send Email"}
              </button>
            </div>
          </section>
        </div>
      ) : null}

      <Toaster position="top-center" toastOptions={{ duration: 4000, style: { background: "#333", color: "#fff", fontSize: 14, fontWeight: 600 } }} />
    </div>
  );
}

function CustomReceiptModal({
  onClose,
  onCreated,
  token,
}: {
  onClose: () => void;
  onCreated: () => void;
  token: string;
}) {
  const [saving, setSaving] = useState(false);

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setSaving(true);

    const fd = new FormData(e.currentTarget);
    const body = {
      donor_name: fd.get("donor_name"),
      email: fd.get("email") || null,
      phone: fd.get("phone") || null,
      address: fd.get("address") || null,
      amount: Number(fd.get("amount")),
      payment_method: fd.get("payment_method") || null,
      purpose: fd.get("purpose"),
      receipt_date: fd.get("receipt_date"),
      notes: fd.get("notes") || null,
    };

    try {
      const res = await fetch(`${API}/admin/receipts/custom`, {
        method: "POST",
        headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
        body: JSON.stringify(body),
      });
      if (!res.ok) {
        const err = await res.json();
        toast.error(err.message || "Failed to create receipt");
        return;
      }
      toast.success("Custom receipt created");
      onCreated();
    } catch {
      toast.error("Failed to create receipt");
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="fixed inset-0 z-[80] grid place-items-center bg-black/45 p-4 backdrop-blur-sm">
      <section className="max-h-[88vh] w-full max-w-2xl overflow-hidden rounded-md bg-white shadow-2xl">
        <header className="flex items-center justify-between border-b border-[var(--color-hairline)] px-4 py-3">
          <div>
            <p className="text-[10px] font-black uppercase tracking-[0.14em] text-[var(--color-primary)]">Custom Receipt</p>
            <h2 className="mt-0.5 text-[13.5px] font-black text-[var(--color-ink)]">Create Custom Receipt</h2>
          </div>
          <button onClick={onClose} className="rounded-md border border-[var(--color-hairline)] px-2.5 py-1.5 text-[11.5px] font-black text-[var(--color-ink)] transition hover:border-[var(--color-primary)] hover:text-[var(--color-primary)]">Close</button>
        </header>
        <form onSubmit={handleSubmit} className="max-h-[70vh] overflow-y-auto p-4">
          <div className="grid gap-3 md:grid-cols-2">
            <label>
              <span className="mb-1.5 block text-[11.5px] font-black text-[var(--color-ink)]">Donor Name *</span>
              <input name="donor_name" required className="w-full rounded-md border border-[var(--color-hairline)] bg-[var(--color-canvas-soft)] px-2.5 py-2 text-[12px] font-medium outline-none focus:border-[var(--color-primary)] focus:ring-4 focus:ring-[var(--color-primary)]/10" />
            </label>
            <label>
              <span className="mb-1.5 block text-[11.5px] font-black text-[var(--color-ink)]">Email</span>
              <input name="email" type="email" className="w-full rounded-md border border-[var(--color-hairline)] bg-[var(--color-canvas-soft)] px-2.5 py-2 text-[12px] font-medium outline-none focus:border-[var(--color-primary)] focus:ring-4 focus:ring-[var(--color-primary)]/10" />
            </label>
            <label>
              <span className="mb-1.5 block text-[11.5px] font-black text-[var(--color-ink)]">Phone</span>
              <input name="phone" className="w-full rounded-md border border-[var(--color-hairline)] bg-[var(--color-canvas-soft)] px-2.5 py-2 text-[12px] font-medium outline-none focus:border-[var(--color-primary)] focus:ring-4 focus:ring-[var(--color-primary)]/10" />
            </label>
            <label>
              <span className="mb-1.5 block text-[11.5px] font-black text-[var(--color-ink)]">Amount (Rs.) *</span>
              <input name="amount" type="number" step="0.01" required className="w-full rounded-md border border-[var(--color-hairline)] bg-[var(--color-canvas-soft)] px-2.5 py-2 text-[12px] font-medium outline-none focus:border-[var(--color-primary)] focus:ring-4 focus:ring-[var(--color-primary)]/10" />
            </label>
            <label>
              <span className="mb-1.5 block text-[11.5px] font-black text-[var(--color-ink)]">Payment Method</span>
              <select name="payment_method" className="w-full rounded-md border border-[var(--color-hairline)] bg-[var(--color-canvas-soft)] px-2.5 py-2 text-[12px] font-medium text-[var(--color-ink)] outline-none focus:border-[var(--color-primary)] focus:ring-4 focus:ring-[var(--color-primary)]/10">
                <option value="">â€” Select â€”</option>
                <option>Cash</option>
                <option>Cheque</option>
                <option>Bank Transfer</option>
                <option>UPI</option>
                <option>PhonePe</option>
                <option>Online</option>
              </select>
            </label>
            <label className="md:col-span-2">
              <span className="mb-1.5 block text-[11.5px] font-black text-[var(--color-ink)]">Purpose *</span>
              <input name="purpose" required className="w-full rounded-md border border-[var(--color-hairline)] bg-[var(--color-canvas-soft)] px-2.5 py-2 text-[12px] font-medium outline-none focus:border-[var(--color-primary)] focus:ring-4 focus:ring-[var(--color-primary)]/10" />
            </label>
            <label className="md:col-span-2">
              <span className="mb-1.5 block text-[11.5px] font-black text-[var(--color-ink)]">Address</span>
              <textarea name="address" rows={2} className="w-full rounded-md border border-[var(--color-hairline)] bg-[var(--color-canvas-soft)] px-2.5 py-2 text-[12px] font-medium outline-none focus:border-[var(--color-primary)] focus:ring-4 focus:ring-[var(--color-primary)]/10" />
            </label>
            <label>
              <span className="mb-1.5 block text-[11.5px] font-black text-[var(--color-ink)]">Receipt Date *</span>
              <input name="receipt_date" type="date" required defaultValue={new Date().toISOString().slice(0, 10)} className="w-full rounded-md border border-[var(--color-hairline)] bg-[var(--color-canvas-soft)] px-2.5 py-2 text-[12px] font-medium outline-none focus:border-[var(--color-primary)] focus:ring-4 focus:ring-[var(--color-primary)]/10" />
            </label>
            <label>
              <span className="mb-1.5 block text-[11.5px] font-black text-[var(--color-ink)]">Notes</span>
              <input name="notes" className="w-full rounded-md border border-[var(--color-hairline)] bg-[var(--color-canvas-soft)] px-2.5 py-2 text-[12px] font-medium outline-none focus:border-[var(--color-primary)] focus:ring-4 focus:ring-[var(--color-primary)]/10" />
            </label>
          </div>
          <div className="mt-4 flex justify-end gap-2 border-t border-[var(--color-hairline)] pt-4">
            <button type="button" onClick={onClose} className="rounded-md border border-[var(--color-hairline)] px-3 py-2 text-[11.5px] font-black text-[var(--color-ink)] transition hover:border-[var(--color-primary)] hover:text-[var(--color-primary)]">Cancel</button>
            <button disabled={saving} className="rounded-md bg-gradient-to-r from-[var(--color-primary)] to-[var(--color-primary-deep)] px-4 py-2 text-[11.5px] font-black text-white shadow-[0_8px_18px_rgba(93,111,241,0.28)] disabled:opacity-50 transition hover:brightness-105">
              {saving ? "Creating..." : "Create Receipt"}
            </button>
          </div>
        </form>
      </section>
    </div>
  );
}
