"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import {
  ClockIcon,
  BookOpenIcon,
  AlertTriangleIcon,
  ArrowLeftIcon,
  ArrowRightIcon,
  Loader2Icon,
} from "lucide-react";

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import ExamStepIndicator from "@/components/exam/exam-step-indicator";

import { type Exam, submitExamAttempt } from "@/lib/api/exams";
import { type User } from "@/lib/api/labs";
import { useLocaleFunction } from "@/hooks/use-localed";
import { renderRemarkInline } from "@/lib/remark-inline";

export default function WaitingContent({
  examId,
  exam,
  user,
}: {
  examId: number;
  exam: Exam;
  user: User;
}) {
  const t = useLocaleFunction();
  const router = useRouter();
  const [error, setError] = useState<string | null>(null);
  const [showErrorDialog, setShowErrorDialog] = useState(false);
  const [starting, setStarting] = useState(false);

  const variantId = exam.variant_id;

  const handleStartExam = async () => {
    if (starting) return;
    setStarting(true);

    try {
      await submitExamAttempt(variantId);
      router.push(`/exam/${examId}/question/1`);
    } catch (error) {
      setStarting(false);
      console.error("Failed to start exam:", error);
      if (error instanceof Error) {
        setError(error.message);
        setShowErrorDialog(true);
      }
    }
  };

  const handleReturn = () => {
    setShowErrorDialog(false);
    router.push(`/exam/${examId}`);
  };

  return (
    <>
      <div className="animate-fade-in">
        <ExamStepIndicator currentStep={2} />

        {/* Waiting card */}
        <Card className="py-2">
          <CardHeader>
            <CardTitle className="text-xl">
              <h1 className="text-xl font-semibold text-foreground mb-2">
                {t(
                  "exam.waiting_room",
                  `${user.first_name || ""} ${user.last_name || ""}`
                )}
              </h1>
              <p className="text-muted-foreground text-base">
                {renderRemarkInline(t("exam.waiting_room_intro", exam.title), true)}
              </p>
            </CardTitle>
          </CardHeader>
          <CardContent>
            {/* Quick info */}
            <div className="grid grid-cols-2 gap-4 mb-6">
              <div className="flex items-center gap-3 p-3 bg-muted">
                <ClockIcon className="w-5 h-5 text-muted-foreground" />
                <div>
                  <p className="text-sm font-semibold text-foreground">
                    {t("exam.waiting_room_duration", exam.duration)}
                  </p>
                  <p className="text-xs text-muted-foreground">
                    {t("exam.waiting_room_time_limit")}
                  </p>
                </div>
              </div>
              <div className="flex items-center gap-3 p-3 bg-muted">
                <BookOpenIcon className="w-5 h-5 text-muted-foreground" />
                <div>
                  <p className="text-sm font-semibold text-foreground">
                    {t("exam.waiting_room_questions", exam.question_count)}
                  </p>
                  <p className="text-xs text-muted-foreground">
                    {t("exam.waiting_room_total_questions")}
                  </p>
                </div>
              </div>
            </div>

            {/* Rules */}
            <h2 className="font-medium text-foreground mb-3">
              {t("exam.waiting_room_rules")}
            </h2>
            <ul className="mb-6 flex flex-col gap-2">
              <li className="flex items-start gap-3">
                <span className="w-5 h-5 rounded-full bg-muted text-muted-foreground flex items-center justify-center text-xs font-medium flex-shrink-0 mt-0.5">
                  1
                </span>
                <span className="text-sm text-muted-foreground">
                  {renderRemarkInline(t("exam.waiting_room_rule.1", exam.duration), true)}
                </span>
              </li>
              <li className="flex items-start gap-3">
                <span className="w-5 h-5 rounded-full bg-muted text-muted-foreground flex items-center justify-center text-xs font-medium flex-shrink-0 mt-0.5">
                  2
                </span>
                <span className="text-sm text-muted-foreground">
                  {renderRemarkInline(t("exam.waiting_room_rule.2"), true)}
                </span>
              </li>
              <li className="flex items-start gap-3">
                <span className="w-5 h-5 rounded-full bg-muted text-muted-foreground flex items-center justify-center text-xs font-medium flex-shrink-0 mt-0.5">
                  3
                </span>
                <span className="text-sm text-muted-foreground">
                  {renderRemarkInline(t("exam.waiting_room_rule.3"), true)}
                </span>
              </li>
              <li className="flex items-start gap-3">
                <span className="w-5 h-5 rounded-full bg-muted text-muted-foreground flex items-center justify-center text-xs font-medium flex-shrink-0 mt-0.5">
                  4
                </span>
                <span className="text-sm text-muted-foreground">
                  {renderRemarkInline(t("exam.waiting_room_rule.4"), true)}
                </span>
              </li>
              <li className="flex items-start gap-3">
                <span className="w-5 h-5 rounded-full bg-muted text-muted-foreground flex items-center justify-center text-xs font-medium flex-shrink-0 mt-0.5">
                  5
                </span>
                <span className="text-sm text-muted-foreground">
                  {renderRemarkInline(t("exam.waiting_room_rule.5", exam.pass_score_percentage, `${exam.pass_score}/${exam.total_score}`), true)}
                </span>
              </li>
            </ul>

            {/* Warning */}
            <Alert
              variant="warn"
              className="bg-amber-600/10 border border-amber-600/20"
            >
              <AlertTriangleIcon size={20} className="-mt-1" />
              <AlertTitle className="text-foreground">
                {t("exam.waiting_room_warning.alert.title")}
              </AlertTitle>
              <AlertDescription className="text-muted-foreground">
                {renderRemarkInline(t("exam.waiting_room_warning.alert.description"), true)}
              </AlertDescription>
            </Alert>

            <h2 className="font-medium text-foreground mb-2 mt-6">
              {t("exam.waiting_room_code_of_conduct_agreement")}
            </h2>
            <ul className="mb-3 list-disc pl-4 text-sm text-muted-foreground flex flex-col gap-2">
              <li>{t("exam.waiting_room_code_of_conduct_agreement_rule.1")}</li>
              <li>{t("exam.waiting_room_code_of_conduct_agreement_rule.2")}</li>
              <li>{t("exam.waiting_room_code_of_conduct_agreement_rule.3")}</li>
            </ul>
            <p className="text-foreground">
              {t("exam.waiting_room_code_of_conduct_agreement_footer")}
            </p>
          </CardContent>
        </Card>

        <div className="flex justify-between gap-4 pt-8">
          <Button variant="outline" size="lg" asChild className="px-4">
            <Link href={`/exam/${examId}/confirm-info`}>
              <ArrowLeftIcon className="w-4 h-4 mr-2" />
              {t("exam.back")}
            </Link>
          </Button>
          <Button
            className="cursor-pointer"
            onClick={handleStartExam}
            disabled={starting}
          >
            {t("exam.start_exam")}
            {starting ?
              (<Loader2Icon className="w-4 h-4 ml-2 animate-spin" />)
              : (<ArrowRightIcon className="w-4 h-4 ml-2" />)}
          </Button>
        </div>
      </div>

      <Dialog open={showErrorDialog} onOpenChange={setShowErrorDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{t("exam.error_unable_to_start_exam")}</DialogTitle>
            <DialogDescription>
              {error || t("exam.error_description")}
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              onClick={handleReturn}
              className="cursor-pointer"
            >
              {t("exam.return_to_overview")}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
