import { createFileRoute } from "@tanstack/react-router";
import { useEffect, useMemo, useState } from "react";
import { PageHeader, EmptyState } from "@/components/common/PageHeader";
import { Badge } from "@/components/ui/badge";
import { reportsService } from "@/services/api/reports";
import type { PlayerReport, ReportStatus } from "@/types";
import { useAuthStore } from "@/store/auth";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Link } from "@tanstack/react-router";
import { Input } from "@/components/ui/input";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Flag, Search } from "lucide-react";
import { players } from "@/features/_mock/data";
import { usePagination, Pager } from "@/components/common/DataPager";

export const Route = createFileRoute("/_public/account/reports")({
  head: () => ({ meta: [{ title: "Reports — Account" }] }),
  component: ReportsPage,
});

const TONE: Record<ReportStatus, string> = {
  submitted: "border-muted-foreground/40 text-muted-foreground",
  pending_review: "border-info/40 text-info",
  investigating: "border-warning/40 text-warning",
  more_info: "border-warning/40 text-warning",
  resolved: "border-success/40 text-success",
  rejected: "border-destructive/40 text-destructive",
};

function ReportsPage() {
  const user = useAuthStore((s) => s.user);
  const [list, setList] = useState<PlayerReport[]>([]);
  useEffect(() => { reportsService.list(user?.id).then(setList); }, [user?.id]);
  const { paged, page, setPage, totalPages, total } = usePagination(list, 10);

  return (
    <div className="space-y-4">
      <PageHeader
        title="My reports"
        description="Player reports you have submitted."
        actions={<NewReportButton />}
      />
      {list.length === 0 ? (
        <EmptyState title="No reports yet" hint="Use the New report button above, or report from a player profile." />
      ) : (
        <>
        <div className="overflow-hidden rounded-xl border border-border bg-card">
          <table className="w-full text-sm">
            <thead className="bg-surface text-left text-xs uppercase text-muted-foreground">
              <tr><th className="px-3 py-2.5">ID</th><th className="px-3 py-2.5">Player</th><th className="px-3 py-2.5">Category</th><th className="px-3 py-2.5">Status</th><th className="px-3 py-2.5">Submitted</th></tr>
            </thead>
            <tbody className="divide-y divide-border/40">
              {paged.map((r) => (
                <tr key={r.id} className="hover:bg-surface/40">
                  <td className="px-3 py-2.5 font-mono text-xs">{r.id}</td>
                  <td className="px-3 py-2.5">{r.reportedPlayerName}</td>
                  <td className="px-3 py-2.5 capitalize">{r.category.replace("_", " ")}</td>
                  <td className="px-3 py-2.5"><Badge variant="outline" className={TONE[r.status]}>{r.status.replace("_", " ")}</Badge></td>
                  <td className="px-3 py-2.5 text-muted-foreground">{r.createdAt}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <Pager page={page} totalPages={totalPages} onChange={setPage} total={total} />
        </>
      )}
    </div>
  );
}

function NewReportButton() {
  const [q, setQ] = useState("");
  const filtered = useMemo(
    () => players.filter((p) => p.name.toLowerCase().includes(q.toLowerCase()) || p.steamId.includes(q)).slice(0, 8),
    [q],
  );
  return (
      <Dialog>
        <DialogTrigger asChild>
          <Button className="gradient-primary text-primary-foreground shadow-glow hover:opacity-95">
            <Flag className="mr-1.5 h-4 w-4" /> New report
          </Button>
        </DialogTrigger>
        <DialogContent className="max-w-md">
          <DialogHeader><DialogTitle>Pick a player to report</DialogTitle></DialogHeader>
          <div className="relative">
            <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <Input placeholder="Search by name or Steam ID…" value={q} onChange={(e) => setQ(e.target.value)} className="pl-9" />
          </div>
          <div className="max-h-72 space-y-1 overflow-y-auto">
            {filtered.map((p) => (
              <Link
                key={p.id}
                to="/players/$playerId"
                params={{ playerId: p.id }}
                className="flex items-center gap-2 rounded-md p-2 transition-colors hover:bg-surface"
              >
                <Avatar className="h-8 w-8"><AvatarImage src={p.avatar} /><AvatarFallback>{p.name[0]}</AvatarFallback></Avatar>
                <div className="min-w-0 flex-1">
                  <div className="truncate text-sm font-medium">{p.name}</div>
                  <div className="truncate font-mono text-[11px] text-muted-foreground">{p.steamId}</div>
                </div>
                <Flag className="h-3.5 w-3.5 text-secondary" />
              </Link>
            ))}
            {filtered.length === 0 && <div className="p-4 text-center text-xs text-muted-foreground">No players match.</div>}
          </div>
          <p className="text-[11px] text-muted-foreground">Open a profile to submit the full report with evidence.</p>
        </DialogContent>
      </Dialog>
  );
}