import { Head, router } from '@inertiajs/react';
import { useState, useEffect, useRef, useMemo } from 'react';
import UserLayout from '@/components/Layouts/UserLayout';
import { Show } from '@/types';
import Artplayer from 'artplayer';
import Hls from 'hls.js';

interface LivePlayerProps {
    show: Show;
    streamServerUrl: string;
    slugLive?: string;
}

export default function LivePlayer({ show, streamServerUrl, slugLive }: LivePlayerProps) {
    const containerRef = useRef<HTMLDivElement>(null);
    const wrapperRef = useRef<HTMLDivElement | null>(null);
    const playerRef = useRef<any>(null);
    const hlsRef = useRef<any>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const isUnmountingRef = useRef(false);
    const initKeyRef = useRef<string | null>(null);
    
    const playerKey = useMemo(() => {
        return `${slugLive || show.showId}-${streamServerUrl}`;
    }, [slugLive, show.showId, streamServerUrl]);

    useEffect(() => {
        if (isUnmountingRef.current || initKeyRef.current === playerKey) {
            return;
        }
        
        initKeyRef.current = playerKey;
        
        if (!document.getElementById('artplayer-css')) {
            const link = document.createElement('link');
            link.id = 'artplayer-css';
            link.rel = 'stylesheet';
            link.href = 'https://cdn.jsdelivr.net/npm/artplayer/dist/artplayer.css';
            document.head.appendChild(link);
        }

        const initPlayer = async () => {
            if (isUnmountingRef.current || initKeyRef.current !== playerKey) {
                return;
            }
            
            if (!containerRef.current) {
                setTimeout(() => {
                    if (containerRef.current && !isUnmountingRef.current) {
                        initPlayer();
                    } else {
                        setError('Container tidak tersedia. Silakan refresh halaman.');
                        setLoading(false);
                    }
                }, 200);
                return;
            }
            
            if (!show) {
                setError('Show tidak tersedia.');
                setLoading(false);
                return;
            }

            const identifier = slugLive || show.showId;
            if (!identifier) {
                setError('Show identifier tidak tersedia.');
                setLoading(false);
                return;
            }
            
            const endpoint = `${streamServerUrl}/api/stream/v3/playback?slug=${encodeURIComponent(String(identifier))}`;
            const container = containerRef.current;
            
            if (!container || !container.parentNode) {
                setError('Container tidak tersedia.');
                setLoading(false);
                return;
            }
            
            const clearContainer = () => {
                try {
                    if (!container || !container.parentNode) {
                        return;
                    }
                    
                    if (playerRef.current?.destroy) {
                        try {
                            playerRef.current.destroy();
                        } catch (err) {
                            // Ignore cleanup errors
                        }
                    }
                    
                    wrapperRef.current = null;
                    
                    while (container.firstChild) {
                        const child = container.firstChild;
                        if (child?.parentNode === container) {
                            try {
                                container.removeChild(child);
                            } catch (err) {
                                break;
                            }
                        } else {
                            break;
                        }
                    }
                } catch (err) {
                    // Ignore cleanup errors
                }
            };
            
            clearContainer();
            
            const wrapper = document.createElement('div');
            wrapper.id = `artplayer-wrapper-${Date.now()}`;
            wrapper.style.width = '100%';
            wrapper.style.height = '100%';
            wrapperRef.current = wrapper;
            
            if (!container.parentNode || isUnmountingRef.current) {
                setError('Container tidak tersedia.');
                setLoading(false);
                return;
            }
            
            container.appendChild(wrapper);
            
            const playerConfig: any = {
                container: wrapper,
                url: endpoint,
                title: show.title || 'Live Streaming',
                poster: show.banner_link || '',
                volume: 0.7,
                autoplay: true,
                isLive: true,
                muted: false,
                theme: '#d4af37',
                whitelist: ['*'],
                setting: true,
                quality: [],
                playbackRate: false,
                fullscreen: true,
                fullscreenWeb: true,
                pip: true,
                mutex: true,
                backdrop: true,
                playsInline: true,
                autoSize: false,
                autoMini: false,
                screenshot: false,
                hotkey: true,
                lock: true,
                fastForward: false,
                autoPlayback: true,
                airplay: true,
            };

            if (Hls.isSupported()) {
                playerConfig.customType = {
                    m3u8: (video: HTMLVideoElement, url: string, art: any) => {
                        const playerArt = art;
                        
                        const hls = new Hls({
                            enableWorker: true,
                            lowLatencyMode: true,
                            backBufferLength: 90,
                            debug: false,
                            xhrSetup: (xhr: XMLHttpRequest) => {
                                xhr.withCredentials = false;
                                
                                xhr.addEventListener('load', () => {
                                    if (xhr.status === 500) {
                                        setError('Streaming sedang offline dan segera disiapkan. Silakan coba lagi beberapa saat.');
                                        setLoading(false);
                                        hls?.destroy();
                                    } else if (xhr.status >= 400 && xhr.status !== 500) {
                                        setError('Gagal memuat stream. Silakan refresh halaman.');
                                        setLoading(false);
                                    }
                                });
                            },
                        });

                        hls.on(Hls.Events.ERROR, (event: any, data: any) => {
                            const isServerError = data.response?.code === 500;
                            
                            if (isServerError) {
                                setError('Streaming sedang offline dan segera disiapkan. Silakan coba lagi beberapa saat.');
                                setLoading(false);
                                hls.destroy();
                                return;
                            }
                            
                            if (data.fatal) {
                                switch (data.type) {
                                    case Hls.ErrorTypes.NETWORK_ERROR:
                                        if (isServerError) {
                                            setError('Streaming sedang offline dan segera disiapkan. Silakan coba lagi beberapa saat.');
                                            setLoading(false);
                                            hls.destroy();
                                        } else {
                                            hls.startLoad();
                                        }
                                        break;
                                    case Hls.ErrorTypes.MEDIA_ERROR:
                                        hls.recoverMediaError();
                                        break;
                                    default:
                                        setError('Gagal memuat stream. Silakan refresh halaman.');
                                        setLoading(false);
                                        hls.destroy();
                                        break;
                                }
                            }
                        });

                        hlsRef.current = hls;
                        
                        hls.on(Hls.Events.MANIFEST_PARSED, () => {
                            const levels = hls.levels;
                            if (levels && levels.length > 0) {
                                const qualityOptions: any[] = [{
                                    default: hls.currentLevel === -1,
                                    html: 'Auto',
                                    url: endpoint,
                                    level: -1,
                                }];

                                levels.forEach((level: any, index: number) => {
                                    let label = 'Unknown';
                                    if (level.height) {
                                        const resolution = `${level.width}x${level.height}`;
                                        const bitrate = level.bitrate ? ` (${Math.round(level.bitrate / 1000)}k)` : '';
                                        label = resolution + bitrate;
                                    } else if (level.bitrate) {
                                        label = `${Math.round(level.bitrate / 1000)}k`;
                                    } else {
                                        label = `Level ${index}`;
                                    }

                                    qualityOptions.push({
                                        default: index === hls.currentLevel,
                                        html: label,
                                        url: endpoint,
                                        level: index,
                                    });
                                });

                                if (qualityOptions.length > 0) {
                                    (playerArt as any).quality = qualityOptions;
                                }

                                playerArt.on('video:quality', (quality: any) => {
                                    const selectedLevel = quality.level;
                                    if (selectedLevel !== undefined && hls) {
                                        try {
                                            if (selectedLevel === -1) {
                                                hls.currentLevel = -1;
                                                hls.nextLevel = -1;
                                            } else if (selectedLevel >= 0 && selectedLevel < levels.length) {
                                                hls.currentLevel = selectedLevel;
                                                hls.nextLevel = selectedLevel;
                                                hls.loadLevel = selectedLevel;
                                            }
                                        } catch (err) {
                                            // Ignore quality change errors
                                        }
                                    }
                                });
                            }
                        });

                        playerArt.on('destroy', () => {
                            if (hls) {
                                hls.destroy();
                                hlsRef.current = null;
                            }
                        });
                        
                        try {
                            hls.loadSource(url);
                            hls.attachMedia(video);
                        } catch (err) {
                            setError('Gagal memuat stream. Silakan refresh halaman.');
                            setLoading(false);
                        }
                    },
                };
                playerConfig.type = 'm3u8';
            } else if ((document.createElement('video') as HTMLVideoElement).canPlayType('application/vnd.apple.mpegurl')) {
                playerConfig.type = 'm3u8';
            } else {
                setError('Browser tidak mendukung HLS streaming');
                setLoading(false);
                return;
            }

            try {
                const artInstance = new Artplayer(playerConfig);
                playerRef.current = artInstance;
                setLoading(false);
            } catch (err) {
                setError('Gagal membuat player. Silakan refresh halaman.');
                setLoading(false);
            }
        };

        initPlayer();

        return () => {
            if (initKeyRef.current !== playerKey) {
                return;
            }
            
            isUnmountingRef.current = true;
            
            const cleanup = () => {
                if (hlsRef.current?.destroy) {
                    try {
                        hlsRef.current.destroy();
                    } catch (err) {
                        // Ignore cleanup errors
                    } finally {
                        hlsRef.current = null;
                    }
                }
                
                if (playerRef.current?.destroy) {
                    try {
                        playerRef.current.destroy();
                    } catch (err) {
                        // Ignore cleanup errors
                    } finally {
                        playerRef.current = null;
                    }
                }
                
                wrapperRef.current = null;
                initKeyRef.current = null;
            };
            
            requestAnimationFrame(() => {
                requestAnimationFrame(() => {
                    cleanup();
                });
            });
        };
    }, [playerKey]);

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

    return (
        <UserLayout title={`Live: ${show.title}`}>
            <Head title={`Live: ${show.title}`} />
            <div className="space-y-6">
                <div className="flex items-center justify-between">
                    <div>
                        <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Live Streaming</h1>
                        <p className="mt-1 text-sm text-gray-500 dark:text-gray-400">{show.title}</p>
                    </div>
                    <button
                        onClick={() => router.visit('/dashboard')}
                        className="rounded-md bg-gray-200 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-300 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600"
                    >
                        Kembali
                    </button>
                </div>

                <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                    <div className="lg:col-span-2">
                        <div className="bg-white dark:bg-gray-800 rounded-lg overflow-hidden shadow-lg">
                            <div className="w-full aspect-video bg-gray-900 relative" style={{ minHeight: '400px' }}>
                                <div 
                                    key={`player-container-${slugLive || show.showId}`}
                                    ref={containerRef} 
                                    className="w-full h-full"
                                />
                                
                                {loading && (
                                    <div className="absolute inset-0 flex items-center justify-center bg-gray-900 z-50 pointer-events-none">
                                        <div className="text-center">
                                            <div className="w-12 h-12 border-4 border-[#d4af37] border-t-transparent rounded-full animate-spin mx-auto mb-3"></div>
                                            <p className="text-white text-sm">Memuat stream...</p>
                                        </div>
                                    </div>
                                )}
                                
                                {error && (
                                    <div className="absolute inset-0 flex items-center justify-center bg-gray-900 z-50">
                                        <div className="text-center p-6 max-w-md">
                                            {error.includes('offline') ? (
                                                <>
                                                    <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-yellow-500/20 flex items-center justify-center">
                                                        <svg className="w-8 h-8 text-yellow-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                                                        </svg>
                                                    </div>
                                                    <p className="text-yellow-400 font-semibold mb-2 text-lg">Streaming Sedang Offline</p>
                                                    <p className="text-gray-300 text-sm mb-4">{error}</p>
                                                    <button
                                                        onClick={() => window.location.reload()}
                                                        className="px-4 py-2 bg-[#d4af37] text-white rounded-md hover:bg-[#c4a027] transition-colors text-sm font-medium"
                                                    >
                                                        Coba Lagi
                                                    </button>
                                                </>
                                            ) : (
                                                <>
                                                    <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-red-500/20 flex items-center justify-center">
                                                        <svg className="w-8 h-8 text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                                        </svg>
                                                    </div>
                                                    <p className="text-red-400 font-semibold mb-2 text-lg">Gagal Memuat Stream</p>
                                                    <p className="text-gray-300 text-sm mb-4">{error}</p>
                                                    <button
                                                        onClick={() => router.reload()}
                                                        className="px-4 py-2 bg-[#d4af37] text-white rounded-md hover:bg-[#c4a027] transition-colors text-sm font-medium"
                                                    >
                                                        Refresh Halaman
                                                    </button>
                                                </>
                                            )}
                                        </div>
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>

                    <div className="space-y-4">
                        <div className="bg-white dark:bg-gray-800 rounded-lg p-4 shadow-lg">
                            <h2 className="text-lg font-bold text-gray-900 dark:text-white mb-3">{show.title}</h2>
                            {show.showId && (
                                <div className="mb-3">
                                    <p className="text-gray-600 dark:text-gray-400 text-xs mb-1">Show ID</p>
                                    <p className="text-gray-900 dark:text-white font-mono text-sm">{show.showId}</p>
                                </div>
                            )}
                            {show.start_time && (
                                <div className="mb-3">
                                    <p className="text-gray-600 dark:text-gray-400 text-xs mb-1">Waktu Mulai</p>
                                    <p className="text-gray-900 dark:text-white text-sm">{formatDate(show.start_time)}</p>
                                </div>
                            )}
                            {show.type && (
                                <div className="mb-3">
                                    <p className="text-gray-600 dark:text-gray-400 text-xs mb-1">Tipe Show</p>
                                    <span className="inline-block px-2 py-1 bg-[#d4af37]/20 text-[#d4af37] rounded-md text-xs font-semibold">
                                        {show.type}
                                    </span>
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </div>
        </UserLayout>
    );
}
