import { Head, Link } from '@inertiajs/react';
import { useState, useEffect, useRef } from 'react';
import { Show } from '@/types';

interface ReplayShowPageProps {
    show: Show;
    has_active_membership?: boolean;
    membership_expires_at?: string | null;
}

export default function ReplayShow({ 
    show, 
    has_active_membership = false,
    membership_expires_at = null,
}: ReplayShowPageProps) {
    const containerRef = useRef<HTMLDivElement>(null);
    const playerRef = useRef<any>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const isUnmountingRef = useRef(false);

    // Extract YouTube video ID from URL
    const extractYouTubeVideoId = (url: string): string | null => {
        if (!url) return null;

        try {
            // Handle different YouTube URL formats
            if (url.includes('youtube.com/watch?v=')) {
                const urlParams = new URLSearchParams(url.split('?')[1]);
                return urlParams.get('v');
            } else if (url.includes('youtu.be/')) {
                return url.split('youtu.be/')[1]?.split('?')[0] || null;
            } else if (url.includes('youtube.com/embed/')) {
                return url.split('youtube.com/embed/')[1]?.split('?')[0] || null;
            } else if (url.match(/^[a-zA-Z0-9_-]{11}$/)) {
                // Direct video ID
                return url;
            }
        } catch (err) {
            return null;
        }

        return null;
    };

    useEffect(() => {
        if (isUnmountingRef.current) {
            return;
        }

        if (!show.url_replay) {
            setError('URL replay tidak tersedia.');
            setLoading(false);
            return;
        }

        const videoId = extractYouTubeVideoId(show.url_replay);
        if (!videoId) {
            setError('Format URL YouTube tidak valid. Pastikan URL adalah link YouTube yang valid.');
            setLoading(false);
            return;
        }

        // Load Plyr CSS
        if (!document.getElementById('plyr-css')) {
            const link = document.createElement('link');
            link.id = 'plyr-css';
            link.rel = 'stylesheet';
            link.href = 'https://cdn.plyr.io/3.7.8/plyr.css';
            document.head.appendChild(link);
        }

        // Load Plyr JS
        const loadPlyr = () => {
            return new Promise((resolve, reject) => {
                if ((window as any).Plyr) {
                    resolve((window as any).Plyr);
                    return;
                }

                const script = document.createElement('script');
                script.src = 'https://cdn.plyr.io/3.7.8/plyr.polyfilled.js';
                script.onload = () => resolve((window as any).Plyr);
                script.onerror = reject;
                document.head.appendChild(script);
            });
        };

        const initPlayer = async () => {
            if (isUnmountingRef.current || !containerRef.current) {
                return;
            }

            try {
                setLoading(true);
                setError(null);

                // Load Plyr library
                const Plyr = await loadPlyr() as any;

                // Create div element for Plyr YouTube embed
                const videoWrapper = document.createElement('div');
                videoWrapper.className = 'plyr__video-embed';
                videoWrapper.setAttribute('data-plyr-provider', 'youtube');
                videoWrapper.setAttribute('data-plyr-embed-id', videoId);

                // Clear container and add wrapper
                if (containerRef.current) {
                    containerRef.current.innerHTML = '';
                    containerRef.current.appendChild(videoWrapper);
                }

                // Initialize Plyr with YouTube
                const player = new Plyr(videoWrapper, {
                    youtube: {
                        noCookie: false,
                        rel: 0,
                        modestbranding: 1,
                        iv_load_policy: 3,
                        disablekb: 1,
                        fs: 0,
                    },
                    controls: ['play-large', 'play', 'progress', 'current-time', 'mute', 'volume', 'settings', 'fullscreen'],
                    settings: ['quality', 'speed'],
                    speed: {
                        selected: 1,
                        options: [0.5, 0.75, 1, 1.25, 1.5, 2],
                    },
                });

                playerRef.current = player;

                // Prevent right-click context menu on player
                videoWrapper.addEventListener('contextmenu', (e) => {
                    e.preventDefault();
                    return false;
                });

                // Also prevent on iframe after it's created by Plyr
                setTimeout(() => {
                    const iframe = containerRef.current?.querySelector('iframe');
                    if (iframe) {
                        iframe.addEventListener('contextmenu', (e) => {
                            e.preventDefault();
                            return false;
                        });
                    }
                }, 1000);

                // Handle player ready
                player.on('ready', () => {
                    setLoading(false);
                });

                // Handle errors
                player.on('error', () => {
                    setError('Terjadi kesalahan saat memuat video. Silakan coba lagi.');
                    setLoading(false);
                });

                // Timeout fallback
                setTimeout(() => {
                    if (loading) {
                        setLoading(false);
                    }
                }, 10000);

            } catch (err: any) {
                console.error('Error initializing Plyr:', err);
                setError('Terjadi kesalahan saat memuat video. Silakan coba lagi.');
                setLoading(false);
            }
        };

        initPlayer();

        return () => {
            isUnmountingRef.current = true;
            
            if (playerRef.current) {
                try {
                    playerRef.current.destroy();
                } catch (e) {
                    // Ignore cleanup errors
                }
                playerRef.current = null;
            }
            
            if (containerRef.current) {
                containerRef.current.innerHTML = '';
            }
        };
    }, [show.url_replay]);

    const formatDate = (timestamp: number): string => {
        const date = new Date(timestamp * 1000);
        return date.toLocaleDateString('id-ID', {
            weekday: 'long',
            year: 'numeric',
            month: 'long',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
        });
    };

    if (error) {
        return (
            <div className="min-h-screen bg-gradient-to-br from-gray-900 via-gray-800 to-gray-900 flex items-center justify-center p-4">
                <div className="max-w-2xl w-full text-center">
                    <div className="rounded-lg bg-red-50 dark:bg-red-900/20 p-6 mb-6">
                        <p className="text-lg font-medium text-red-800 dark:text-red-200">
                            {error}
                        </p>
                    </div>
                    <Link
                        href="/dashboard/replay"
                        className="inline-flex items-center gap-2 rounded-md bg-blue-600 px-6 py-3 text-base font-medium text-white hover:bg-blue-700 dark:bg-blue-700 dark:hover:bg-blue-800 transition-colors"
                    >
                        <ArrowLeftIcon className="h-5 w-5" />
                        Kembali ke Daftar Replay
                    </Link>
                </div>
            </div>
        );
    }

    return (
        <div className="min-h-screen bg-gradient-to-br from-gray-900 via-gray-800 to-gray-900">
            <Head title={`${show.title} - Replay`} />
            
            {/* Header */}
            <div className="bg-black/50 backdrop-blur-sm border-b border-gray-700/50 sticky top-0 z-50">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
                    <div className="flex items-center justify-between">
                        <div className="flex items-center gap-4">
                            <Link
                                href="/dashboard/replay"
                                className="p-2 rounded-lg bg-gray-800/50 hover:bg-gray-700/50 text-gray-300 hover:text-white transition-colors"
                            >
                                <ArrowLeftIcon className="h-5 w-5" />
                            </Link>
                            <div>
                                <h1 className="text-xl sm:text-2xl font-bold text-white line-clamp-1">
                                    {show.title}
                                </h1>
                                <p className="text-sm text-gray-400 mt-1">
                                    {formatDate(show.start_time)}
                                </p>
                            </div>
                        </div>
                        {has_active_membership && (
                            <span className="hidden sm:inline-flex items-center gap-1.5 rounded-full bg-gradient-to-r from-purple-500 to-pink-500 px-3 py-1 text-xs font-semibold text-white shadow-lg">
                                <CrownIcon className="h-3.5 w-3.5" />
                                Membership Istimewa
                            </span>
                        )}
                    </div>
                </div>
            </div>

            {/* Main Content */}
            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
                <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    {/* Video Player - Takes 2/3 on large screens */}
                    <div className="lg:col-span-2">
                        <div className="bg-black rounded-lg overflow-hidden shadow-2xl">
                            <div className="relative w-full" style={{ aspectRatio: '16/9' }}>
                                {loading && (
                                    <div className="absolute inset-0 z-10 flex items-center justify-center bg-gray-900/90 rounded-lg">
                                        <div className="text-center">
                                            <div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-white mb-4"></div>
                                            <div className="text-white text-lg">Memuat video...</div>
                                        </div>
                                    </div>
                                )}
                                <div ref={containerRef} className="w-full h-full" />
                            </div>
                        </div>

                        {/* Show Description */}
                        {show.description && (
                            <div className="mt-6 bg-gray-800/50 backdrop-blur-sm rounded-lg p-6 border border-gray-700/50">
                                <h2 className="text-lg font-semibold text-white mb-3">Deskripsi Show</h2>
                                <p className="text-gray-300 leading-relaxed whitespace-pre-line">
                                    {show.description}
                                </p>
                            </div>
                        )}
                    </div>

                    {/* Sidebar Info */}
                    <div className="lg:col-span-1">
                        <div className="bg-gray-800/50 backdrop-blur-sm rounded-lg p-6 border border-gray-700/50 sticky top-20">
                            <div className="space-y-6">
                                {/* Show Info */}
                                <div>
                                    <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wide mb-4">
                                        Informasi Show
                                    </h3>
                                    <div className="space-y-3">
                                        <div>
                                            <p className="text-xs text-gray-500">Judul</p>
                                            <p className="text-white font-medium">{show.title}</p>
                                        </div>
                                        <div>
                                            <p className="text-xs text-gray-500">Tanggal & Waktu</p>
                                            <p className="text-white font-medium">{formatDate(show.start_time)}</p>
                                        </div>
                                        {show.type && (
                                            <div>
                                                <p className="text-xs text-gray-500">Tipe</p>
                                                <p className="text-white font-medium">{show.type}</p>
                                            </div>
                                        )}
                                    </div>
                                </div>

                                {/* Actions */}
                                <div className="pt-4 border-t border-gray-700/50">
                                    <Link
                                        href="/dashboard/replay"
                                        className="w-full flex items-center justify-center gap-2 rounded-md bg-blue-600 px-4 py-3 text-sm font-medium text-white hover:bg-blue-700 dark:bg-blue-700 dark:hover:bg-blue-800 transition-colors"
                                    >
                                        <ArrowLeftIcon className="h-4 w-4" />
                                        Kembali ke Daftar Replay
                                    </Link>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}

// Icons
function ArrowLeftIcon({ className }: { className?: string }) {
    return (
        <svg className={className} fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" d="M10.5 19.5L3 12m0 0l7.5-7.5M3 12h18" />
        </svg>
    );
}

function CrownIcon({ className }: { className?: string }) {
    return (
        <svg className={className} fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" d="M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09zM18.259 8.715L18 9.75l-.259-1.035a3.375 3.375 0 00-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 002.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 002.456 2.456L21.75 6l-1.035.259a3.375 3.375 0 00-2.456 2.456zM16.894 20.567L16.5 21.75l-.394-1.183a2.25 2.25 0 00-1.423-1.423L13.5 18.75l1.183-.394a2.25 2.25 0 001.423-1.423l.394-1.183.394 1.183a2.25 2.25 0 001.423 1.423l1.183.394-1.183.394a2.25 2.25 0 00-1.423 1.423z" />
        </svg>
    );
}

