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

// 전체화면 시 자동 가로 회전 훅 (숏츠가 아닐 때만)
function useFullscreenOrientation(isShorts) {
    useEffect(() => {
        // 숏츠는 세로 유지
        if (isShorts) return;

        const handleFullscreenChange = async () => {
            const isFullscreen = !!document.fullscreenElement;

            if (isFullscreen) {
                // 전체화면 진입 시 가로 모드로 전환 시도
                try {
                    if (screen.orientation && screen.orientation.lock) {
                        await screen.orientation.lock('landscape');
                    }
                } catch (e) {
                    // 지원하지 않는 브라우저이거나 권한이 없는 경우 무시
                }
            } else {
                // 전체화면 종료 시 세로 모드로 복귀
                try {
                    if (screen.orientation && screen.orientation.unlock) {
                        screen.orientation.unlock();
                    }
                } catch (e) {
                    // 무시
                }
            }
        };

        document.addEventListener('fullscreenchange', handleFullscreenChange);
        document.addEventListener('webkitfullscreenchange', handleFullscreenChange);

        return () => {
            document.removeEventListener('fullscreenchange', handleFullscreenChange);
            document.removeEventListener('webkitfullscreenchange', handleFullscreenChange);
        };
    }, [isShorts]);
}

// 카테고리 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 YoutubeSection({ schedule }) {
    const videoId = extractYoutubeVideoId(schedule.source_url);
    const isShorts = schedule.source_url?.includes('/shorts/');

    // 전체화면 시 가로 회전 (숏츠 제외)
    useFullscreenOrientation(isShorts);
    const members = schedule.members || [];
    const isFullGroup = members.length === 5;

    if (!videoId) return null;

    return (
        <div className="space-y-4">
            {/* 영상 임베드 */}
            <motion.div
                initial={{ opacity: 0, scale: 0.98 }}
                animate={{ opacity: 1, scale: 1 }}
                transition={{ delay: 0.1 }}
            >
                <div
                    className={`relative bg-gray-900 rounded-xl overflow-hidden shadow-lg ${
                        isShorts ? 'aspect-[9/16] max-w-[280px] mx-auto' : 'aspect-video'
                    }`}
                >
                    <iframe
                        src={`https://www.youtube.com/embed/${videoId}?rel=0`}
                        title={schedule.title}
                        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; fullscreen; web-share"
                        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 }}
                className="bg-white rounded-xl p-4 shadow-sm"
            >
                {/* 제목 */}
                <h1 className="font-bold text-gray-900 text-base leading-relaxed mb-3">
                    {decodeHtmlEntities(schedule.title)}
                </h1>

                {/* 메타 정보 */}
                <div className="flex flex-wrap items-center gap-3 text-xs text-gray-500 mb-3">
                    <div className="flex items-center gap-1">
                        <Calendar size={12} />
                        <span>{formatFullDate(schedule.date)}</span>
                    </div>
                    {schedule.time && (
                        <div className="flex items-center gap-1">
                            <Clock size={12} />
                            <span>{formatTime(schedule.time)}</span>
                        </div>
                    )}
                    {schedule.source_name && (
                        <div className="flex items-center gap-1">
                            <Link2 size={12} />
                            <span>{schedule.source_name}</span>
                        </div>
                    )}
                </div>

                {/* 멤버 목록 */}
                {members.length > 0 && (
                    <div className="flex flex-wrap gap-1.5 mb-4">
                        {isFullGroup ? (
                            <span className="px-2.5 py-1 bg-primary/10 text-primary text-xs font-medium rounded-full">
                                프로미스나인
                            </span>
                        ) : (
                            members.map((member) => (
                                <span
                                    key={member.id}
                                    className="px-2.5 py-1 bg-primary/10 text-primary text-xs font-medium rounded-full"
                                >
                                    {member.name}
                                </span>
                            ))
                        )}
                    </div>
                )}

                {/* 유튜브에서 보기 버튼 */}
                <a
                    href={schedule.source_url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex items-center justify-center gap-2 w-full py-3 bg-red-500 active:bg-red-600 text-white rounded-xl font-medium transition-colors"
                >
                    <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>
            </motion.div>
        </div>
    );
}

