'use client';
import { useLocale, useTranslations } from 'next-intl';
import { useState } from 'react';

import {
    Video,
    VideoOff,
    List,
    Clock,
    Calendar,
    FileDown,
    PlayCircle,
    ChevronRight,
    ChevronLeft
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { ScrollArea } from '@/components/ui/scroll-area';

// Types
type VideoType = 'youtube' | 'vimeo' | null;

interface VideoInfo {
    type: VideoType;
    id: string;
    embedUrl: string;
}

export function ProgramSessions({ sessions }: { sessions: any[] }) {
    const t = useTranslations('programs');

    const locale = useLocale();
    const isRTL = locale === "ar";
    const [selectedSession, setSelectedSession] = useState(sessions[0]);

    // Parse video URL to determine type and extract ID
    const parseVideoUrl = (url: string): VideoInfo => {
        if (!url) return { type: null, id: '', embedUrl: '' };

        // YouTube patterns
        const youtubeRegex = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/;
        const youtubeMatch = url.match(youtubeRegex);
        if (youtubeMatch) {
            const videoId = youtubeMatch[1];
            return {
                type: 'youtube',
                id: videoId,
                embedUrl: `https://www.youtube.com/embed/${videoId}`
            };
        }

        // Vimeo patterns
        const vimeoRegex = /(?:vimeo\.com\/)(?:.*\/)?(\d+)/;
        const vimeoMatch = url.match(vimeoRegex);
        if (vimeoMatch) {
            const videoId = vimeoMatch[1];
            return {
                type: 'vimeo',
                id: videoId,
                embedUrl: `https://player.vimeo.com/video/${videoId}`
            };
        }

        return { type: null, id: '', embedUrl: '' };
    };

    const videoSessions = sessions.filter(s => s.join_url);
    const currentVideoInfo = sessions ? parseVideoUrl(selectedSession?.join_url) : null;
    const currentIndex = sessions ? videoSessions.findIndex(s => s.id === selectedSession?.id) : -1;

    const goToNextVideo = () => {
        if (!sessions || currentIndex >= videoSessions.length - 1) return;
        setSelectedSession(videoSessions[currentIndex + 1]);
    };

    const goToPreviousVideo = () => {
        if (!selectedSession || currentIndex <= 0) return;
        setSelectedSession(videoSessions[currentIndex - 1]);
    };
    return (
        <div className='min-h-screen'>
            <div>
                {sessions.length === 0 ? (
                    <Card>
                        <CardContent className="py-16 text-center">
                            <VideoOff className="size-14 text-gray-300 mx-auto mb-4" />
                            <h3 className="text-xl font-semibold text-gray-900 mb-2">{t('noSessions')}</h3>
                            <p className="text-gray-600">{t('noSessionsDescription')}</p>
                        </CardContent>
                    </Card>
                ) : videoSessions.length === 0 ? (
                    <Card>
                        <CardContent className="py-16 text-center">
                            <VideoOff className="size-14 text-gray-300 mx-auto mb-4" />
                            <h3 className="text-xl font-semibold text-gray-900 mb-2">{t('noVideos')}</h3>
                            <p className="text-gray-600">{t('noVideosDescription')}</p>
                        </CardContent>
                    </Card>
                ) : (
                    <div className={`grid md:grid-cols-[350px_1fr] gap-2`}>
                        {/* Video List Sidebar */}
                        <Card className="h-fit sticky top-6">
                            <CardHeader>
                                <CardTitle className='flex items-center gap-2'>
                                    <List className="size-4 text-purple-700" />
                                    {t('videoList')}
                                </CardTitle>
                            </CardHeader>
                            <CardContent className="p-4">
                                <ScrollArea className="h-[calc(100vh-300px)]">
                                    <div className="space-y-3">
                                        {videoSessions.map((session, index) => {
                                            const isSelected = selectedSession?.id === session.id;
                                            const videoInfo = parseVideoUrl(session.join_url);

                                            return (
                                                <div
                                                    key={session.id}
                                                    onClick={() => setSelectedSession(session)}
                                                    className={`p-4 rounded-lg cursor-pointer transition-all border-2 ${isSelected
                                                        ? `bg-purple-50 border-purple-700 border-l-4 rtl:border-r-4`
                                                        : 'bg-transparent border-transparent hover:bg-gray-50 hover:border-gray-200'
                                                        }`}
                                                >
                                                    <div className={`flex gap-4 items-start`}>
                                                        <div className={`w-10 h-10 rounded-lg flex items-center justify-center text-sm font-bold flex-shrink-0 ${isSelected
                                                            ? 'bg-gradient-to-br from-purple-700 to-purple-500 text-white'
                                                            : 'bg-gray-200 text-gray-600'
                                                            }`}>
                                                            {index + 1}
                                                        </div>
                                                        <div className={`flex-1 min-w-0`}>
                                                            <h3 className="font-semibold text-gray-900 mb-1 line-clamp-2">
                                                                {session.topic}
                                                            </h3>
                                                            <div className={`flex items-center gap-2 text-xs text-gray-600`}>
                                                                <span className={videoInfo.type === 'youtube' ? 'text-red-600' : 'text-blue-500'}>
                                                                    {videoInfo.type === 'youtube' ? t('youtube') : t('vimeo')}
                                                                </span>
                                                                <span>•</span>
                                                                <span>{session.duration} {t('min')}</span>
                                                            </div>
                                                        </div>
                                                        {isSelected && (
                                                            <PlayCircle className="h-5 w-5 text-purple-700 flex-shrink-0 mt-1" />
                                                        )}
                                                    </div>
                                                </div>
                                            );
                                        })}
                                    </div>
                                </ScrollArea>
                            </CardContent>
                        </Card>

                        {/* Video Player Section */}
                        <Card>
                            <CardContent className="p-8">
                                {selectedSession && currentVideoInfo?.type ? (
                                    <>
                                        {/* Video Title and Info */}
                                        <div className={`mb-6`}>
                                            <h2 className="text-2xl font-bold text-gray-900 mb-4">
                                                {selectedSession.topic}
                                            </h2>
                                            <div className={`flex flex-wrap gap-6 text-gray-600`}>
                                                <div className={`flex items-center gap-2`}>
                                                    <Clock className="h-5 w-5 text-purple-700" />
                                                    <span>{selectedSession.duration} {t('minutes')}</span>
                                                </div>
                                                <div className={`flex items-center gap-2`}>
                                                    <Calendar className="h-5 w-5 text-purple-700" />
                                                    <span>{new Date(selectedSession.date).toLocaleDateString(isRTL ? 'ar-SA' : 'en-US')}</span>
                                                </div>
                                                <div className={`flex items-center gap-2`}>
                                                    <span className={currentVideoInfo.type === 'youtube' ? 'text-red-600' : 'text-blue-500'}>
                                                        {currentVideoInfo.type === 'youtube' ? t('youtube') : t('vimeo')}
                                                    </span>
                                                </div>
                                            </div>
                                        </div>

                                        {/* Video Player */}
                                        <div className="relative w-full pb-[56.25%] mb-6 rounded-lg overflow-hidden bg-black">
                                            <iframe
                                                src={currentVideoInfo.embedUrl}
                                                className="absolute top-0 left-0 w-full h-full border-0"
                                                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                                                allowFullScreen
                                                title={selectedSession.topic}
                                            />
                                        </div>

                                        {/* Navigation Buttons */}
                                        <div className={`flex items-center justify-between pt-6 border-t-2`}>
                                            <Button
                                                onClick={goToPreviousVideo}
                                                disabled={currentIndex === 0}
                                                variant={currentIndex === 0 ? 'ghost' : 'default'}
                                                className={`${currentIndex === 0 ? '' : 'bg-purple-700 hover:bg-purple-800'}`}
                                            >
                                                <ChevronLeft className="size-4 ml-2 rtl:mr-2" />
                                                {t('previous')}
                                            </Button>

                                            <div className="text-sm text-gray-600 font-medium">
                                                {t('video')} {currentIndex + 1} {t('of')} {videoSessions.length}
                                            </div>

                                            <Button
                                                onClick={goToNextVideo}
                                                disabled={currentIndex === videoSessions.length - 1}
                                                variant={currentIndex === videoSessions.length - 1 ? 'ghost' : 'default'}
                                                className={`${currentIndex === videoSessions.length - 1 ? '' : 'bg-purple-700 hover:bg-purple-800'}`}
                                            >
                                                {t('next')}
                                                <ChevronRight className="size-4 ml-2 rtl:mr-2" />
                                            </Button>
                                        </div>

                                        {/* Download Material Button */}
                                        {selectedSession.file && (
                                            <div className="mt-6 pt-6 border-t-2">
                                                <Button
                                                    variant="outline"
                                                    className={`border-2 border-purple-700 text-purple-700 hover:bg-purple-700 hover:text-white`}
                                                    asChild
                                                >
                                                    <a
                                                        href={`https://tr.ivorytraining.com/${selectedSession.file}`}
                                                        target="_blank"
                                                        rel="noopener noreferrer"
                                                    >
                                                        <FileDown className="size-4 ml-2 rtl:mr-2" />
                                                        {t('downloadMaterial')}
                                                    </a>
                                                </Button>
                                            </div>
                                        )}
                                    </>
                                ) : (
                                    <div className="py-16 text-center text-gray-600">
                                        <Video className="h-12 w-12 text-gray-300 mx-auto mb-4" />
                                        <p>{t('selectVideo')}</p>
                                    </div>
                                )}
                            </CardContent>
                        </Card>
                    </div>
                )}
            </div>
        </div>
    );
}