import React, { useState, useRef, useEffect } from 'react';
import { Play, Pause, RotateCcw, Volume2, VolumeX, Maximize, Clock, AlertCircle, CheckCircle } from 'lucide-react';
import { cn } from '../../utils/cn';

interface VideoScenarioProps {
  videoSrc: string;
  title: string;
  description: string;
  scenarios: VideoScenarioStep[];
  onScenarioComplete: (results: ScenarioResult[]) => void;
  className?: string;
}

interface VideoScenarioStep {
  id: string;
  timestamp: number; // detik
  title: string;
  question: string;
  options: VideoOption[];
  correctAnswer: number;
  explanation: string;
  pauseVideo?: boolean;
}

interface VideoOption {
  id: string;
  text: string;
  consequence?: string;
  isCorrect?: boolean;
}

interface ScenarioResult {
  stepId: string;
  selectedOption: number;
  isCorrect: boolean;
  timestamp: number;
  reactionTime: number;
}

const VideoScenario: React.FC<VideoScenarioProps> = ({
  videoSrc,
  title,
  description,
  scenarios,
  onScenarioComplete,
  className
}) => {
  const videoRef = useRef<HTMLVideoElement>(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const [isMuted, setIsMuted] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const [currentScenario, setCurrentScenario] = useState<VideoScenarioStep | null>(null);
  const [scenarioResults, setScenarioResults] = useState<ScenarioResult[]>([]);
  const [completedScenarios, setCompletedScenarios] = useState<Set<string>>(new Set());
  const [showQuestion, setShowQuestion] = useState(false);
  const [questionStartTime, setQuestionStartTime] = useState(0);

  // Monitor video progress
  useEffect(() => {
    const video = videoRef.current;
    if (!video) return;

    const handleTimeUpdate = () => {
      const time = video.currentTime;
      setCurrentTime(time);

      // Check for scenario triggers
      const activeScenario = scenarios.find(
        scenario => 
          Math.abs(time - scenario.timestamp) < 0.5 && 
          !completedScenarios.has(scenario.id)
      );

      if (activeScenario && !showQuestion) {
        setCurrentScenario(activeScenario);
        setShowQuestion(true);
        setQuestionStartTime(Date.now());
        
        if (activeScenario.pauseVideo) {
          video.pause();
          setIsPlaying(false);
        }
      }
    };

    const handleLoadedMetadata = () => {
      setDuration(video.duration);
    };

    video.addEventListener('timeupdate', handleTimeUpdate);
    video.addEventListener('loadedmetadata', handleLoadedMetadata);

    return () => {
      video.removeEventListener('timeupdate', handleTimeUpdate);
      video.removeEventListener('loadedmetadata', handleLoadedMetadata);
    };
  }, [scenarios, completedScenarios, showQuestion]);

  const togglePlay = () => {
    const video = videoRef.current;
    if (!video) return;

    if (isPlaying) {
      video.pause();
    } else {
      video.play();
    }
    setIsPlaying(!isPlaying);
  };

  const toggleMute = () => {
    const video = videoRef.current;
    if (!video) return;

    video.muted = !isMuted;
    setIsMuted(!isMuted);
  };

  const restart = () => {
    const video = videoRef.current;
    if (!video) return;

    video.currentTime = 0;
    setCurrentTime(0);
    setScenarioResults([]);
    setCompletedScenarios(new Set());
    setCurrentScenario(null);
    setShowQuestion(false);
  };

  const handleAnswerSelect = (optionIndex: number) => {
    if (!currentScenario) return;

    const reactionTime = Date.now() - questionStartTime;
    const isCorrect = optionIndex === currentScenario.correctAnswer;
    
    const result: ScenarioResult = {
      stepId: currentScenario.id,
      selectedOption: optionIndex,
      isCorrect,
      timestamp: currentTime,
      reactionTime
    };

    const newResults = [...scenarioResults, result];
    setScenarioResults(newResults);
    setCompletedScenarios(prev => new Set([...Array.from(prev), currentScenario.id]));
    setShowQuestion(false);
    setCurrentScenario(null);

    // Resume video if it was paused
    const video = videoRef.current;
    if (video && video.paused && currentScenario.pauseVideo) {
      video.play();
      setIsPlaying(true);
    }

    // Check if all scenarios completed
    if (newResults.length === scenarios.length) {
      onScenarioComplete(newResults);
    }
  };

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

  const progress = duration > 0 ? (currentTime / duration) * 100 : 0;

  return (
    <div className={cn("bg-white rounded-lg shadow-lg overflow-hidden", className)}>
      {/* Header */}
      <div className="p-4 bg-gradient-to-r from-blue-600 to-blue-700 text-white">
        <h3 className="text-lg font-semibold">{title}</h3>
        <p className="text-blue-100 text-sm mt-1">{description}</p>
        <div className="flex items-center gap-4 mt-2 text-sm">
          <span className="flex items-center gap-1">
            <Clock size={16} />
            {formatTime(currentTime)} / {formatTime(duration)}
          </span>
          <span className="flex items-center gap-1">
            <CheckCircle size={16} />
            {completedScenarios.size}/{scenarios.length} Scenario
          </span>
        </div>
      </div>

      {/* Video Container */}
      <div className="relative bg-black">
        <video
          ref={videoRef}
          src={videoSrc}
          className="w-full aspect-video"
          onPlay={() => setIsPlaying(true)}
          onPause={() => setIsPlaying(false)}
        />

        {/* Video Controls Overlay */}
        <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-4">
          {/* Progress Bar */}
          <div className="mb-3">
            <div className="w-full bg-white/20 rounded-full h-1">
              <div 
                className="bg-blue-500 h-1 rounded-full transition-all duration-300"
                style={{ width: `${progress}%` }}
              />
            </div>
            {/* Scenario Markers */}
            {scenarios.map((scenario) => (
              <div
                key={scenario.id}
                className={cn(
                  "absolute top-0 w-2 h-2 rounded-full transform -translate-x-1 -translate-y-1",
                  completedScenarios.has(scenario.id) 
                    ? "bg-green-400" 
                    : "bg-yellow-400"
                )}
                style={{ 
                  left: `${duration > 0 ? (scenario.timestamp / duration) * 100 : 0}%` 
                }}
                title={`Scenario: ${scenario.title}`}
              />
            ))}
          </div>

          {/* Control Buttons */}
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <button
                onClick={togglePlay}
                className="p-2 bg-white/20 hover:bg-white/30 rounded-full transition-colors"
              >
                {isPlaying ? <Pause size={20} /> : <Play size={20} />}
              </button>
              <button
                onClick={restart}
                className="p-2 bg-white/20 hover:bg-white/30 rounded-full transition-colors"
              >
                <RotateCcw size={20} />
              </button>
              <button
                onClick={toggleMute}
                className="p-2 bg-white/20 hover:bg-white/30 rounded-full transition-colors"
              >
                {isMuted ? <VolumeX size={20} /> : <Volume2 size={20} />}
              </button>
            </div>
            
            <div className="text-white text-sm">
              {formatTime(currentTime)} / {formatTime(duration)}
            </div>
          </div>
        </div>

        {/* Question Overlay */}
        {showQuestion && currentScenario && (
          <div className="absolute inset-0 bg-black/80 flex items-center justify-center p-6">
            <div className="bg-white rounded-lg max-w-2xl w-full p-6">
              <div className="flex items-center gap-2 mb-4">
                <AlertCircle className="text-blue-600" size={24} />
                <h4 className="text-lg font-semibold text-gray-800">
                  {currentScenario.title}
                </h4>
              </div>
              
              <p className="text-gray-700 mb-6">{currentScenario.question}</p>
              
              <div className="space-y-3">
                {currentScenario.options.map((option, index) => (
                  <button
                    key={option.id}
                    onClick={() => handleAnswerSelect(index)}
                    className="w-full p-4 text-left border-2 border-gray-200 rounded-lg hover:border-blue-500 hover:bg-blue-50 transition-colors"
                  >
                    <div className="flex items-start gap-3">
                      <span className="flex-shrink-0 w-6 h-6 bg-blue-100 text-blue-600 rounded-full flex items-center justify-center text-sm font-medium">
                        {String.fromCharCode(65 + index)}
                      </span>
                      <div>
                        <p className="font-medium text-gray-800">{option.text}</p>
                        {option.consequence && (
                          <p className="text-sm text-gray-600 mt-1">{option.consequence}</p>
                        )}
                      </div>
                    </div>
                  </button>
                ))}
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Scenario Progress */}
      <div className="p-4 bg-gray-50">
        <div className="flex items-center justify-between mb-2">
          <span className="text-sm font-medium text-gray-700">Progress Scenario</span>
          <span className="text-sm text-gray-600">
            {completedScenarios.size}/{scenarios.length} selesai
          </span>
        </div>
        <div className="flex gap-2">
          {scenarios.map((scenario) => (
            <div
              key={scenario.id}
              className={cn(
                "flex-1 h-2 rounded-full",
                completedScenarios.has(scenario.id)
                  ? "bg-green-400"
                  : currentScenario?.id === scenario.id
                  ? "bg-yellow-400"
                  : "bg-gray-200"
              )}
              title={scenario.title}
            />
          ))}
        </div>
      </div>
    </div>
  );
};

export default VideoScenario;