import { useParams, Link } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { motion } from 'framer-motion';
import { Clock, Calendar, ExternalLink, ChevronRight, Link2 } from 'lucide-react';
import { getSchedule } from '../../../api/public/schedules';

// 카테고리 ID 상수
const CATEGORY_ID = {
    YOUTUBE: 2,
    X: 3,
    ALBUM: 4,
    FANSIGN: 5,
    CONCERT: 6,
    TICKET: 7,
};

// HTML 엔티티 디코딩 함수
const decodeHtmlEntities = (text) => {
    if (!text) return '';
    const textarea = document.createElement('textarea');
    textarea.innerHTML = text;
    return textarea.value;
};

// 유튜브 비디오 ID 추출
const extractYoutubeVideoId = (url) => {
    if (!url) return null;
    const shortMatch = url.match(/youtu\.be\/([a-zA-Z0-9_-]{11})/);
    if (shortMatch) return shortMatch[1];
    const watchMatch = url.match(/youtube\.com\/watch\?v=([a-zA-Z0-9_-]{11})/);
    if (watchMatch) return watchMatch[1];
    const shortsMatch = url.match(/youtube\.com\/shorts\/([a-zA-Z0-9_-]{11})/);
    if (shortsMatch) return shortsMatch[1];
    return null;
};

// 날짜 포맷팅
const formatFullDate = (dateStr) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    const dayNames = ['일', '월', '화', '수', '목', '금', '토'];
    return `${date.getFullYear()}. ${date.getMonth() + 1}. ${date.getDate()}. (${dayNames[date.getDay()]})`;
};

// 시간 포맷팅
const formatTime = (timeStr) => {
    if (!timeStr) return null;
    return timeStr.slice(0, 5);
};

// 영상 정보 컴포넌트 (공통)
function VideoInfo({ schedule, isShorts }) {
    return (
        <div className={`bg-gradient-to-br from-gray-50 to-gray-100/50 rounded-2xl p-6 ${isShorts ? 'flex-1' : ''}`}>
            {/* 제목 */}
            <h1 className={`font-bold text-gray-900 mb-4 leading-relaxed ${isShorts ? 'text-lg' : 'text-xl'}`}>
                {decodeHtmlEntities(schedule.title)}
            </h1>

            {/* 메타 정보 */}
            <div className={`flex flex-wrap items-center gap-4 text-sm ${isShorts ? 'gap-3' : ''}`}>
                {/* 날짜 */}
                <div className="flex items-center gap-1.5 text-gray-500">
                    <Calendar size={14} />
                    <span>{formatFullDate(schedule.date)}</span>
                </div>

                {/* 시간 */}
                {schedule.time && (
                    <>
                        <div className="w-px h-4 bg-gray-300" />
                        <div className="flex items-center gap-1.5 text-gray-500">
                            <Clock size={14} />
                            <span>{formatTime(schedule.time)}</span>
                        </div>
                    </>
                )}

                {/* 채널명 */}
                {schedule.source_name && (
                    <>
                        <div className="w-px h-4 bg-gray-300" />
                        <div className="flex items-center gap-2 text-gray-500">
                            <Link2 size={14} className="opacity-60" />
                            <span className="font-medium">{schedule.source_name}</span>
                        </div>
                    </>
                )}
            </div>

            {/* 유튜브에서 보기 버튼 */}
            <div className="mt-6 pt-5 border-t border-gray-200">
                <a
                    href={schedule.source_url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-2 px-5 py-2.5 bg-red-500 hover:bg-red-600 text-white rounded-xl font-medium transition-colors shadow-lg shadow-red-500/20"
                >
                    <svg className="w-5 h-5" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z"/>
                    </svg>
                    YouTube에서 보기
                </a>
            </div>
        </div>
    );
}

// 유튜브 섹션 컴포넌트
function YoutubeSection({ schedule }) {
    const videoId = extractYoutubeVideoId(schedule.source_url);
    const isShorts = schedule.source_url?.includes('/shorts/');

    if (!videoId) return null;

    // 숏츠: 가로 레이아웃 (영상 + 정보)
    if (isShorts) {
        return (
            <div className="flex gap-6 items-start">
                {/* 영상 임베드 */}
                <motion.div
                    initial={{ opacity: 0, scale: 0.98 }}
                    animate={{ opacity: 1, scale: 1 }}
                    transition={{ delay: 0.1 }}
                    className="w-[420px] flex-shrink-0"
                >
                    <div className="relative aspect-[9/16] bg-gray-900 rounded-2xl overflow-hidden shadow-2xl shadow-black/20">
                        <iframe
                            src={`https://www.youtube.com/embed/${videoId}?rel=0`}
                            title={schedule.title}
                            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                            allowFullScreen
                            className="absolute inset-0 w-full h-full"
                        />
                    </div>
                </motion.div>

                {/* 영상 정보 카드 */}
                <motion.div
                    initial={{ opacity: 0, x: 10 }}
                    animate={{ opacity: 1, x: 0 }}
                    transition={{ delay: 0.2 }}
                    className="flex-1"
                >
                    <VideoInfo schedule={schedule} isShorts={true} />
                </motion.div>
            </div>
        );
    }

    // 일반 영상: 세로 레이아웃 (영상 위, 정보 아래)
    return (
        <div className="space-y-6">
            {/* 영상 임베드 */}
            <motion.div
                initial={{ opacity: 0, scale: 0.98 }}
                animate={{ opacity: 1, scale: 1 }}
                transition={{ delay: 0.1 }}
                className="w-full"
            >
                <div className="relative aspect-video bg-gray-900 rounded-2xl overflow-hidden shadow-2xl shadow-black/20">
                    <iframe
                        src={`https://www.youtube.com/embed/${videoId}?rel=0`}
                        title={schedule.title}
                        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                        allowFullScreen
                        className="absolute inset-0 w-full h-full"
                    />
                </div>
            </motion.div>

            {/* 영상 정보 카드 */}
            <motion.div
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.2 }}
            >
                <VideoInfo schedule={schedule} isShorts={false} />
            </motion.div>
        </div>
    );
}

