import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { honorProjectGift } from "@/lib/server/api-donations";
import { moneyCents } from "@/lib/utils";

const AMOUNTS = [50, 100, 250, 500, 1000];

type Kind = "anonymous" | "professor" | "memorial" | "team" | "named";

const KINDS: { id: Kind; label: string; hint: string }[] = [
  { id: "team", label: "The student team", hint: "In honor of the athletes building this project." },
  { id: "professor", label: "A professor or coach", hint: "Name the faculty member who shepherds the work." },
  { id: "memorial", label: "In memory", hint: "Someone lost to the injury or illness this project is studying." },
  { id: "named", label: "Someone I name", hint: "A family member, a teammate, a trainer." },
  { id: "anonymous", label: "Anonymous", hint: "The receipt still shows your name. The public honor line does not." },
];

export function HonorGiftForm({
  email,
  donorName,
  projectName,
  teamId,
  professorExample,
}: {
  email?: string;
  donorName?: string;
  projectName: string;
  teamId: string;
  professorExample: string;
}) {
  const [kind, setKind] = useState<Kind>("team");
  const [honorName, setHonorName] = useState("");
  const [amount, setAmount] = useState("100");
  const [busy, setBusy] = useState(false);
  const [receipt, setReceipt] = useState<string | null>(null);
  const [giverName, setGiverName] = useState(donorName ?? "");
  const [giverEmail, setGiverEmail] = useState(email ?? "");
  const dollars = Number(amount);
  const askIdentity = !email || !donorName;

  async function give() {
    const name = (giverName || donorName || "").trim();
    const mail = (giverEmail || email || "").trim().toLowerCase();
    if (name.length < 2) {
      toast.error("Put the name the receipt should carry.");
      return;
    }
    if (!mail.includes("@")) {
      toast.error("We need an email for the receipt. CFL does not sell it.");
      return;
    }
    setBusy(true);
    try {
      const result = await honorProjectGift({
        data: {
          email: mail,
          donorName: name,
          amount: dollars,
          projectName,
          teamId,
          honorKind: kind,
          honorName: honorName || professorExample,
        },
      });
      setReceipt(result.receiptId ?? result.id);
      toast.success(`Thank you. ${moneyCents(Math.round(dollars * 100))} is on the education program for ${projectName}.`);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Gift did not post.");
    } finally {
      setBusy(false);
    }
  }

  const needsName = kind === "professor" || kind === "memorial" || kind === "named";

  return (
    <div className="mt-5 rounded-lg border border-gold-ink/40 bg-gold-wash px-4 py-4">
      <p className="text-[11px] font-semibold tracking-[0.16em] text-gold-ink uppercase">Give in honor of this project</p>
      <h3 className="mt-1 font-display text-lg text-navy">I would like to make a donation in the amount of</h3>
      <p className="mt-1 text-sm text-navy">
        Restricted to the {projectName} education program. Not an investment. CFL takes no equity. You can give in honor
        of the team, a professor, or someone this work might have helped.
      </p>
      {askIdentity ? (
        <div className="mt-3 grid gap-3 sm:grid-cols-2">
          <div>
            <Label htmlFor={`gn-${teamId}`}>Your name (for the receipt)</Label>
            <Input id={`gn-${teamId}`} className="mt-1" value={giverName} onChange={(e) => setGiverName(e.target.value)} />
          </div>
          <div>
            <Label htmlFor={`ge-${teamId}`}>Email</Label>
            <Input
              id={`ge-${teamId}`}
              type="email"
              className="mt-1"
              value={giverEmail}
              onChange={(e) => setGiverEmail(e.target.value)}
            />
          </div>
        </div>
      ) : null}
      <div className="mt-3 flex flex-wrap gap-2">
        {AMOUNTS.map((n) => (
          <Button key={n} type="button" size="sm" variant={Number(amount) === n ? "gold" : "outline"} onClick={() => setAmount(String(n))}>
            ${n.toLocaleString("en-US")}
          </Button>
        ))}
      </div>
      <div className="mt-3 max-w-xs">
        <Label htmlFor={`amt-${teamId}`}>Amount (USD)</Label>
        <div className="mt-1 flex items-center gap-2">
          <span className="text-sm font-semibold text-navy">$</span>
          <Input
            id={`amt-${teamId}`}
            inputMode="decimal"
            value={amount}
            onChange={(e) => setAmount(e.target.value.replace(/[^\d.]/g, ""))}
          />
        </div>
      </div>
      <p className="mt-4 text-sm font-semibold text-navy">In honor of</p>
      <ul className="mt-2 space-y-2">
        {KINDS.map((k) => (
          <li key={k.id}>
            <label className="flex cursor-pointer items-start gap-2 text-sm text-navy">
              <input
                type="radio"
                className="mt-1"
                name={`honor-${teamId}`}
                checked={kind === k.id}
                onChange={() => {
                  setKind(k.id);
                  if (k.id === "professor" && !honorName) setHonorName(professorExample);
                }}
              />
              <span>
                <span className="font-semibold">{k.label}</span>
                <span className="block text-xs">{k.hint}</span>
              </span>
            </label>
          </li>
        ))}
      </ul>
      {needsName ? (
        <div className="mt-3 max-w-md">
          <Label htmlFor={`hon-${teamId}`}>Name</Label>
          <Input
            id={`hon-${teamId}`}
            className="mt-1"
            placeholder={kind === "professor" ? professorExample : kind === "memorial" ? "In memory of…" : "Name"}
            value={honorName}
            onChange={(e) => setHonorName(e.target.value)}
          />
        </div>
      ) : null}
      {receipt ? (
        <p className="mt-3 text-sm font-semibold text-navy">Receipt {receipt} is on your gifts list. Thank you.</p>
      ) : (
        <Button className="mt-4" variant="gold" disabled={busy || !Number.isFinite(dollars) || dollars < 5} onClick={() => void give()}>
          {busy ? "Recording…" : `Donate $${Number.isFinite(dollars) ? dollars.toLocaleString("en-US") : "—"} in honor of this project`}
        </Button>
      )}
    </div>
  );
}