import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Clock, Calendar, PlayCircle, AlertCircle } from "lucide-react";
import { assignmentsService } from "@/services/assignments.service";
import type { StudentExamAssignment } from "@/types";

export default function ExamPopup() {
  const navigate = useNavigate();
  const [open, setOpen] = useState(false);
  const [dismissed, setDismissed] = useState<Set<number>>(new Set());

  const { data } = useQuery({
    queryKey: ["student-my-exams"],
    queryFn: () => assignmentsService.getStudentExams(),
    refetchInterval: 30000,
  });

  const exams = (data?.items ?? []) as StudentExamAssignment[];
  const pendingExams = exams.filter((e) => !dismissed.has(e.id));

  useEffect(() => {
    if (pendingExams.length > 0 && !open) {
      setOpen(true);
    }
  }, [pendingExams.length]);

  if (pendingExams.length === 0) return null;

  const formatDate = (iso: string | null) => {
    if (!iso) return "—";
    const d = new Date(iso);
    return d.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }) +
      " " + d.toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit" });
  };

  const handleStart = (exam: StudentExamAssignment) => {
    setOpen(false);
    navigate(`/student/exam/${exam.exam_id}/session`);
  };

  const handleDismiss = (id: number) => {
    setDismissed((prev) => new Set([...prev, id]));
    const remaining = pendingExams.filter((e) => e.id !== id);
    if (remaining.length === 0) setOpen(false);
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogContent className="max-w-lg">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <AlertCircle className="h-5 w-5 text-primary" />
            Upcoming Exams ({pendingExams.length})
          </DialogTitle>
        </DialogHeader>
        <div className="space-y-3 max-h-[60vh] overflow-y-auto pr-1">
          {pendingExams.map((exam) => (
            <div key={exam.id} className="border rounded-lg p-4 space-y-3">
              <div className="flex items-center justify-between">
                <h3 className="font-semibold text-sm">{exam.exam_title || exam.schedule_name}</h3>
                <Badge
                  variant={exam.schedule_state === "active" ? "default" : "secondary"}
                  className="capitalize text-xs"
                >
                  {exam.schedule_state === "active" ? "Active Now" : exam.schedule_state}
                </Badge>
              </div>

              {exam.schedule_name && exam.exam_title && (
                <p className="text-xs text-muted-foreground">{exam.schedule_name}</p>
              )}

              <div className="flex items-center gap-4 text-xs text-muted-foreground">
                <span className="flex items-center gap-1">
                  <Calendar className="h-3 w-3" />
                  From: {formatDate(exam.start_date)}
                </span>
                <span className="flex items-center gap-1">
                  <Clock className="h-3 w-3" />
                  To: {formatDate(exam.end_date)}
                </span>
              </div>

              <div className="flex items-center gap-2">
                <Button
                  size="sm"
                  disabled={!exam.can_start}
                  onClick={() => handleStart(exam)}
                  className="gap-1.5"
                >
                  <PlayCircle className="h-3.5 w-3.5" />
                  {exam.can_start ? "Start Exam" : "Not Available Yet"}
                </Button>
                <Button
                  size="sm"
                  variant="ghost"
                  onClick={() => handleDismiss(exam.id)}
                >
                  Dismiss
                </Button>
                {!exam.can_start && (
                  <span className="text-[11px] text-muted-foreground italic ml-auto">
                    {exam.schedule_state === "planned"
                      ? "Exam will be available once it becomes active"
                      : "Exam is not currently active"}
                  </span>
                )}
              </div>
            </div>
          ))}
        </div>
      </DialogContent>
    </Dialog>
  );
}
