'use client';

import { Exam } from '@/types/models';
import { useTranslations, useLocale } from 'next-intl';
import { useState, useEffect, useRef } from 'react';
import { useFormSubmission } from '@/hooks/use-form-submission';
import { useRouter } from '@/i18n/navigation';
import { toast } from '@/hooks/use-toast';

import { Clock, FileText, CheckCircle, AlertCircle, Loader, Timer } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';


interface ExamData {
    id: number;
    exam_id: number;
    name: string;
    required_to_cert: number;
    nb_questions: number;
    duration: number | null;
    exam: Exam;
}

export function ExamInterface({ examData, courseName, onExamSubmitted }: { examData: any, courseName?: string, onExamSubmitted?: () => void }) {
    const t = useTranslations('programs');
    const router = useRouter();

    const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
    const [answers, setAnswers] = useState<Record<string, any>>({});
    const [isSubmitted, setIsSubmitted] = useState(false);
    const isSubmittedRef = useRef(false);

    // Handle the actual API response structure
    const exam = examData?.groupExam || examData;
    const questions = exam?.exam?.questions || [];

    const submissionId = examData?._submissionId || exam?.id || exam?.exam_id;
    
    // Set duration from API (exam_duration or duration)
    const durationInMinutes = exam?.duration || exam?.exam?.duration || examData?.duration;
    const [timeLeft, setTimeLeft] = useState<number | null>(
        (durationInMinutes && Number(durationInMinutes) > 0) ? Number(durationInMinutes) * 60 : null
    );

    useEffect(() => {
        if (timeLeft === null || isSubmitted || isSubmittedRef.current) return;

        if (timeLeft <= 0) {
            toast({
                title: t('timeUp') || (useLocale() === 'ar' ? 'انتهى الوقت' : 'Time Up'),
                description: t('examAutoSubmitting') || (useLocale() === 'ar' ? 'سيتم تقديم الاختبار تلقائياً' : 'Automating exam submission'),
                variant: "destructive"
            });
            handleSubmit();
            return;
        }

        const timer = setInterval(() => {
            setTimeLeft(prev => (prev !== null && prev > 0) ? prev - 1 : 0);
        }, 1000);

        return () => clearInterval(timer);
    }, [timeLeft, isSubmitted]);

    const formatTime = (seconds: number) => {
        const h = Math.floor(seconds / 3600);
        const m = Math.floor((seconds % 3600) / 60);
        const s = seconds % 60;
        return `${h > 0 ? h + ':' : ''}${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
    };

    if (!exam || !questions.length) {
        return (
            <div className="min-h-screen flex items-center justify-center">
                <Card className="max-w-md w-full">
                    <CardContent className="p-8 text-center">
                        <AlertCircle className="h-16 w-16 text-red-600 mx-auto mb-4" />
                        <h2 className="text-2xl font-bold mb-2">{t('examNotAvailable')}</h2>
                        <p className="text-gray-600 mb-6">{t('examNotAvailableMessage')}</p>
                        <Button 
                            onClick={() => window.location.reload()}
                            className="bg-purple-600 hover:bg-purple-700"
                        >
                            {t('go-back')}
                        </Button>
                    </CardContent>
                </Card>
            </div>
        );
    };

    const submitExamMutation = useFormSubmission({
        endPoint: `/user/exams/pass/${submissionId}`,
        method: "POST",
        onError: (error) => {
            console.error("Submission failed:", error);
            toast({
                title: t('error'),
                description: t('examSubmissionFailed'),
                variant: "destructive"
            });
        },
        onSuccess: (response) => {
            const success = response?.success || response?.status;

            if (!success) {
                toast({
                    title: t('error'),
                    description: response?.error_message || response?.error || t('examSubmissionFailed'),
                    variant: "destructive"
                });
                return;
            }

            setIsSubmitted(true);
            isSubmittedRef.current = true;
        }
    });

    const currentQuestion = questions[currentQuestionIndex];
    const progress = ((currentQuestionIndex + 1) / questions.length) * 100;

    const handleAnswerChange = (questionId: number, answer: any, multiSelect = false) => {
        if (multiSelect) {
            // Toggle the answer in the array for multiple_choice
            setAnswers(prev => {
                const current: string[] = prev[`answers_${questionId}`] || [];
                const already = current.includes(answer);
                return {
                    ...prev,
                    [`answers_${questionId}`]: already
                        ? current.filter(a => a !== answer)
                        : [...current, answer]
                };
            });
        } else {
            setAnswers(prev => ({
                ...prev,
                [`answers_${questionId}`]: [answer]
            }));
        }
    };

    const handleSubmit = () => {
        if (isSubmittedRef.current) return;

        const payload: Record<string, any> = {
            questions: questions.map(q => q.id),
        };

        Object.keys(answers).forEach(key => {
            const questionId = parseInt(key.replace('answers_', ''));
            const question = questions.find(q => q.id === questionId);
            
            // Always send the answer choice strings so the backend saves them
            payload[key] = answers[key];

            if (question && question.answer_type === 'true_false') {
                const ansStr = answers[key]?.[0] || '';
                const isTrue = ansStr.includes('صحيح') || ansStr.toLowerCase().includes('true') || ansStr.includes('نعم') || ansStr.toLowerCase().includes('yes');
                payload[`my_rate_${questionId}`] = isTrue ? 1 : 0;
            }
        });

        submitExamMutation.mutate(payload);
    };

    const isArabic = useLocale() === 'ar';

    if (isSubmitted) {
        return (
            <div className="min-h-screen flex items-center justify-center" dir={isArabic ? 'rtl' : 'ltr'}>
                <Card className="max-w-md w-full">
                    <CardContent className="p-8 text-center">
                        <CheckCircle className="h-16 w-16 text-green-600 mx-auto mb-4" />
                        <h2 className="text-2xl font-bold mb-2">
                           {isArabic ? 'تم تقديم الاختبار بنجاح' : 'Exam Submitted Successfully'}
                        </h2>
                        <p className="text-gray-600 mb-6">{t('examSubmittedMessage')}</p>
                        <Button 
                            onClick={() => {
                                const currentUrl = new URL(window.location.href);
                                currentUrl.searchParams.set('exam', submissionId.toString());
                                window.location.href = currentUrl.toString();
                            }}
                            className="w-full bg-purple-600 hover:bg-purple-700 text-white"
                        >
                            {t('viewResult')}
                        </Button>
                    </CardContent>
                </Card>
            </div>
        );
    }

    return (
        <div className="h-screen flex flex-col bg-gray-50 overflow-hidden" dir={isArabic ? 'rtl' : 'ltr'}>
            {/* Purple Header */}
            <div className="bg-gradient-to-r from-purple-600 via-purple-700 to-indigo-700  text-white px-6 py-4 flex-shrink-0 shadow-lg relative z-10">
                <div className="max-w-5xl mx-auto flex items-center justify-between">
                    <div className="flex items-center gap-4">
                        <h2 className="text-xl font-bold line-clamp-1">
                            {exam?.exam?.name || exam?.name || examData?.name}
                        </h2>
                    </div>

                    <div className="flex items-center gap-6">
                        {timeLeft !== null && (
                            <div className={`flex items-center gap-3 px-4 py-2 rounded-full font-mono text-lg font-bold shadow-sm transition-all duration-300 ${
                                timeLeft < 60 ? 'bg-red-500 text-white animate-pulse' : 'bg-white/10 text-white'
                            }`}>
                                <Timer className={`w-5 h-5 ${timeLeft < 60 ? 'animate-bounce' : ''}`} />
                                <span className="tabular-nums">{formatTime(timeLeft)}</span>
                            </div>
                        )}
                   
                        <Button
                                onClick={() => window.location.reload()}
                                variant="ghost"
                                className="bg-white/10 hover:bg-white text-white hover:text-purple-700 px-4 rounded-lg transition-all"
                            >
                                {t('go-back')}
                                <svg className={`w-4 h-4 ${isArabic ? 'mr-2 rotate-180' : 'ml-2'}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                                </svg>
                            </Button>
                    </div>
                </div>
            </div>

            <div className="flex-1 overflow-y-auto">
                <div className="max-w-4xl mx-auto p-6 pb-20">
                    {/* Question Card */}
                    <div className="bg-white rounded-lg shadow-sm p-8">
                    {/* Question Numbers Navigation */}
                    <div className="mb-6">
                        <h3 className="text-sm font-semibold text-gray-700 mb-4">
                            {t('questionOutOf', { current: currentQuestionIndex + 1, total: questions.length })}
                        </h3>
                        <div className="flex gap-2 flex-wrap">
                            {questions.map((_, index) => (
                                <button
                                    key={index}
                                    onClick={() => setCurrentQuestionIndex(index)}
                                    className={`size-10 rounded-full font-semibold transition-all ${
                                        index === currentQuestionIndex
                                            ? 'bg-gray-800 text-white'
                                            : answers[`answers_${questions[index].id}`]
                                            ? 'bg-purple-100 text-purple-700 border-2 border-purple-300'
                                            : 'bg-white text-gray-600 border-2 border-gray-300 hover:border-gray-400'
                                    }`}
                                >
                                    {index + 1}
                                </button>
                            ))}
                        </div>
                    </div>

                    {/* Question */}
                    <div className="mb-6">
                        <p className={`text-gray-700 text-base leading-relaxed ${isArabic ? 'text-right' : 'text-left'}`}>
                            {currentQuestion.question}
                        </p>
                    </div>

                    {/* Answers */}
                    <div className="space-y-3 mb-8">

                        {/* ── one_choice → single select (RadioGroup) ── */}
                        {currentQuestion.answer_type === 'one_choice' && (
                            <RadioGroup
                                value={answers[`answers_${currentQuestion.id}`]?.[0] || ''}
                                onValueChange={(value) => handleAnswerChange(currentQuestion.id, value)}
                                className="space-y-3"
                            >
                                {currentQuestion.answers.map((answer, index) => (
                                    <div
                                        key={index}
                                        onClick={() => handleAnswerChange(currentQuestion.id, answer)}
                                        className={`flex items-center gap-3 p-4 rounded-lg border-2 transition-all cursor-pointer select-none ${
                                            isArabic ? 'flex-row-reverse' : 'flex-row'
                                        } ${
                                            answers[`answers_${currentQuestion.id}`]?.[0] === answer
                                                ? 'border-purple-600 bg-purple-50'
                                                : 'border-gray-200 hover:border-gray-300 hover:bg-gray-50'
                                        }`}
                                    >
                                        <RadioGroupItem value={answer} className="text-purple-600 pointer-events-none shrink-0" />
                                        <Label className={`cursor-pointer text-base  pointer-events-none ${isArabic ? 'text-right' : 'text-left'}`}>
                                            {answer}
                                        </Label>
                                    </div>
                                ))}
                            </RadioGroup>
                        )}

                        {/* ── multiple_choice → multi-select (Checkboxes) ── */}
                        {currentQuestion.answer_type === 'multiple_choice' && (
                            <div className="space-y-3">
                                {currentQuestion.answers.map((answer, index) => {
                                    const selected: string[] = answers[`answers_${currentQuestion.id}`] || [];
                                    const isChecked = selected.includes(answer);
                                    return (
                                        <div
                                            key={index}
                                            onClick={() => handleAnswerChange(currentQuestion.id, answer, true)}
                                            className={`flex items-center gap-3 p-4 rounded-lg border-2 transition-all cursor-pointer select-none ${
                                                isArabic ? 'flex-row-reverse' : 'flex-row'
                                            } ${
                                                isChecked
                                                    ? 'border-purple-600 bg-purple-50'
                                                    : 'border-gray-200 hover:border-gray-300 hover:bg-gray-50'
                                            }`}
                                        >
                                            <Checkbox
                                                checked={isChecked}
                                                className="pointer-events-none shrink-0 data-[state=checked]:bg-purple-600 data-[state=checked]:border-purple-600"
                                            />
                                            <Label className={`cursor-pointer text-base flex-1 pointer-events-none ${isArabic ? 'text-right' : 'text-left'}`}>
                                                {answer}
                                            </Label>
                                        </div>
                                    );
                                })}
                                <p className={`text-xs text-gray-400 mt-1 ${isArabic ? 'text-right' : 'text-left'}`}>
                                    {isArabic ? 'يمكنك اختيار أكثر من إجابة' : 'You can select more than one answer'}
                                </p>
                            </div>
                        )}

                        {/* ── true_false → single select (RadioGroup) ── */}
                        {currentQuestion.answer_type === 'true_false' && (
                            <RadioGroup
                                value={answers[`answers_${currentQuestion.id}`]?.[0]?.toString() || ''}
                                onValueChange={(value) => handleAnswerChange(currentQuestion.id, value)}
                                className="space-y-3"
                            >
                                {(currentQuestion.answers || (isArabic ? ['صحيح', 'خطأ'] : ['True', 'False'])).map((answer, index) => (
                                    <div
                                        key={index}
                                        onClick={() => handleAnswerChange(currentQuestion.id, answer)}
                                        className={`flex items-center gap-3 p-4 rounded-lg border-2 transition-all cursor-pointer select-none ${
                                            isArabic ? 'flex-row-reverse' : 'flex-row'
                                        } ${
                                            answers[`answers_${currentQuestion.id}`]?.[0] === answer
                                                ? 'border-purple-600 bg-purple-50'
                                                : 'border-gray-200 hover:border-gray-300 hover:bg-gray-50'
                                        }`}
                                    >
                                        <RadioGroupItem value={answer} className="text-purple-600 pointer-events-none shrink-0" />
                                        <Label className={`cursor-pointer text-base flex-1 pointer-events-none ${isArabic ? 'text-right' : 'text-left'}`}>
                                            {answer}
                                        </Label>
                                    </div>
                                ))}
                            </RadioGroup>
                        )}
                    </div>

                    {/* Action Buttons */}
                    <div className="flex gap-3">
                        {currentQuestionIndex === questions.length - 1 ? (
                            <Button 
                                onClick={handleSubmit} 
                                disabled={submitExamMutation.isPending}
                                className="bg-purple-600 hover:bg-purple-700 text-white px-8 py-2"
                            >
                                {submitExamMutation.isPending ? (
                                    <>
                                        <Loader className='animate-spin' />
                                        {t('submitting')}
                                    </>
                                ) : (
                                    t('submitExam')
                                )}
                            </Button>
                        ) : (
                            <>
                                <Button
                                    onClick={() => {
                                        if (currentQuestionIndex < questions.length - 1) {
                                            setCurrentQuestionIndex(prev => prev + 1);
                                        }
                                    }}
                                    disabled={
                                        !answers[`answers_${currentQuestion.id}`] ||
                                        (Array.isArray(answers[`answers_${currentQuestion.id}`]) && answers[`answers_${currentQuestion.id}`].length === 0)
                                    }
                                    className="bg-purple-600 hover:bg-purple-700 text-white px-8 py-2"
                                >
                                    {t('confirm')}
                                </Button>
                                <Button
                                    onClick={() => {
                                        if (currentQuestionIndex < questions.length - 1) {
                                            setCurrentQuestionIndex(prev => prev + 1);
                                        }
                                    }}
                                    variant="outline"
                                    className="bg-gray-800  text-white border-0 px-8 py-2"
                                >
                                    {t('skipQuestion')}
                                </Button>
                            </>
                        )}
                    </div>
                </div>
                </div>
            </div>
        </div>
    );
}
