import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
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 { t, i18n } = useTranslation();
  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;

  // Localize dates with the active language so Arabic users see ar-EG
  // month names instead of "Apr 19, 2026". The locale is taken from i18n.
  const dateLocale = i18n.language?.startsWith("ar") ? "ar-EG" : "en-US";
  const formatDate = (iso: string | null) => {
    if (!iso) return "—";
    const d = new Date(iso);
    return d.toLocaleDateString(dateLocale, { month: "short", day: "numeric", year: "numeric" }) +
      " " + d.toLocaleTimeString(dateLocale, { 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" />
            {t("examPopup.title", { n: pendingExams.length })}
          </DialogTitle>
        </DialogHeader>
        <div className="space-y-3 max-h-[60vh] overflow-y-auto pe-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" ? t("examPopup.activeNow") : 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" />
                  {t("examPopup.from")} {formatDate(exam.start_date)}
                </span>
                <span className="flex items-center gap-1">
                  <Clock className="h-3 w-3" />
                  {t("examPopup.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 ? t("examPopup.startExam") : t("examPopup.notAvailableYet")}
                </Button>
                <Button
                  size="sm"
                  variant="ghost"
                  onClick={() => handleDismiss(exam.id)}
                >
                  {t("common.dismiss")}
                </Button>
                {!exam.can_start && (
                  <span className="text-[11px] text-muted-foreground italic ms-auto">
                    {exam.schedule_state === "planned"
                      ? t("examPopup.willBeAvailable")
                      : t("examPopup.notActive")}
                  </span>
                )}
              </div>
            </div>
          ))}
        </div>
      </DialogContent>
    </Dialog>
  );
}
