"use client";

import { useEffect, useRef } from "react";
// @ts-ignore
import Plyr from "plyr";
import "plyr/dist/plyr.css";
import { X, Play, Monitor, Info } from "lucide-react";

interface SourcePreviewModalProps {
    filePath: string;
    fileName: string;
    fileInfo: any;
    onClose: () => void;
}

export default function SourcePreviewModal({ filePath, fileName, fileInfo, onClose }: SourcePreviewModalProps) {
    const videoRef = useRef<HTMLVideoElement>(null);
    const playerRef = useRef<any>(null);

    const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001';

    // Map the absolute local path to the served static URL
    // backend serves data/downloads as /originals
    // backend serves data/extracted as /extracted
    const getServedUrl = () => {
        const isExtracted = filePath.includes('extracted');
        const type = isExtracted ? 'extracted' : 'originals';
        
        // We need the sessionId and fileName from the path
        // Typical path: C:\...\data\downloads\session-id\file.mkv
        const parts = filePath.split(/[\\/]/);
        const name = parts.pop();
        const sessionId = parts.pop();
        
        return `${API_URL}/${type}/${sessionId}/${name}`;
    };

    const previewUrl = getServedUrl();
    const vlcUrl = `vlc://${previewUrl}`;

    useEffect(() => {
        if (videoRef.current) {
            playerRef.current = new Plyr(videoRef.current, {
                controls: [
                    'play-large', 'play', 'progress', 'current-time', 'mute', 'volume', 'captions', 'settings', 'pip', 'airplay', 'fullscreen'
                ],
                tooltips: { controls: true, seek: true }
            });
        }

        return () => {
            if (playerRef.current) {
                playerRef.current.destroy();
            }
        };
    }, []);

    return (
        <div className="fixed inset-0 z-[200] flex items-center justify-center p-4 md:p-8 bg-black/95 backdrop-blur-md animate-fade-in">
            <div className="w-full max-w-6xl bg-zinc-900 border border-white/10 rounded-3xl overflow-hidden shadow-2xl flex flex-col max-h-full">
                {/* Header */}
                <div className="p-4 md:p-6 border-b border-white/5 flex items-center justify-between gap-4">
                    <div className="min-w-0">
                        <div className="flex items-center gap-2 mb-1">
                            <span className="badge badge-cyan">Source Preview</span>
                            <span className="text-[10px] font-mono text-white/40 tracking-widest uppercase">Format: {fileInfo?.format || 'Unknown'}</span>
                        </div>
                        <h2 className="text-lg font-bold truncate text-white">{fileName}</h2>
                    </div>
                    <button onClick={onClose} className="p-2 hover:bg-white/5 rounded-full transition-colors">
                        <X className="w-5 h-5 text-white/40" />
                    </button>
                </div>

                <div className="flex-1 overflow-y-auto no-scrollbar flex flex-col lg:flex-row">
                    {/* Player Section */}
                    <div className="flex-1 bg-black aspect-video lg:aspect-auto flex items-center justify-center relative">
                        <div className="w-full h-full">
                            <video
                                ref={videoRef}
                                playsInline
                                controls
                                className="w-full h-full"
                            >
                                <source src={previewUrl} />
                            </video>
                        </div>
                    </div>

                    {/* Info Sidebar */}
                    <div className="w-full lg:w-80 p-6 space-y-8 bg-zinc-900 border-l border-white/5">
                        <div className="space-y-4">
                            <h3 className="text-xs font-black uppercase tracking-widest text-white/40 flex items-center gap-2">
                                <Info className="w-3 h-3" />
                                Stream Actions
                            </h3>

                            <a
                                href={vlcUrl}
                                className="flex items-center justify-between p-4 bg-orange-500/10 border border-orange-500/20 rounded-2xl group hover:border-orange-500/40 transition-all active:scale-[0.98]"
                            >
                                <div className="flex items-center gap-3">
                                    <div className="w-10 h-10 rounded-xl bg-orange-500/10 flex items-center justify-center text-orange-500">
                                        <Monitor className="w-5 h-5" />
                                    </div>
                                    <div>
                                        <p className="text-sm font-bold text-white">Open in VLC</p>
                                        <p className="text-[10px] text-orange-400 font-bold uppercase tracking-tight">External Codec Play</p>
                                    </div>
                                </div>
                                <Play className="w-4 h-4 text-orange-400 opacity-40 group-hover:opacity-100 transition-opacity" />
                            </a>
                            
                            <p className="text-[10px] text-white/40 leading-relaxed px-1">
                                <span className="font-bold text-white/60">Note:</span> Browsers do not support all codecs (like HEVC or EAC3). If video doesn't play, use the <span className="text-orange-400">VLC option</span> above.
                            </p>
                        </div>

                        <div className="pt-8 border-t border-white/5">
                            <h3 className="text-[10px] font-black uppercase tracking-widest text-white/20 mb-4">Source Specs</h3>
                            <div className="space-y-4">
                                <SpecItem label="Duration" value={fileInfo?.durationHuman || "N/A"} />
                                <SpecItem label="Size" value={fileInfo?.fileSizeHuman || "N/A"} />
                                <SpecItem label="Video Codec" value={fileInfo?.videoStreams?.[0]?.codec || "N/A"} />
                                <SpecItem label="Resolution" value={fileInfo?.videoStreams?.[0]?.resolution || "N/A"} />
                                <SpecItem label="Audio Tracks" value={String(fileInfo?.audioStreams?.length || 0)} />
                                <SpecItem label="Subtitles" value={String(fileInfo?.subtitleStreams?.length || 0)} />
                            </div>
                        </div>
                        
                        <button 
                            onClick={onClose}
                            className="w-full py-4 rounded-2xl bg-white/5 hover:bg-white/10 text-white font-bold transition-all border border-white/5"
                        >
                            Back to Config
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
}

function SpecItem({ label, value }: { label: string, value: string }) {
    return (
        <div className="flex justify-between items-center text-[10px]">
            <span className="font-bold text-white/30 uppercase tracking-tighter">{label}</span>
            <span className="font-mono text-white/60">{value}</span>
        </div>
    );
}