// 기본 섹션 컴포넌트 (다른 카테고리용)
function DefaultSection({ schedule }) {
    return (
        <div className="space-y-6">
            {/* 제목 */}
            <h1 className="text-2xl font-bold text-gray-900 leading-relaxed">
                {decodeHtmlEntities(schedule.title)}
            </h1>

            {/* 메타 정보 */}
            <div className="flex flex-wrap items-center gap-4 text-sm text-gray-500">
                <div className="flex items-center gap-1.5">
                    <Calendar size={16} />
                    <span>{formatFullDate(schedule.date)}</span>
                </div>
                {schedule.time && (
                    <div className="flex items-center gap-1.5">
                        <Clock size={16} />
                        <span>{formatTime(schedule.time)}</span>
                    </div>
                )}
            </div>

            {/* 설명 */}
            {schedule.description && (
                <div className="bg-gray-50 rounded-2xl p-6">
                    <p className="text-gray-700 whitespace-pre-wrap leading-relaxed">
                        {decodeHtmlEntities(schedule.description)}
                    </p>
                </div>
            )}

            {/* 원본 링크 */}
            {schedule.source_url && (
                <a
                    href={schedule.source_url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-2 px-5 py-2.5 bg-gray-900 hover:bg-gray-800 text-white rounded-xl font-medium transition-colors"
                >
                    <ExternalLink size={16} />
                    원본 보기
                </a>
            )}
        </div>
    );
}

function ScheduleDetail() {
    const { id } = useParams();

    const { data: schedule, isLoading, error } = useQuery({
        queryKey: ['schedule', id],
        queryFn: () => getSchedule(id),
    });

    if (isLoading) {
        return (
            <div className="min-h-[calc(100vh-64px)] flex items-center justify-center bg-gray-50">
                <div className="w-10 h-10 border-3 border-primary border-t-transparent rounded-full animate-spin" />
            </div>
        );
    }

    if (error || !schedule) {
        return (
            <div className="min-h-[calc(100vh-64px)] flex flex-col items-center justify-center bg-gray-50">
                <div className="text-center">
                    <div className="text-6xl mb-4">😢</div>
                    <p className="text-gray-500 mb-6">일정을 찾을 수 없습니다</p>
                    <Link
                        to="/schedule"
                        className="px-6 py-3 bg-primary hover:bg-primary-dark text-white rounded-xl font-medium transition-colors"
                    >
                        일정 목록으로
                    </Link>
                </div>
            </div>
        );
    }

    // 카테고리별 섹션 렌더링
    const renderCategorySection = () => {
        switch (schedule.category_id) {
            case CATEGORY_ID.YOUTUBE:
                return <YoutubeSection schedule={schedule} />;
            default:
                return <DefaultSection schedule={schedule} />;
        }
    };

    const isYoutube = schedule.category_id === CATEGORY_ID.YOUTUBE;

    return (
        <div className="min-h-[calc(100vh-64px)] bg-gray-50">
            <div className={`${isYoutube ? 'max-w-5xl' : 'max-w-3xl'} mx-auto px-6 py-8`}>
                {/* 브레드크럼 네비게이션 */}
                <motion.div
                    initial={{ opacity: 0, y: -10 }}
                    animate={{ opacity: 1, y: 0 }}
                    className="flex items-center gap-2 text-sm text-gray-500 mb-8"
                >
                    <Link to="/schedule" className="hover:text-primary transition-colors">
                        일정
                    </Link>
                    <ChevronRight size={14} />
                    <span
                        className="hover:text-primary transition-colors"
                        style={{ color: schedule.category_color }}
                    >
                        {schedule.category_name}
                    </span>
                    <ChevronRight size={14} />
                    <span className="text-gray-700 font-medium truncate max-w-md">
                        {decodeHtmlEntities(schedule.title)}
                    </span>
                </motion.div>

                {/* 메인 컨텐츠 */}
                <motion.div
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.05 }}
                    className={`${isYoutube ? '' : 'bg-white rounded-3xl shadow-sm p-8'}`}
                >
                    {renderCategorySection()}
                </motion.div>
            </div>
        </div>
    );
}

export default ScheduleDetail;