// 기본 섹션 컴포넌트 (다른 카테고리용 - 임시)
function DefaultSection({ schedule }) {
    return (
        <div className="bg-white rounded-xl p-4 shadow-sm">
            <h1 className="font-bold text-gray-900 text-base mb-3">
                {decodeHtmlEntities(schedule.title)}
            </h1>
            <div className="flex items-center gap-3 text-xs text-gray-500">
                <div className="flex items-center gap-1">
                    <Calendar size={12} />
                    <span>{formatFullDate(schedule.date)}</span>
                </div>
                {schedule.time && (
                    <div className="flex items-center gap-1">
                        <Clock size={12} />
                        <span>{formatTime(schedule.time)}</span>
                    </div>
                )}
            </div>
            {schedule.description && (
                <p className="mt-3 text-sm text-gray-600 whitespace-pre-wrap">
                    {decodeHtmlEntities(schedule.description)}
                </p>
            )}
        </div>
    );
}

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

    // 모바일 레이아웃 활성화
    useEffect(() => {
        document.documentElement.classList.add('mobile-layout');
        return () => {
            document.documentElement.classList.remove('mobile-layout');
        };
    }, []);

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

    if (isLoading) {
        return (
            <div className="mobile-layout-container bg-gray-50">
                <div className="mobile-content flex items-center justify-center">
                    <div className="w-8 h-8 border-2 border-primary border-t-transparent rounded-full animate-spin" />
                </div>
            </div>
        );
    }

    if (error || !schedule) {
        return (
            <div className="mobile-layout-container bg-gradient-to-br from-gray-50 to-gray-100">
                <div className="mobile-content flex items-center justify-center px-6">
                    <div className="text-center">
                    {/* 아이콘 */}
                    <motion.div
                        initial={{ opacity: 0, scale: 0.5 }}
                        animate={{ opacity: 1, scale: 1 }}
                        transition={{ duration: 0.5, type: "spring", stiffness: 100 }}
                        className="mb-6"
                    >
                        <div className="w-24 h-24 mx-auto bg-gradient-to-br from-primary/10 to-primary/5 rounded-2xl flex items-center justify-center">
                            <Calendar size={48} className="text-primary/40" />
                        </div>
                    </motion.div>

                    {/* 메시지 */}
                    <motion.div
                        initial={{ opacity: 0, y: 20 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ delay: 0.2, duration: 0.5 }}
                        className="mb-6"
                    >
                        <h2 className="text-xl font-bold text-gray-800 mb-2">
                            일정을 찾을 수 없습니다
                        </h2>
                        <p className="text-gray-500 text-sm leading-relaxed">
                            요청하신 일정이 존재하지 않거나
                            <br />
                            삭제되었을 수 있습니다.
                        </p>
                    </motion.div>

                    {/* 장식 요소 */}
                    <motion.div
                        initial={{ opacity: 0 }}
                        animate={{ opacity: 1 }}
                        transition={{ delay: 0.4, duration: 0.5 }}
                        className="flex justify-center gap-1.5 mb-8"
                    >
                        {[...Array(5)].map((_, i) => (
                            <motion.div
                                key={i}
                                className="w-1.5 h-1.5 rounded-full bg-primary"
                                animate={{
                                    y: [0, -6, 0],
                                    opacity: [0.3, 1, 0.3],
                                }}
                                transition={{
                                    duration: 1.2,
                                    repeat: Infinity,
                                    delay: i * 0.15,
                                    ease: "easeInOut",
                                }}
                            />
                        ))}
                    </motion.div>

                    {/* 버튼들 */}
                    <motion.div
                        initial={{ opacity: 0, y: 20 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ delay: 0.5, duration: 0.5 }}
                        className="flex flex-col gap-3"
                    >
                        <button
                            onClick={() => window.history.back()}
                            className="flex items-center justify-center gap-2 w-full px-6 py-3 border-2 border-primary text-primary rounded-full font-medium active:bg-primary active:text-white transition-colors"
                        >
                            <ChevronLeft size={18} />
                            이전 페이지
                        </button>
                        <Link
                            to="/schedule"
                            className="flex items-center justify-center gap-2 w-full px-6 py-3 bg-gradient-to-r from-primary to-primary-dark text-white rounded-full font-medium active:opacity-90 transition-opacity"
                        >
                            <Calendar size={18} />
                            일정 목록
                        </Link>
                    </motion.div>
                    </div>
                </div>
            </div>
        );
    }

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

    return (
        <div className="mobile-layout-container bg-gray-50">
            {/* 헤더 */}
            <div className="flex-shrink-0 bg-white border-b border-gray-100">
                <div className="flex items-center h-14 px-4">
                    <button
                        onClick={() => window.history.back()}
                        className="p-2 -ml-2 rounded-lg active:bg-gray-100"
                    >
                        <ChevronLeft size={24} />
                    </button>
                    <div className="flex-1 text-center">
                        <span
                            className="text-sm font-medium"
                            style={{ color: schedule.category_color }}
                        >
                            {schedule.category_name}
                        </span>
                    </div>
                    <div className="w-10" />
                </div>
            </div>

            {/* 메인 컨텐츠 */}
            <div className="mobile-content p-4">
                {renderCategorySection()}
            </div>
        </div>
    );
}

export default MobileScheduleDetail;
