import { useState } from "react";
import { toast } from "sonner";
import { Gift, Vote } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { footballFromPoints, downLabel } from "@/lib/stadium-scoring";
import { MERCH_SKUS, castStadiumVote, orderStadiumMerch, type StadiumPlay, type StadiumTeamBoard } from "@/lib/server/api-stadium";
import { AuctionPaddle } from "./auction-paddle";
import { haptic } from "@/lib/haptics";

export function isShowcase(home: StadiumTeamBoard, away: StadiumTeamBoard | null) {
  return !away || away.id === home.id;
}

export function SeatTray({
  home,
  away,
  plays,
  email,
  onMoved,
}: {
  home: StadiumTeamBoard;
  away: StadiumTeamBoard | null;
  plays: StadiumPlay[];
  email: string;
  onMoved: () => Promise<void>;
}) {
  const solo = isShowcase(home, away);
  const [addr, setAddr] = useState(email.includes("@") && !email.startsWith("public@") ? email : "");
  const [busy, setBusy] = useState(false);
  const h = footballFromPoints(home.points);
  const a = away ? footballFromPoints(away.points) : null;
  const recent = plays.slice(0, 3);

  async function vote(teamId: string) {
    setBusy(true);
    try {
      const res = await castStadiumVote({ data: { email: addr, teamId } });
      toast.success(`Vote recorded · ${res.points} yards. The ball moved.`);
      haptic("score");
      await onMoved();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Could not record the vote.");
    } finally {
      setBusy(false);
    }
  }

  async function merch(sku: string) {
    setBusy(true);
    try {
      const res = await orderStadiumMerch({ data: { email: addr, sku, teamId: home.id } });
      toast.success(`${res.label} · $${res.price}. We’ll email you from the CFL shop.`);
      haptic("tap");
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Could not take that order.");
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="seat-tray" onPointerDown={(e) => e.stopPropagation()}>
      <div className={`seat-dashboards ${solo ? "solo" : ""}`}>
        <TeamDash side="home" team={home} fb={h} showcase={solo} />
        <div className="seat-field-gap" aria-hidden />
        {!solo && away && a ? <TeamDash side="away" team={away} fb={a} showcase={false} /> : null}
      </div>

      <div className="seat-dock">
        {recent.length ? (
          <ul className="seat-plays">
            {recent.map((p) => (
              <li key={p.id}>
                <span>{p.team_name}</span> {p.note ?? p.event_type} <em>+{p.points}</em>
              </li>
            ))}
          </ul>
        ) : null}

        <div className="seat-actions">
          <Input
            value={addr}
            onChange={(e) => setAddr(e.target.value)}
            placeholder="Email to vote or order"
            className="h-9 border-sidebar-border bg-navy/80 text-sidebar-foreground"
          />
          <Button size="sm" disabled={busy} onClick={() => void vote(home.id)}>
            <Vote className="size-3.5" />
            Vote {home.name.split(" ")[0]}
          </Button>
          {!solo && away ? (
            <Button size="sm" variant="secondary" disabled={busy} onClick={() => void vote(away.id)}>
              <Vote className="size-3.5" />
              Vote {away.name.split(" ")[0]}
            </Button>
          ) : null}
        </div>

        <div className="seat-shop">
          <p>
            <Gift className="inline size-3.5" /> From this seat · CFL souvenirs
          </p>
          <div>
            {MERCH_SKUS.map((item) => (
              <button key={item.sku} type="button" disabled={busy} onClick={() => void merch(item.sku)}>
                {item.label}
                <span>${item.price}</span>
              </button>
            ))}
          </div>
        </div>
        <AuctionPaddle compact />
      </div>
    </div>
  );
}

function TeamDash({
  side,
  team,
  fb,
  showcase,
}: {
  side: "home" | "away";
  team: StadiumTeamBoard;
  fb: ReturnType<typeof footballFromPoints>;
  showcase: boolean;
}) {
  return (
    <article className={`seat-dash ${side}`}>
      <p>{showcase ? "Tonight’s venture" : side === "home" ? "Home" : "Away"}</p>
      <h3>{team.name}</h3>
      <p className="seat-dash-cat">{team.category}</p>
      <p className="seat-dash-blurb">{team.blurb}</p>
      <p className="seat-dash-score tabular">
        {fb.displayScore} pts · {team.points} yards · {downLabel(fb)} · {team.votes} votes
      </p>
    </article>
  );
}
