"use client";

import { useEffect, useRef, useState } from "react";
import { X, Play, Pause, RotateCcw, Volume2, VolumeX, Maximize, ChevronRight, Info } from "lucide-react";
import { clsx } from "clsx";

interface ComparePlayerProps {
    originalUrl: string;
    encodedUrl: string;
    originalLabel?: string;
    encodedLabel?: string;
    onClose: () => void;
}

export default function ComparePlayer({ originalUrl, encodedUrl, originalLabel = "Original Source", encodedLabel = "Encoded Result", onClose }: ComparePlayerProps) {
    const v1Ref = useRef<HTMLVideoElement>(null);
    const v2Ref = useRef<HTMLVideoElement>(null);
    const [playing, setPlaying] = useState(false);
    const [currentTime, setCurrentTime] = useState(0);
    const [duration, setDuration] = useState(0);
    const [muted, setMuted] = useState(true);
    const [volume, setVolume] = useState(1);
    const [isSyncing, setIsSyncing] = useState(true);

    useEffect(() => {
        const v1 = v1Ref.current;
        const v2 = v2Ref.current;
        if (!v1 || !v2) return;

        const handleTimeUpdate = () => {
            if (v1.duration) {
                setCurrentTime(v1.currentTime);
                setDuration(v1.duration);
            }
        };

        const handlePlay = () => setPlaying(true);
        const handlePause = () => setPlaying(false);

        v1.addEventListener("timeupdate", handleTimeUpdate);
        v1.addEventListener("play", handlePlay);
        v1.addEventListener("pause", handlePause);

        return () => {
            v1.removeEventListener("timeupdate", handleTimeUpdate);
            v1.removeEventListener("play", handlePlay);
            v1.removeEventListener("pause", handlePause);
        };
    }, []);

    // Sync v2 to v1
    useEffect(() => {
        if (!isSyncing) return;
        const v1 = v1Ref.current;
        const v2 = v2Ref.current;
        if (!v1 || !v2) return;

        const sync = () => {
            if (Math.abs(v1.currentTime - v2.currentTime) > 0.1) {
                v2.currentTime = v1.currentTime;
            }
            if (v1.paused !== v2.paused) {
                v1.paused ? v2.pause() : v2.play().catch(() => { });
            }
        };

        const interval = setInterval(sync, 50);
        return () => clearInterval(interval);
    }, [isSyncing]);

    const togglePlay = () => {
        if (!v1Ref.current || !v2Ref.current) return;
        if (playing) {
            v1Ref.current.pause();
            v2Ref.current.pause();
        } else {
            v1Ref.current.play();
            v2Ref.current.play();
        }
    };

    const handleSeek = (e: React.ChangeEvent<HTMLInputElement>) => {
        const val = parseFloat(e.target.value);
        if (v1Ref.current) v1Ref.current.currentTime = val;
        if (v2Ref.current) v2Ref.current.currentTime = val;
    };

    const formatTime = (time: number) => {
        const m = Math.floor(time / 60);
        const s = Math.floor(time % 60);
        return `${m}:${s.toString().padStart(2, "0")}`;
    };

    return (
        <div className="fixed inset-0 z-[120] bg-black flex flex-col font-sans animate-fade-in">
            {/* Header */}
            <div className="p-4 bg-zinc-900/50 border-b border-white/5 flex items-center justify-between">
                <div className="flex items-center gap-4">
                    <h2 className="text-white font-black uppercase tracking-widest text-sm flex items-center gap-2">
                        <Monitor className="w-4 h-4 text-accent-cyan" />
                        Side-by-Side Comparison
                    </h2>
                    <div className="h-4 w-[1px] bg-white/10" />
                    <button
                        onClick={() => setIsSyncing(!isSyncing)}
                        className={clsx(
                            "px-3 py-1 rounded-full text-[10px] font-bold uppercase transition-all",
                            isSyncing ? "bg-accent-cyan/10 text-accent-cyan border border-accent-cyan/20" : "bg-white/5 text-white/40 border border-white/10"
                        )}
                    >
                        {isSyncing ? "Lock: Synced" : "Unlock: Free"}
                    </button>
                </div>
                <button onClick={onClose} className="p-2 hover:bg-white/5 rounded-full">
                    <X className="text-white/40 w-6 h-6" />
                </button>
            </div>

            {/* Players Area */}
            <div className="flex-1 flex flex-col md:row overflow-hidden p-2 gap-2">
                <div className="flex-1 flex flex-col md:flex-row gap-2">
                    {/* Original */}
                    <div className="flex-1 bg-zinc-950 rounded-2xl overflow-hidden relative group">
                        <video ref={v1Ref} src={originalUrl} muted={muted} className="w-full h-full object-contain" />
                        <div className="absolute top-4 left-4 bg-black/60 backdrop-blur-md px-3 py-1.5 rounded-lg border border-white/10">
                            <span className="text-white font-black text-[10px] uppercase tracking-widest">{originalLabel}</span>
                        </div>
                    </div>

                    {/* Encoded */}
                    <div className="flex-1 bg-zinc-950 rounded-2xl overflow-hidden relative group">
                        <video ref={v2Ref} src={encodedUrl} muted={muted} className="w-full h-full object-contain" />
                        <div className="absolute top-4 left-4 bg-accent-cyan/80 backdrop-blur-md px-3 py-1.5 rounded-lg border border-accent-cyan/20">
                            <span className="text-white font-black text-[10px] uppercase tracking-widest">{encodedLabel}</span>
                        </div>
                    </div>
                </div>
            </div>

            {/* Controls Bar */}
            <div className="p-6 bg-zinc-900 border-t border-white/10 flex flex-col gap-4">
                {/* Progress */}
                <div className="flex items-center gap-4">
                    <span className="text-[10px] font-mono text-white/40 w-10 text-right">{formatTime(currentTime)}</span>
                    <input
                        type="range"
                        min="0"
                        max={duration || 100}
                        value={currentTime}
                        onChange={handleSeek}
                        className="flex-1 h-1 bg-white/5 appearance-none rounded-full cursor-pointer accent-accent-cyan"
                    />
                    <span className="text-[10px] font-mono text-white/40 w-10">{formatTime(duration)}</span>
                </div>

                {/* Main Controls */}
                <div className="flex items-center justify-between">
                    <div className="flex items-center gap-6">
                        <button onClick={togglePlay} className="p-3 bg-white text-black rounded-full hover:scale-105 transition-transform active:scale-95">
                            {playing ? <Pause className="w-6 h-6 fill-current" /> : <Play className="w-6 h-6 fill-current ml-0.5" />}
                        </button>
                        <button onClick={() => { if (v1Ref.current) v1Ref.current.currentTime = 0; if (v2Ref.current) v2Ref.current.currentTime = 0; }} className="text-white/40 hover:text-white transition-colors">
                            <RotateCcw className="w-5 h-5" />
                        </button>

                        <div className="flex items-center gap-3 group">
                            <button onClick={() => setMuted(!muted)} className="text-white/40 hover:text-white transition-colors">
                                {muted ? <VolumeX className="w-5 h-5" /> : <Volume2 className="w-5 h-5" />}
                            </button>
                            <input
                                type="range" min="0" max="1" step="0.1" value={volume}
                                onChange={(e) => {
                                    const v = parseFloat(e.target.value);
                                    setVolume(v);
                                    if (v1Ref.current) v1Ref.current.volume = v;
                                    if (v2Ref.current) v2Ref.current.volume = v;
                                    if (v > 0) setMuted(false);
                                }}
                                className="w-20 h-1 bg-white/5 appearance-none rounded-full cursor-pointer accent-white opacity-0 group-hover:opacity-100 transition-opacity"
                            />
                        </div>
                    </div>

                    <div className="hidden lg:flex items-center gap-4 bg-black/40 px-4 py-2 rounded-2xl border border-white/5 text-white/40 text-[10px] font-bold uppercase tracking-widest">
                        <Info className="w-4 h-4 text-accent-cyan" />
                        Pixel-Perfect Validation Mode
                    </div>
                </div>
            </div>
        </div>
    );
}

function Monitor({ className }: { className?: string }) {
    return (
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
            <rect width="20" height="14" x="2" y="3" rx="2" ry="2" /><line x1="8" y1="21" x2="16" y2="21" /><line x1="12" y1="17" x2="12" y2="21" />
        </svg>
    );
}
