import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Checkbox } from "@/components/ui/checkbox";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import {
  useBulkRelease,
  usePendingScores,
  useRejectScore,
  useReleaseScore,
} from "@/hooks/queries/useScoreRelease";
import type { PendingScore } from "@/types";
import { toast } from "sonner";

export default function ScoreApprovalQueue() {
  const { data, isLoading, refetch } = usePendingScores();
  const release = useReleaseScore();
  const reject = useRejectScore();
  const bulk = useBulkRelease();

  const [selected, setSelected] = useState<Set<number>>(new Set());
  const [rejectOpen, setRejectOpen] = useState(false);
  const [rejectTarget, setRejectTarget] = useState<PendingScore | null>(null);
  const [reason, setReason] = useState("");

  const rows: PendingScore[] = data?.data ?? [];

  const toggle = (attemptId: number) => {
    setSelected((prev) => {
      const n = new Set(prev);
      if (n.has(attemptId)) n.delete(attemptId);
      else n.add(attemptId);
      return n;
    });
  };

  const toggleAll = (checked: boolean) => {
    if (!checked) setSelected(new Set());
    else setSelected(new Set(rows.map((r) => r.attempt_id)));
  };

  const approveOne = (attemptId: number) => {
    release.mutate(attemptId, {
      onSuccess: () => {
        toast.success("Released.");
        refetch();
      },
      onError: (e) => toast.error(e instanceof Error ? e.message : "Failed"),
    });
  };

  const openReject = (row: PendingScore) => {
    setRejectTarget(row);
    setReason("");
    setRejectOpen(true);
  };

  const submitReject = () => {
    if (!rejectTarget) return;
    reject.mutate(
      { attemptId: rejectTarget.attempt_id, reason },
      {
        onSuccess: () => {
          toast.success("Rejected.");
          setRejectOpen(false);
          refetch();
        },
        onError: (e) => toast.error(e instanceof Error ? e.message : "Failed"),
      },
    );
  };

  const bulkApprove = () => {
    const ids = [...selected];
    if (!ids.length) return;
    bulk.mutate(ids, {
      onSuccess: () => {
        toast.success("Bulk release complete.");
        setSelected(new Set());
        refetch();
      },
      onError: (e) => toast.error(e instanceof Error ? e.message : "Failed"),
    });
  };

  return (
    <div className="space-y-6 p-6 max-w-6xl mx-auto">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight">Pending score releases</h1>
          <p className="text-muted-foreground text-sm mt-1">Approve before students see results</p>
        </div>
        <Button onClick={bulkApprove} disabled={!selected.size || bulk.isPending}>
          Approve All Selected
        </Button>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>Queue</CardTitle>
          <CardDescription>Official and practice attempts awaiting approval</CardDescription>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <p className="text-muted-foreground py-8 text-center">Loading…</p>
          ) : (
            <div className="rounded-md border overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-12">
                      <Checkbox
                        checked={rows.length > 0 && selected.size === rows.length}
                        onCheckedChange={(c) => toggleAll(!!c)}
                      />
                    </TableHead>
                    <TableHead>Student</TableHead>
                    <TableHead>Exam</TableHead>
                    <TableHead>Type</TableHead>
                    <TableHead>Submitted</TableHead>
                    <TableHead>Score</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead className="text-right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {rows.map((r) => (
                    <TableRow key={r.id}>
                      <TableCell>
                        <Checkbox
                          checked={selected.has(r.attempt_id)}
                          onCheckedChange={() => toggle(r.attempt_id)}
                        />
                      </TableCell>
                      <TableCell className="font-medium">{r.student_name}</TableCell>
                      <TableCell>{r.exam_title}</TableCell>
                      <TableCell className="capitalize">{r.exam_type}</TableCell>
                      <TableCell className="whitespace-nowrap text-sm text-muted-foreground">
                        {new Date(r.submitted_at).toLocaleString()}
                      </TableCell>
                      <TableCell>{r.overall_score}</TableCell>
                      <TableCell>{r.status}</TableCell>
                      <TableCell className="text-right space-x-2 whitespace-nowrap">
                        <Button size="sm" onClick={() => approveOne(r.attempt_id)} disabled={release.isPending}>
                          Approve
                        </Button>
                        <Button size="sm" variant="destructive" onClick={() => openReject(r)}>
                          Reject
                        </Button>
                        <Button size="sm" variant="outline">
                          View Details
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>

      <Dialog open={rejectOpen} onOpenChange={setRejectOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Reject release</DialogTitle>
          </DialogHeader>
          <div className="space-y-2">
            <Label htmlFor="reason">Reason</Label>
            <Textarea id="reason" value={reason} onChange={(e) => setReason(e.target.value)} rows={4} />
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setRejectOpen(false)}>
              Cancel
            </Button>
            <Button variant="destructive" onClick={submitReject} disabled={reject.isPending}>
              Confirm reject
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
