'use client';

import React, { useState, useEffect } from 'react';
import { useExam } from '@/contexts/ExamContext';
import { 
  Clock, 
  FileText, 
  AlertCircle, 
  CheckCircle, 
  Users, 
  Calendar,
  Timer,
  BookOpen,
  Target,
  Info,
  X,
  Play
} from 'lucide-react';
import { cn } from '@/utils/cn';

interface QuizIntroductionModalProps {
  isOpen: boolean;
  onClose: () => void;
  onStart: () => void;
  autoStartCountdown?: number; // in seconds
  showRules?: boolean;
  showStats?: boolean;
}

export default function QuizIntroductionModal({
  isOpen,
  onClose,
  onStart,
  autoStartCountdown = 0,
  showRules = true,
  showStats = true
}: QuizIntroductionModalProps) {
  const { state } = useExam();
  const [countdown, setCountdown] = useState(autoStartCountdown);
  const [isCountingDown, setIsCountingDown] = useState(false);
  const [agreedToRules, setAgreedToRules] = useState(false);

  useEffect(() => {
    if (autoStartCountdown > 0 && isOpen) {
      setCountdown(autoStartCountdown);
      setIsCountingDown(true);
    }
  }, [autoStartCountdown, isOpen]);

  useEffect(() => {
    let interval: NodeJS.Timeout;
    
    if (isCountingDown && countdown > 0) {
      interval = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) {
            setIsCountingDown(false);
            if (agreedToRules) {
              onStart();
            }
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    }

    return () => {
      if (interval) {
        clearInterval(interval);
      }
    };
  }, [isCountingDown, countdown, agreedToRules, onStart]);

  const handleStartQuiz = () => {
    if (!agreedToRules && showRules) {
      return;
    }
    onStart();
  };

  const handleStartCountdown = () => {
    if (!agreedToRules && showRules) {
      return;
    }
    setCountdown(5);
    setIsCountingDown(true);
  };

  if (!isOpen || !state.examData) {
    return null;
  }

  const examData = state.examData;
  const totalQuestions = examData.questions.length;
  const timeLimit = examData.duration;
    const formattedTimeLimit = `${Math.floor(timeLimit / 60)} menit ${timeLimit % 60} detik`;

  const quizRules = [
    'Pastikan koneksi internet Anda stabil selama mengerjakan quiz',
    'Jawaban akan tersimpan otomatis setiap kali Anda memilih atau mengubah jawaban',
    'Anda dapat menandai soal untuk ditinjau kembali menggunakan tombol flag',
    'Gunakan fitur bookmark untuk menyimpan soal penting',
    'Quiz akan berakhir otomatis ketika waktu habis',
    'Pastikan tidak menutup browser atau tab selama mengerjakan quiz',
    'Jika terjadi gangguan teknis, hubungi pengawas segera'
  ];

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-xl shadow-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <div className="flex items-center space-x-3">
            <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
              <BookOpen className="w-5 h-5 text-blue-600" />
            </div>
            <div>
              <h2 className="text-xl font-bold text-gray-900">
                {examData.title}
              </h2>
              <p className="text-sm text-gray-500">
                Persiapan Quiz
              </p>
            </div>
          </div>
          
          {!isCountingDown && (
            <button
              onClick={onClose}
              className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
            >
              <X className="w-5 h-5 text-gray-500" />
            </button>
          )}
        </div>

        {/* Countdown Display */}
        {isCountingDown && (
          <div className="p-6 bg-gradient-to-r from-blue-50 to-indigo-50 border-b border-gray-200">
            <div className="text-center">
              <div className="w-20 h-20 mx-auto bg-white rounded-full flex items-center justify-center shadow-lg mb-4">
                <span className="text-3xl font-bold text-blue-600">
                  {countdown}
                </span>
              </div>
              <h3 className="text-lg font-semibold text-gray-900 mb-2">
                Quiz akan dimulai dalam...
              </h3>
              <p className="text-sm text-gray-600">
                Pastikan Anda sudah siap untuk memulai quiz
              </p>
            </div>
          </div>
        )}

        {/* Quiz Information */}
        <div className="p-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
            {/* Basic Info */}
            <div className="space-y-4">
              <div className="flex items-center space-x-3">
                <FileText className="w-5 h-5 text-gray-500" />
                <div>
                  <div className="text-sm font-medium text-gray-900">
                    Total Soal
                  </div>
                  <div className="text-lg font-bold text-blue-600">
                    {totalQuestions} soal
                  </div>
                </div>
              </div>

              <div className="flex items-center space-x-3">
                <Clock className="w-5 h-5 text-gray-500" />
                <div>
                  <div className="text-sm font-medium text-gray-900">
                    Waktu Pengerjaan
                  </div>
                  <div className="text-lg font-bold text-orange-600">
                    {formattedTimeLimit}
                  </div>
                </div>
              </div>

              <div className="flex items-center space-x-3">
                <Target className="w-5 h-5 text-gray-500" />
                <div>
                  <div className="text-sm font-medium text-gray-900">
                    Passing Grade
                  </div>
                  <div className="text-lg font-bold text-green-600">
                    {examData.passingGrade || 70}%
                  </div>
                </div>
              </div>
            </div>

            {/* Additional Info */}
            <div className="space-y-4">
              <div className="flex items-center space-x-3">
                <Calendar className="w-5 h-5 text-gray-500" />
                <div>
                  <div className="text-sm font-medium text-gray-900">
                    Tanggal
                  </div>
                  <div className="text-sm text-gray-600">
                    {new Date().toLocaleDateString('id-ID', {
                      weekday: 'long',
                      year: 'numeric',
                      month: 'long',
                      day: 'numeric'
                    })}
                  </div>
                </div>
              </div>

              <div className="flex items-center space-x-3">
                <Timer className="w-5 h-5 text-gray-500" />
                <div>
                  <div className="text-sm font-medium text-gray-900">
                    Waktu Mulai
                  </div>
                  <div className="text-sm text-gray-600">
                    {new Date().toLocaleTimeString('id-ID', {
                      hour: '2-digit',
                      minute: '2-digit'
                    })} WIB
                  </div>
                </div>
              </div>

              {showStats && (
                <div className="flex items-center space-x-3">
                  <Users className="w-5 h-5 text-gray-500" />
                  <div>
                    <div className="text-sm font-medium text-gray-900">
                      Peserta Aktif
                    </div>
                    <div className="text-sm text-gray-600">
                      1 peserta
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Quiz Description */}
          {examData.description && (
            <div className="mb-6 p-4 bg-gray-50 rounded-lg">
              <h4 className="text-sm font-medium text-gray-900 mb-2 flex items-center">
                <Info className="w-4 h-4 mr-2" />
                Deskripsi Quiz
              </h4>
              <p className="text-sm text-gray-600">
                {examData.description}
              </p>
            </div>
          )}

          {/* Rules */}
          {showRules && (
            <div className="mb-6">
              <h4 className="text-sm font-medium text-gray-900 mb-3 flex items-center">
                <AlertCircle className="w-4 h-4 mr-2 text-orange-500" />
                Aturan dan Ketentuan
              </h4>
              <div className="space-y-2">
                {quizRules.map((rule, index) => (
                  <div key={index} className="flex items-start space-x-2">
                    <div className="w-1.5 h-1.5 bg-gray-400 rounded-full mt-2 flex-shrink-0"></div>
                    <p className="text-sm text-gray-600">{rule}</p>
                  </div>
                ))}
              </div>

              {/* Agreement Checkbox */}
              <div className="mt-4 p-3 bg-blue-50 rounded-lg">
                <label className="flex items-start space-x-3 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={agreedToRules}
                    onChange={(e) => setAgreedToRules(e.target.checked)}
                    className="mt-1 w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                  />
                  <div className="text-sm">
                    <span className="font-medium text-gray-900">
                      Saya telah membaca dan menyetujui
                    </span>
                    <span className="text-gray-600">
                      {' '}semua aturan dan ketentuan yang berlaku untuk quiz ini.
                    </span>
                  </div>
                </label>
              </div>
            </div>
          )}

          {/* Action Buttons */}
          <div className="flex items-center justify-between pt-4 border-t border-gray-200">
            <div className="text-sm text-gray-500">
              {showRules && !agreedToRules && (
                <span className="flex items-center text-orange-600">
                  <AlertCircle className="w-4 h-4 mr-1" />
                  Harap setujui aturan terlebih dahulu
                </span>
              )}
            </div>

            <div className="flex items-center space-x-3">
              {!isCountingDown && (
                <button
                  onClick={onClose}
                  className="px-4 py-2 text-sm font-medium text-gray-600 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors"
                >
                  Batal
                </button>
              )}

              {!isCountingDown ? (
                <div className="flex space-x-2">
                  <button
                    onClick={handleStartCountdown}
                    disabled={showRules && !agreedToRules}
                    className={cn(
                      'px-4 py-2 text-sm font-medium rounded-lg transition-colors',
                      showRules && !agreedToRules
                        ? 'bg-gray-200 text-gray-400 cursor-not-allowed'
                        : 'bg-orange-500 text-white hover:bg-orange-600'
                    )}
                  >
                    Mulai dengan Countdown
                  </button>
                  
                  <button
                    onClick={handleStartQuiz}
                    disabled={showRules && !agreedToRules}
                    className={cn(
                      'px-6 py-2 text-sm font-medium rounded-lg transition-colors flex items-center space-x-2',
                      showRules && !agreedToRules
                        ? 'bg-gray-200 text-gray-400 cursor-not-allowed'
                        : 'bg-blue-600 text-white hover:bg-blue-700'
                    )}
                  >
                    <Play className="w-4 h-4" />
                    <span>Mulai Quiz Sekarang</span>
                  </button>
                </div>
              ) : (
                <button
                  onClick={() => setIsCountingDown(false)}
                  className="px-4 py-2 text-sm font-medium text-red-600 bg-red-50 rounded-lg hover:bg-red-100 transition-colors"
                >
                  Batalkan Countdown
                </button>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}