"use client";

import { useEffect, useRef, useState } from "react";
import * as PlyrModule from "plyr";
const Plyr = (PlyrModule as any).default || PlyrModule;
import "plyr/dist/plyr.css";
import { X, CheckCircle, Trash2, ExternalLink, Play, Monitor, Info, FolderPlus, Globe, Link2, ChevronRight } from "lucide-react";
import { approveJob, discardJob } from "@/lib/api";
import { clsx } from "clsx";
import { useUI } from "@/context/UIContext";
import ComparePlayer from "./ComparePlayer";

interface QCPreviewModalProps {
    job: any;
    onClose: () => void;
    onStatusChange: () => void;
}

export default function QCPreviewModal({ job, onClose, onStatusChange }: QCPreviewModalProps) {
    const { confirm, alert } = useUI();
    const videoRef = useRef<HTMLVideoElement>(null);
    const playerRef = useRef<any>(null);
    const [loading, setLoading] = useState(false);
    const [selectedRes, setSelectedRes] = useState<any>(job.output_files?.[0] || null);
    const [uploadMode, setUploadMode] = useState<"auto" | "manual">("auto");
    const [customFolder, setCustomFolder] = useState("");
    const [showCompare, setShowCompare] = useState(false);

    const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001';

    useEffect(() => {
        if (videoRef.current && selectedRes) {
            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();
            }
        };
    }, [selectedRes]);

    const handleApprove = async () => {
        if (uploadMode === 'manual' && !customFolder) {
            return alert({ title: "Input Required", message: "Please provide a GDrive Folder link or ID for manual routing.", type: "warning" });
        }

        const ok = await confirm({
            title: "Approve Media?",
            message: uploadMode === 'manual'
                ? "This will start the final upload to your CUSTOM folder. Proceed?"
                : "This will start the final upload to the default Google Drive root. Proceed?",
            type: "success",
            confirmLabel: "Approve & Upload"
        });
        if (!ok) return;

        setLoading(true);
        try {
            await approveJob(job.id, uploadMode === 'manual' ? customFolder : undefined);
            onStatusChange();
            onClose();
        } catch (err: any) {
            alert({ title: "Error", message: err.message, type: "error" });
        } finally {
            setLoading(false);
        }
    };

    const handleDiscard = async () => {
        const ok = await confirm({
            title: "Discard Files?",
            message: "REJECT & DELETE this file? This cannot be undone.",
            type: "danger",
            confirmLabel: "Delete Forever"
        });
        if (!ok) return;

        setLoading(true);
        try {
            await discardJob(job.id);
            onStatusChange();
            onClose();
        } catch (err: any) {
            alert({ title: "Error", message: err.message, type: "error" });
        } finally {
            setLoading(false);
        }
    };

    const getPreviewUrl = (outputPath: string) => {
        // Map local path back to /previews/jobId/filename
        const fileName = outputPath.split(/[\\/]/).pop();
        return `${API_URL}/previews/${job.id}/${fileName}`;
    };

    const vlcUrl = selectedRes ? `vlc://${getPreviewUrl(selectedRes.outputPath)}` : "";

    const getOriginalUrl = () => {
        const path = job.file_info?.path;
        if (!path) return "";
        const type = path.includes('extracted') ? 'extracted' : 'originals';
        const fileName = path.split(/[\\/]/).pop();
        return `${API_URL}/${type}/${job.id}/${fileName}`;
    };

    return (
        <>
            <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 md:p-8 bg-black/90 backdrop-blur-sm 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-amber">Awaiting Review</span>
                                <span className="text-[10px] font-mono text-white/40 tracking-widest uppercase">ID: {job.id.slice(0, 8)}</span>
                            </div>
                            <h2 className="text-lg font-bold truncate text-white">{job.original_file_name}</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 group">
                            {selectedRes ? (
                                <div className="w-full h-full">
                                    <video
                                        ref={videoRef}
                                        key={selectedRes.outputPath}
                                        playsInline
                                        controls
                                        className="w-full h-full"
                                    >
                                        <source src={getPreviewUrl(selectedRes.outputPath)} type="video/webm" />
                                        <source src={getPreviewUrl(selectedRes.outputPath)} type="video/mp4" />
                                    </video>
                                </div>
                            ) : (
                                <div className="text-white/20 text-center animate-pulse">
                                    <Play className="w-12 h-12 mx-auto mb-4 opacity-10" />
                                    <p className="text-xs uppercase font-bold tracking-widest">Select target to preview</p>
                                </div>
                            )}

                            {/* Top Overlay - Resolution Switcher */}
                            <div className="absolute top-4 left-4 right-4 flex justify-between pointer-events-none">
                                <div className="flex gap-2 pointer-events-auto">
                                    {job.output_files?.map((f: any, i: number) => (
                                        <button
                                            key={i}
                                            onClick={() => setSelectedRes(f)}
                                            className={clsx(
                                                "px-3 py-1.5 rounded-lg text-[10px] font-black uppercase tracking-tighter transition-all",
                                                selectedRes === f ? "bg-accent-cyan text-white  scale-105" : "bg-black/60 text-white/40 border border-white/5 hover:bg-black/80"
                                            )}
                                        >
                                            {f.resolution}
                                        </button>
                                    ))}
                                </div>
                            </div>
                        </div>

                        {/* Controls & Details 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" />
                                    Verification Actions
                                </h3>

                                <button
                                    onClick={() => setShowCompare(true)}
                                    className="flex items-center justify-between p-4 bg-accent-cyan/10 border border-accent-cyan/20 rounded-2xl group hover:border-accent-cyan/40 transition-all active:scale-[0.98]"
                                >
                                    <div className="flex items-center gap-3">
                                        <div className="w-10 h-10 rounded-xl bg-accent-cyan/10 flex items-center justify-center text-accent-cyan">
                                            <Monitor className="w-5 h-5" />
                                        </div>
                                        <div>
                                            <p className="text-sm font-bold text-white">Compare Tool</p>
                                            <p className="text-[10px] text-accent-cyan/60 font-bold uppercase tracking-tight">Side-by-Side Review</p>
                                        </div>
                                    </div>
                                    <div className="p-1 bg-white/5 rounded-lg group-hover:bg-accent-cyan group-hover:text-black transition-colors">
                                        <ChevronRight className="w-4 h-4" />
                                    </div>
                                </button>

                                <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">Full Codec Check</p>
                                        </div>
                                    </div>
                                    <ExternalLink className="w-4 h-4 text-orange-400 opacity-40 group-hover:opacity-100 transition-opacity" />
                                </a>

                                <div className="pt-2 space-y-4">
                                    <div className="space-y-2">
                                        <p className="text-[10px] font-black uppercase tracking-widest text-white/30 px-1">Upload Destination</p>
                                        <div className="flex bg-black/40 p-1 rounded-xl border border-white/5">
                                            <button
                                                onClick={() => setUploadMode("auto")}
                                                className={clsx("flex-1 py-2 text-[10px] font-bold uppercase tracking-widest rounded-lg transition-all", uploadMode === 'auto' ? "bg-white/5 text-white shadow-inner" : "text-white/20 hover:text-white/40")}
                                            >
                                                Automatic
                                            </button>
                                            <button
                                                onClick={() => setUploadMode("manual")}
                                                className={clsx("flex-1 py-2 text-[10px] font-bold uppercase tracking-widest rounded-lg transition-all", uploadMode === 'manual' ? "bg-white/5 text-white shadow-inner" : "text-white/20 hover:text-white/40")}
                                            >
                                                Manual Link
                                            </button>
                                        </div>
                                    </div>

                                    {uploadMode === 'manual' && (
                                        <div className="space-y-2 animate-slide-up">
                                            <div className="relative">
                                                <input
                                                    type="text"
                                                    value={customFolder}
                                                    onChange={(e) => setCustomFolder(e.target.value)}
                                                    placeholder="Paste folder link or ID..."
                                                    className="w-full bg-black/40 border border-white/5 rounded-xl px-4 py-3 text-xs text-white placeholder:text-white/10 focus:outline-none focus:border-accent-cyan/40 transition-all pr-10"
                                                />
                                                <Link2 className="absolute right-3 top-3 w-4 h-4 text-white/10" />
                                            </div>
                                            <p className="text-[9px] text-white/60 font-medium leading-tight px-1 italic">
                                                Tip: You can paste the full GDrive URL. We'll extract the ID automatically.
                                            </p>
                                        </div>
                                    )}
                                </div>

                                <div className="pt-2 space-y-3">
                                    <button
                                        onClick={handleApprove}
                                        disabled={loading}
                                        className="btn-primary w-full justify-center py-4 rounded-2xl "
                                    >
                                        <CheckCircle className="w-5 h-5 mr-2" />
                                        Approve & Upload
                                    </button>
                                    <button
                                        onClick={handleDiscard}
                                        disabled={loading}
                                        className="w-full flex items-center justify-center py-4 rounded-2xl bg-red-500/10 text-red-500 border border-red-500/20 hover:bg-red-500/20 transition-all font-bold text-sm active:scale-[0.98]"
                                    >
                                        <Trash2 className="w-5 h-5 mr-2" />
                                        Discard Files
                                    </button>
                                </div>
                            </div>

                            <div className="pt-8 border-t border-white/5">
                                <h3 className="text-[10px] font-black uppercase tracking-widest text-white/20 mb-4">Encoded Specs</h3>
                                <div className="space-y-4">
                                    <SpecItem label="Target Resolution" value={selectedRes?.resolution || "N/A"} />
                                    <SpecItem label="Source Codec" value={job.file_info?.videoCodec || "N/A"} />
                                    <SpecItem label="Audio Channels" value={job.file_info?.audioChannels || "N/A"} />
                                    <SpecItem label="Duration" value={job.file_info?.durationHuman || "N/A"} />
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Footer Message */}
                    <div className="bg-black/30 p-3 text-center border-t border-white/5">
                        <p className="text-[10px] text-white/20 font-bold uppercase tracking-[0.2em]">Quality Control System Phase v1.0 • MovieHubBD Exclusive</p>
                    </div>
                </div>

                {showCompare && (
                    <ComparePlayer
                        originalUrl={getOriginalUrl()}
                        encodedUrl={getPreviewUrl(selectedRes.outputPath)}
                        originalLabel="Source Media"
                        encodedLabel={`Result: ${selectedRes.resolution}`}
                        onClose={() => setShowCompare(false)}
                    />
                )}
            </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>
    );
}
