import { createFileRoute, Link } from "@tanstack/react-router";
import { AppShell, PageHeader } from "@/components/app-shell";
import { StadiumLiveStrip } from "@/components/stadium/live-strip";
import { GameRulesCard } from "@/components/stadium/game-rules";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { EVENT_CATALOG, TRACTION_THRESHOLD, footballFromPoints } from "@/lib/stadium-scoring";
import { getAdminStadium } from "@/lib/server/api-stadium";
import { getShellMeta } from "@/lib/server/api-core";
import { formatDateTime } from "@/lib/utils";

export const Route = createFileRoute("/admin/stadium")({
  loader: async () => {
    const [meta, stadium] = await Promise.all([getShellMeta(), getAdminStadium()]);
    return { meta, stadium };
  },
  component: Page,
});

function Page() {
  const { meta, stadium } = Route.useLoaderData();
  const home = stadium.home;
  const away = stadium.away;
  const homeFb = home ? footballFromPoints(home.points) : null;
  const awayFb = away ? footballFromPoints(away.points) : null;
  const movers = (stadium.movers ?? []).filter((m) => m.traction || m.stadium_points >= TRACTION_THRESHOLD);

  return (
    <AppShell hold={meta.hold} unread={meta.unread} noticeCount={meta.noticeCount} inboxUnread={meta.inboxUnread}>
      <PageHeader
        kicker="Super Admin · stadium"
        title="Live scoring desk"
        description="Business points recorded from the deal room, fan votes, and studio answers. One point is one yard. Athletes over the traction line can be moved onto a hotter team."
        actions={
          <Button asChild>
            <Link to="/public/stadium">Open public stadium</Link>
          </Button>
        }
      />
      <StadiumLiveStrip />
      <GameRulesCard />

      {home && away && homeFb && awayFb ? (
        <div className="mb-6 grid gap-3 sm:grid-cols-2">
          <Card>
            <CardContent className="pt-5">
              <p className="text-[11px] font-medium tracking-[0.16em] text-muted-foreground uppercase">Home</p>
              <h2 className="font-display text-2xl">{home.name}</h2>
              <p className="mt-2 font-display text-4xl tabular">{homeFb.displayScore}</p>
              <p className="mt-1 text-sm text-muted-foreground">
                {home.points} business pts · {home.driveYards} yd · {homeFb.down} & {homeFb.toGo} · {home.votes} votes
              </p>
            </CardContent>
          </Card>
          <Card>
            <CardContent className="pt-5">
              <p className="text-[11px] font-medium tracking-[0.16em] text-muted-foreground uppercase">Away</p>
              <h2 className="font-display text-2xl">{away.name}</h2>
              <p className="mt-2 font-display text-4xl tabular">{awayFb.displayScore}</p>
              <p className="mt-1 text-sm text-muted-foreground">
                {away.points} business pts · {away.driveYards} yd · {awayFb.down} & {awayFb.toGo} · {away.votes} votes
              </p>
            </CardContent>
          </Card>
        </div>
      ) : null}

      <div className="mb-6 grid gap-4 lg:grid-cols-5">
        <Card className="lg:col-span-3">
          <CardContent className="pt-5">
            <h2 className="mb-3 font-display text-xl">Traction — students to move</h2>
            <p className="mb-4 text-sm text-muted-foreground">
              Flagged at {TRACTION_THRESHOLD} stadium points from deal-room work and votes. These are the athletes a
              coach would pull onto another studio team.
            </p>
            <div className="overflow-x-auto">
              <table className="w-full min-w-[32rem] 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">Athlete</th>
                    <th className="pb-2 font-medium">Team</th>
                    <th className="pb-2 font-medium text-right">Stadium</th>
                    <th className="pb-2 font-medium text-right">Academy</th>
                    <th className="pb-2 font-medium">Flag</th>
                  </tr>
                </thead>
                <tbody>
                  {(stadium.movers ?? []).map((m) => (
                    <tr key={m.member_id} className="border-b border-border/70">
                      <td className="py-2.5">
                        <p className="font-medium">{m.full_name}</p>
                        <p className="text-xs text-muted-foreground">{m.email}</p>
                      </td>
                      <td className="py-2.5">{m.team_name ?? "—"}</td>
                      <td className="py-2.5 text-right tabular font-semibold">{m.stadium_points}</td>
                      <td className="py-2.5 text-right tabular text-muted-foreground">{m.academy_yards}</td>
                      <td className="py-2.5">
                        {m.traction ? <Badge variant="success">Traction</Badge> : <Badge variant="muted">Watch</Badge>}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            {movers.length > 0 ? (
              <p className="mt-3 text-sm text-muted-foreground">
                {movers.length} athlete{movers.length === 1 ? "" : "s"} currently above the traction line.
              </p>
            ) : null}
          </CardContent>
        </Card>

        <Card className="lg:col-span-2">
          <CardContent className="pt-5">
            <h2 className="mb-3 font-display text-xl">Alert list</h2>
            <p className="mb-3 text-sm text-muted-foreground">Public, donor, and student emails waiting on team news.</p>
            <ul className="space-y-2">
              {(stadium.alerts ?? []).map((a) => (
                <li key={a.id} className="text-sm">
                  <p className="font-medium">{a.email}</p>
                  <p className="text-xs text-muted-foreground">
                    {a.team_name} · {a.role} · {formatDateTime(a.created_at)}
                  </p>
                </li>
              ))}
              {(stadium.alerts ?? []).length === 0 ? (
                <li className="text-sm text-muted-foreground">No alert signups yet.</li>
              ) : null}
            </ul>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardContent className="pt-5">
          <h2 className="mb-3 font-display text-xl">Scoring catalog</h2>
          <ul className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
            {Object.entries(EVENT_CATALOG).map(([key, spec]) => (
              <li key={key} className="rounded-lg bg-muted/70 px-3 py-2">
                <p className="text-sm font-medium">{spec.label}</p>
                <p className="text-xs text-muted-foreground">{spec.hint}</p>
              </li>
            ))}
          </ul>
        </CardContent>
      </Card>
    </AppShell>
  );
}
