import { useState } from "react";
import { Link } from "react-router-dom";
import {
  AlertTriangle,
  CheckCircle2,
  FileText,
  Search,
  Sparkles,
} from "lucide-react";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Skeleton } from "@/components/ui/skeleton";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";

import { useExamReviewQueue } from "@/hooks/queries/useExamReview";

/**
 * Admin-facing queue of AI-generated exams that failed the automated quality
 * gate and need a human to sign off before they can be published to students.
 *
 * The list intentionally stays dense — each row shows only the signals an
 * operator needs to prioritise (quality score, failing-question count, AI
 * model used). Clicking through to the detail page reveals the full report.
 */
export default function ExamReviewQueue() {
  const [search, setSearch] = useState("");
  const [page, setPage] = useState(1);
  const pageSize = 20;

  const { data, isLoading } = useExamReviewQueue({
    page,
    size: pageSize,
    search: search || undefined,
    status: "pending_review",
  });

  const items = data?.items ?? [];
  const total = data?.total ?? 0;
  const pageCount = Math.max(1, Math.ceil(total / pageSize));

  return (
    <div className="space-y-4">
      <div className="flex items-start justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">Exam Review Queue</h1>
          <p className="text-sm text-muted-foreground mt-1">
            AI-generated exams that failed the automated quality gate. Review
            each one, then approve to publish or reject back to draft.
          </p>
        </div>
        <Badge variant="secondary" className="gap-1">
          <Sparkles className="h-3 w-3" />
          {total} awaiting review
        </Badge>
      </div>

      <Card>
        <CardHeader className="pb-3">
          <div className="flex items-center gap-3">
            <div className="relative flex-1 max-w-sm">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder="Search by exam title…"
                value={search}
                onChange={(e) => {
                  setPage(1);
                  setSearch(e.target.value);
                }}
                className="pl-9"
              />
            </div>
          </div>
        </CardHeader>
        <CardContent className="p-0">
          {isLoading ? (
            <div className="p-6 space-y-2">
              <Skeleton className="h-10 w-full" />
              <Skeleton className="h-10 w-full" />
              <Skeleton className="h-10 w-full" />
            </div>
          ) : items.length === 0 ? (
            <div className="p-10 text-center">
              <CheckCircle2 className="mx-auto h-10 w-10 text-muted-foreground mb-3" />
              <p className="text-sm text-muted-foreground">
                Nothing in the review queue. Any time an AI-generated exam
                fails the quality gate, it will show up here.
              </p>
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-[32%]">Exam</TableHead>
                  <TableHead>Subject</TableHead>
                  <TableHead className="text-center">Questions</TableHead>
                  <TableHead className="text-center">Avg. Quality</TableHead>
                  <TableHead className="text-center">Failing</TableHead>
                  <TableHead className="text-right">Action</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {items.map((exam) => {
                  const avg = exam.summary.avg_quality_score;
                  const failing = exam.summary.failing_count;
                  return (
                    <TableRow key={exam.id}>
                      <TableCell>
                        <div className="flex items-start gap-2">
                          <FileText className="h-4 w-4 text-muted-foreground mt-0.5 shrink-0" />
                          <div className="min-w-0">
                            <Link
                              to={`/admin/exam/review/${exam.id}`}
                              className="font-medium hover:underline"
                            >
                              {exam.title}
                            </Link>
                            <div className="text-xs text-muted-foreground mt-0.5">
                              {exam.summary.ai_generated_count} AI-generated ·{" "}
                              {exam.teacher_name || "Unassigned"}
                            </div>
                          </div>
                        </div>
                      </TableCell>
                      <TableCell className="text-sm">
                        {exam.subject_name || "—"}
                      </TableCell>
                      <TableCell className="text-center text-sm">
                        {exam.summary.question_count}
                      </TableCell>
                      <TableCell className="text-center">
                        <Badge
                          variant={
                            avg >= 0.85
                              ? "default"
                              : avg >= 0.7
                                ? "secondary"
                                : "destructive"
                          }
                          className="tabular-nums"
                        >
                          {(avg * 100).toFixed(0)}%
                        </Badge>
                      </TableCell>
                      <TableCell className="text-center">
                        {failing > 0 ? (
                          <Badge variant="destructive" className="gap-1">
                            <AlertTriangle className="h-3 w-3" />
                            {failing}
                          </Badge>
                        ) : (
                          <span className="text-muted-foreground text-sm">—</span>
                        )}
                      </TableCell>
                      <TableCell className="text-right">
                        <Button asChild size="sm" variant="outline">
                          <Link to={`/admin/exam/review/${exam.id}`}>Review</Link>
                        </Button>
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      {pageCount > 1 && (
        <div className="flex items-center justify-between text-sm">
          <span className="text-muted-foreground">
            Page {page} of {pageCount} · {total} total
          </span>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              disabled={page <= 1}
              onClick={() => setPage((p) => Math.max(1, p - 1))}
            >
              Previous
            </Button>
            <Button
              variant="outline"
              size="sm"
              disabled={page >= pageCount}
              onClick={() => setPage((p) => Math.min(pageCount, p + 1))}
            >
              Next
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}
