import React, { useRef, useState, useEffect } from 'react';
import { 
  X, 
  Play, 
  Pause, 
  Volume2, 
  VolumeX, 
  Maximize, 
  RotateCcw,
  Sparkles,
  ExternalLink
} from 'lucide-react';
import { REAL_YACHT_PHOTOS, BOOKING_FORM_URL } from '../data/yachtData';

interface VideoPlayerModalProps {
  isOpen: boolean;
  onClose: () => void;
  onOpenBooking: () => void;
}

export const VideoPlayerModal: React.FC<VideoPlayerModalProps> = ({
  isOpen,
  onClose,
  onOpenBooking
}) => {
  const videoRef = useRef<HTMLVideoElement>(null);
  const [isPlaying, setIsPlaying] = useState(true);
  const [isMuted, setIsMuted] = useState(false);
  const [progress, setProgress] = useState(0);
  const [duration, setDuration] = useState(0);
  const [currentTime, setCurrentTime] = useState(0);

  useEffect(() => {
    if (isOpen && videoRef.current) {
      videoRef.current.currentTime = 0;
      videoRef.current.play().then(() => {
        setIsPlaying(true);
      }).catch(() => {
        setIsPlaying(false);
      });
    }
  }, [isOpen]);

  if (!isOpen) return null;

  const togglePlay = () => {
    if (videoRef.current) {
      if (isPlaying) {
        videoRef.current.pause();
        setIsPlaying(false);
      } else {
        videoRef.current.play().then(() => setIsPlaying(true)).catch(() => {});
      }
    }
  };

  const toggleMute = () => {
    if (videoRef.current) {
      videoRef.current.muted = !isMuted;
      setIsMuted(!isMuted);
    }
  };

  const handleTimeUpdate = () => {
    if (videoRef.current) {
      const cur = videoRef.current.currentTime;
      const dur = videoRef.current.duration || 1;
      setCurrentTime(cur);
      setDuration(dur);
      setProgress((cur / dur) * 100);
    }
  };

  const handleSeek = (e: React.ChangeEvent<HTMLInputElement>) => {
    const val = parseFloat(e.target.value);
    if (videoRef.current && duration) {
      const targetTime = (val / 100) * duration;
      videoRef.current.currentTime = targetTime;
      setProgress(val);
    }
  };

  const handleRestart = () => {
    if (videoRef.current) {
      videoRef.current.currentTime = 0;
      videoRef.current.play().then(() => setIsPlaying(true)).catch(() => {});
    }
  };

  const handleFullScreen = () => {
    if (videoRef.current) {
      if (videoRef.current.requestFullscreen) {
        videoRef.current.requestFullscreen();
      }
    }
  };

  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs < 10 ? '0' : ''}${secs}`;
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-3 sm:p-6 bg-slate-950/95 backdrop-blur-2xl">
      <div className="relative w-full max-w-5xl bg-[#1e2a38] border border-[#517e8a]/40 rounded-3xl overflow-hidden shadow-2xl flex flex-col my-auto">
        
        {/* Top Header */}
        <div className="px-5 py-3.5 bg-[#2b3b4e] border-b border-[#517e8a]/20 flex items-center justify-between z-20">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 rounded-lg bg-[#e17f52]/20 border border-[#e17f52]/40 flex items-center justify-center text-[#e17f52]">
              <Sparkles className="w-4 h-4" />
            </div>
            <div>
              <h3 className="text-sm font-bold text-white tracking-wide">
                Entourage Yacht Experience Video
              </h3>
              <p className="text-[11px] text-slate-300 font-light">
                22m Luxury Superyacht • Hong Kong
              </p>
            </div>
          </div>

          <div className="flex items-center gap-3">
            <button
              onClick={() => {
                onClose();
                onOpenBooking();
              }}
              className="hidden sm:inline-flex items-center gap-1 px-3.5 py-1.5 rounded-lg bg-[#e17f52] hover:bg-[#ea8e64] text-white text-xs font-semibold uppercase tracking-wider transition-all cursor-pointer"
            >
              <span>Enquire Now</span>
            </button>
            <button
              onClick={onClose}
              className="p-2 rounded-xl bg-[#1e2a38] hover:bg-[#3b4e63] text-slate-300 hover:text-white border border-[#517e8a]/30 transition-colors cursor-pointer"
              aria-label="Close video"
            >
              <X className="w-5 h-5" />
            </button>
          </div>
        </div>

        {/* Video Player Canvas */}
        <div className="relative bg-black aspect-video flex items-center justify-center overflow-hidden group">
          <video
            ref={videoRef}
            src="/videos/entourage_hero.mp4"
            poster={REAL_YACHT_PHOTOS.aerialTopDown}
            autoPlay
            playsInline
            muted={isMuted}
            onTimeUpdate={handleTimeUpdate}
            onLoadedMetadata={handleTimeUpdate}
            onEnded={() => setIsPlaying(false)}
            onClick={togglePlay}
            className="w-full h-full object-contain cursor-pointer"
          >
            <source src="/videos/entourage_hero.mp4" type="video/mp4" />
            <source src="/videos/entourage_yacht_hero.mp4" type="video/mp4" />
          </video>

          {/* Big Play Overlay if paused */}
          {!isPlaying && (
            <button
              onClick={togglePlay}
              className="absolute inset-0 m-auto w-16 h-16 sm:w-20 sm:h-20 rounded-full bg-[#e17f52]/90 hover:bg-[#e17f52] text-white flex items-center justify-center shadow-2xl transition-transform hover:scale-110 active:scale-95 cursor-pointer z-10"
              aria-label="Play video"
            >
              <Play className="w-8 h-8 sm:w-10 sm:h-10 fill-current translate-x-0.5" />
            </button>
          )}

          {/* Bottom Video Controller Bar */}
          <div className="absolute inset-x-0 bottom-0 p-4 bg-gradient-to-t from-black/90 via-black/50 to-transparent flex flex-col gap-2 transition-opacity z-20">
            
            {/* Progress Bar */}
            <div className="flex items-center gap-3">
              <input
                type="range"
                min="0"
                max="100"
                value={progress || 0}
                onChange={handleSeek}
                className="w-full h-1.5 bg-white/20 rounded-lg appearance-none cursor-pointer accent-[#e17f52]"
              />
              <span className="text-[11px] text-slate-300 font-mono shrink-0 select-none">
                {formatTime(currentTime)} / {formatTime(duration)}
              </span>
            </div>

            {/* Controls Bar */}
            <div className="flex items-center justify-between pt-1 text-white">
              <div className="flex items-center gap-3">
                <button
                  onClick={togglePlay}
                  className="p-2 rounded-lg hover:bg-white/10 text-white transition-colors cursor-pointer"
                  aria-label={isPlaying ? "Pause" : "Play"}
                >
                  {isPlaying ? <Pause className="w-4 h-4" /> : <Play className="w-4 h-4 fill-current" />}
                </button>

                <button
                  onClick={handleRestart}
                  className="p-2 rounded-lg hover:bg-white/10 text-slate-300 hover:text-white transition-colors cursor-pointer"
                  aria-label="Restart video"
                  title="Restart"
                >
                  <RotateCcw className="w-4 h-4" />
                </button>

                <button
                  onClick={toggleMute}
                  className="p-2 rounded-lg hover:bg-white/10 text-slate-300 hover:text-white transition-colors cursor-pointer"
                  aria-label={isMuted ? "Unmute" : "Mute"}
                >
                  {isMuted ? <VolumeX className="w-4 h-4 text-slate-400" /> : <Volume2 className="w-4 h-4 text-[#e17f52]" />}
                </button>
              </div>

              <div className="flex items-center gap-2">
                <button
                  onClick={handleFullScreen}
                  className="p-2 rounded-lg hover:bg-white/10 text-slate-300 hover:text-white transition-colors cursor-pointer"
                  aria-label="Full screen"
                  title="Full screen"
                >
                  <Maximize className="w-4 h-4" />
                </button>
              </div>
            </div>

          </div>
        </div>

        {/* Footer info & CTA */}
        <div className="px-5 py-4 bg-[#2b3b4e] border-t border-[#517e8a]/20 flex flex-col sm:flex-row items-center justify-between gap-3 text-xs text-slate-300">
          <p className="font-light">
            Charter Entourage for private events, harbour cruises, day sails, and celebrations.
          </p>
          <button
            onClick={() => {
              onClose();
              onOpenBooking();
            }}
            className="w-full sm:w-auto px-5 py-2.5 rounded-xl bg-[#e17f52] hover:bg-[#ea8e64] text-white font-bold tracking-wider uppercase transition-all shadow-md shadow-[#e17f52]/20 cursor-pointer text-center inline-flex items-center justify-center gap-1.5"
          >
            <span>Booking Enquiry</span>
          </button>
        </div>

      </div>
    </div>
  );
};
