import { createFileRoute } from "@tanstack/react-router";
import { useEffect, useMemo, useState } from "react";
import { PageHeader } from "@/components/common/PageHeader";
import { AdminDataTable, type Column } from "@/components/common/AdminDataTable";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { appealsService } from "@/services/api/appeals";
import type { Appeal, AppealStatus } from "@/types";
import { toast } from "sonner";

export const Route = createFileRoute("/admin/appeals")({
  head: () => ({ meta: [{ title: "Appeals — Admin" }] }),
  component: AdminAppealsPage,
});

const STATUSES: AppealStatus[] = ["submitted", "under_review", "more_info", "approved", "rejected", "closed"];

function AdminAppealsPage() {
  const [rows, setRows] = useState<Appeal[]>([]);
  const [q, setQ] = useState("");
  const [status, setStatus] = useState<string>("all");
  useEffect(() => { appealsService.list().then(setRows); }, []);

  const filtered = useMemo(() => rows.filter((a) =>
    (status === "all" || a.status === status) &&
    (q === "" || a.playerName.toLowerCase().includes(q.toLowerCase()) || a.id.includes(q) || a.punishmentId.includes(q))
  ), [rows, q, status]);

  async function setSt(id: string, s: AppealStatus) {
    const next = await appealsService.setStatus(id, s);
    setRows((rs) => rs.map((r) => r.id === next.id ? next : r));
    toast.success(`Marked ${s.replace("_", " ")}`);
  }

  const cols: Column<Appeal>[] = [
    { key: "id", header: "ID", cell: (a) => <span className="font-mono text-xs">{a.id}</span> },
    { key: "player", header: "Player", cell: (a) => a.playerName },
    { key: "pun", header: "Punishment", cell: (a) => <span className="font-mono text-xs">{a.punishmentId}</span> },
    { key: "reason", header: "Reason", cell: (a) => a.reason },
    { key: "status", header: "Status", cell: (a) => <Badge variant="outline" className="capitalize">{a.status.replace("_", " ")}</Badge> },
    { key: "adm", header: "Assigned", cell: (a) => a.assignedAdmin ?? "—" },
    { key: "when", header: "Updated", cell: (a) => <span className="text-muted-foreground">{a.updatedAt}</span> },
  ];

  return (
    <div>
      <PageHeader title="Punishment appeals" description="Review player appeals and update their status." />
      <AdminDataTable
        rows={filtered} columns={cols} search={q} onSearchChange={setQ}
        filters={
          <Select value={status} onValueChange={setStatus}>
            <SelectTrigger className="w-[180px]"><SelectValue /></SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All statuses</SelectItem>
              {STATUSES.map((s) => <SelectItem key={s} value={s} className="capitalize">{s.replace("_", " ")}</SelectItem>)}
            </SelectContent>
          </Select>
        }
        rowActions={(a) => (
          <div className="flex justify-end gap-1">
            <Button size="sm" variant="outline" onClick={() => setSt(a.id, "under_review")}>Review</Button>
            <Button size="sm" variant="outline" onClick={() => setSt(a.id, "approved")}>Approve</Button>
            <Button size="sm" variant="ghost" onClick={() => setSt(a.id, "rejected")}>Reject</Button>
          </div>
        )}
      />
    </div>
  );
}
