import React, { useState, useEffect } from "react";
import { Clock, ArrowRight } from "lucide-react";

interface Question {
  id: number;
  text: string;
  options: string[];
}

interface ActiveExamProps {
  title: string;
  questions: Question[];
  totalTimeSeconds: number;
  onSubmit: (answers: Record<number, number>, timeSpent: number) => void;
}

export function ActiveExam({ title, questions, totalTimeSeconds, onSubmit }: ActiveExamProps) {
  const [currentIdx, setCurrentIdx] = useState(0);
  const [answers, setAnswers] = useState<Record<number, number>>({});
  const [timeLeft, setTimeLeft] = useState(totalTimeSeconds);

  useEffect(() => {
    const timer = setInterval(() => {
      setTimeLeft((prev) => {
        if (prev <= 1) {
          clearInterval(timer);
          onSubmit(answers, totalTimeSeconds);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
    return () => clearInterval(timer);
  }, [answers, totalTimeSeconds, onSubmit]);

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

  const handleSelect = (optIndex: number) => {
    setAnswers({ ...answers, [currentIdx]: optIndex });
  };

  const handleNext = () => {
    if (currentIdx < questions.length - 1) {
      setCurrentIdx(currentIdx + 1);
    }
  };

  const handleSkip = () => {
    handleNext();
  };

  const handleSubmit = () => {
    onSubmit(answers, totalTimeSeconds - timeLeft);
  };

  const progressPercent = ((Object.keys(answers).length) / questions.length) * 100;

  return (
    <div className="min-h-screen bg-[#f8f9fa] flex">
      {/* Sidebar */}
      <div className="w-[300px] bg-[#f8f9fa] border-r border-gray-200 flex flex-col p-8">
        <div className="font-bold text-xl mb-12 tracking-tight flex items-center gap-2">
          <span className="bg-black text-white px-2 py-1 rounded">JV</span> JOBVUMI
        </div>

        {/* Progress Bar */}
        <div className="w-full bg-gray-200 h-2 rounded-full mb-8 overflow-hidden">
          <div className="bg-[#fc6123] h-full transition-all duration-300" style={{ width: `${progressPercent}%` }}></div>
        </div>

        <h3 className="text-gray-900 font-medium mb-4">Question Map</h3>
        
        <div className="grid grid-cols-5 gap-3 mb-auto">
          {questions.map((_, idx) => {
            const isCurrent = idx === currentIdx;
            const isAnswered = answers[idx] !== undefined;
            return (
              <button
                key={idx}
                onClick={() => setCurrentIdx(idx)}
                className={`w-10 h-10 flex items-center justify-center rounded text-sm font-semibold transition-colors ${
                  isCurrent
                    ? "bg-[#fff0eb] border border-[#fc6123] text-[#fc6123]"
                    : isAnswered
                    ? "bg-gray-800 text-white border border-gray-800"
                    : "bg-white border border-gray-200 text-gray-500 hover:bg-gray-50"
                }`}
              >
                {String(idx + 1).padStart(2, '0')}
              </button>
            );
          })}
        </div>

        <button 
          onClick={handleSubmit}
          className="w-full bg-black hover:bg-gray-900 text-white py-3.5 rounded-lg font-semibold mt-8 transition-colors"
        >
          Submit Test
        </button>
      </div>

      {/* Main Content */}
      <div className="flex-1 flex flex-col p-10">
        <div className="flex justify-between items-start mb-8">
          <div>
            <h1 className="text-[28px] font-bold text-gray-900 mb-1">{title}</h1>
            <p className="text-gray-500 text-sm font-medium">Question {String(currentIdx + 1).padStart(2, '0')} Of {questions.length}</p>
          </div>
          <div className="flex flex-col items-end">
            <div className="flex items-center gap-2 text-[#fc6123] font-semibold text-lg">
              <Clock className="w-5 h-5" /> 00:{formatTime(timeLeft)}
            </div>
            <span className="text-xs text-[#fc6123] font-medium mt-0.5">Time Left</span>
          </div>
        </div>

        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-10 max-w-3xl flex-1 flex flex-col">
          <h2 className="text-[17px] font-bold text-gray-900 mb-8 leading-relaxed">
            {questions[currentIdx].text}
          </h2>

          <div className="flex flex-col gap-4 mb-auto">
            {questions[currentIdx].options.map((opt, i) => {
              const letters = ['A', 'B', 'C', 'D'];
              const isSelected = answers[currentIdx] === i;
              return (
                <label 
                  key={i} 
                  className={`flex items-center gap-4 p-4 rounded-xl border-2 cursor-pointer transition-all ${
                    isSelected ? "border-[#fc6123] bg-[#fffaf8]" : "border-gray-100 hover:border-gray-200 hover:bg-gray-50"
                  }`}
                >
                  <div className="relative flex items-center justify-center">
                    <input 
                      type="radio" 
                      name="answer" 
                      checked={isSelected}
                      onChange={() => handleSelect(i)}
                      className="w-5 h-5 border-2 border-gray-300 rounded-full appearance-none checked:border-[#fc6123] transition-colors cursor-pointer"
                    />
                    {isSelected && <div className="w-2.5 h-2.5 bg-[#fc6123] rounded-full absolute"></div>}
                  </div>
                  <span className="font-semibold text-gray-500">{letters[i]}.</span>
                  <span className="text-gray-800 font-medium">{opt}</span>
                </label>
              );
            })}
          </div>
        </div>

        <div className="max-w-3xl flex justify-end items-center gap-6 mt-8">
          <button 
            onClick={handleSkip}
            className="text-sm font-bold text-gray-900 hover:text-gray-600 transition-colors"
          >
            Skip
          </button>
          <button 
            onClick={handleNext}
            className="bg-[#fc6123] hover:bg-[#e5561e] text-white px-8 py-3 rounded-lg text-sm font-semibold flex items-center gap-2 shadow-sm transition-all"
          >
            {currentIdx === questions.length - 1 ? "Finish" : "Next"} <ArrowRight className="w-4 h-4" />
          </button>
        </div>
      </div>
    </div>
  );
}
