import { useEffect, useRef, useState } from 'react';
import { useQuery, keepPreviousData } from '@tanstack/react-query';
import { motion, AnimatePresence } from 'framer-motion';
import { ExternalLink, ChevronDown, Check, MapPin, Navigation } from 'lucide-react';
import { getSchedule } from '../../../../api/public/schedules';
import { decodeHtmlEntities } from './utils';
import KakaoMap from './KakaoMap';

// 콘서트 섹션 컴포넌트
function ConcertSection({ schedule }) {
    // 현재 선택된 회차 ID (내부 state로 관리 - URL 변경 없음)
    const [selectedDateId, setSelectedDateId] = useState(schedule.id);
    const [isDropdownOpen, setIsDropdownOpen] = useState(false);
    const dropdownRef = useRef(null);
    const dropdownListRef = useRef(null);

    // 표시할 데이터 state (변경된 부분만 업데이트)
    const [displayData, setDisplayData] = useState({
        posterUrl: schedule.images?.[0] || null,
        title: schedule.title,
        date: schedule.date,
        time: schedule.time,
        locationName: schedule.location_name,
        locationAddress: schedule.location_address,
        locationLat: schedule.location_lat,
        locationLng: schedule.location_lng,
        description: schedule.description,
        sourceUrl: schedule.source?.url,
    });

    // 선택된 회차 데이터 조회
    const { data: selectedSchedule } = useQuery({
        queryKey: ['schedule', selectedDateId],
        queryFn: () => getSchedule(selectedDateId),
        placeholderData: keepPreviousData,
        enabled: selectedDateId !== schedule.id,
    });

    // 데이터 비교 후 변경된 부분만 업데이트
    useEffect(() => {
        const newData = selectedDateId === schedule.id ? schedule : selectedSchedule;
        if (!newData) return;

        setDisplayData(prev => {
            const updates = {};
            const newPosterUrl = newData.images?.[0] || null;

            if (prev.posterUrl !== newPosterUrl) updates.posterUrl = newPosterUrl;
            if (prev.title !== newData.title) updates.title = newData.title;
            if (prev.date !== newData.date) updates.date = newData.date;
            if (prev.time !== newData.time) updates.time = newData.time;
            if (prev.locationName !== newData.location_name) updates.locationName = newData.location_name;
            if (prev.locationAddress !== newData.location_address) updates.locationAddress = newData.location_address;
            if (prev.locationLat !== newData.location_lat) updates.locationLat = newData.location_lat;
            if (prev.locationLng !== newData.location_lng) updates.locationLng = newData.location_lng;
            if (prev.description !== newData.description) updates.description = newData.description;
            if (prev.sourceUrl !== newData.source?.url) updates.sourceUrl = newData.source?.url;

            if (Object.keys(updates).length > 0) {
                return { ...prev, ...updates };
            }
            return prev;
        });
    }, [selectedDateId, schedule, selectedSchedule]);

    // 드롭다운 외부 클릭 감지
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
                setIsDropdownOpen(false);
            }
        };
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, []);

    // 드롭다운 열릴 때 선택된 항목으로 자동 스크롤
    useEffect(() => {
        if (isDropdownOpen && dropdownListRef.current) {
            const selectedElement = dropdownListRef.current.querySelector('[data-selected="true"]');
            if (selectedElement) {
                // 약간의 지연 후 스크롤 (애니메이션 후)
                setTimeout(() => {
                    selectedElement.scrollIntoView({ block: 'center', behavior: 'smooth' });
                }, 50);
            }
        }
    }, [isDropdownOpen]);

    const relatedDates = schedule.related_dates || [];
    const hasMultipleDates = relatedDates.length > 1;
    const hasLocation = displayData.locationLat && displayData.locationLng;
    const hasPoster = !!displayData.posterUrl;
    const hasDescription = !!displayData.description;

    // 현재 선택된 회차 인덱스
    const selectedIndex = relatedDates.findIndex(d => d.id === selectedDateId);
    const selectedDisplayIndex = selectedIndex >= 0 ? selectedIndex + 1 : 1;

    // 회차 선택 핸들러
    const handleSelectDate = (id) => {
        setSelectedDateId(id);
        setIsDropdownOpen(false);
    };

    // 짧은 날짜 포맷팅 (회차 목록용)
    const formatShortDate = (dateStr, timeStr) => {
        const date = new Date(dateStr);
        const dayNames = ['일', '월', '화', '수', '목', '금', '토'];
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const weekday = dayNames[date.getDay()];

        let result = `${month}/${day} (${weekday})`;
        if (timeStr) {
            result += ` ${timeStr.slice(0, 5)}`;
        }
        return result;
    };

    return (
        <div className="space-y-6">
            {/* ========== 히어로 섹션 ========== */}
            <motion.section
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                className="relative rounded-3xl overflow-visible"
            >
                {/* 배경 레이어 - 포스터 확대 + 블러 */}
                <div className="absolute inset-0 rounded-3xl overflow-hidden">
                    {hasPoster ? (
                        <>
                            <img
                                src={displayData.posterUrl}
                                alt=""
                                className="w-full h-full object-cover scale-125 blur-xl"
                            />
                            <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/50 to-black/30" />
                        </>
                    ) : (
                        <div className="absolute inset-0 bg-gradient-to-br from-primary via-primary/90 to-primary/70" />
                    )}
                </div>

                {/* 메인 콘텐츠 */}
                <div className="relative z-10 p-10">
                    <div className="flex items-start gap-10">
                        {/* 포스터 */}
                        {hasPoster && (
                            <motion.div
                                initial={{ opacity: 0, y: 20 }}
                                animate={{ opacity: 1, y: 0 }}
                                transition={{ duration: 0.5 }}
                                className="flex-shrink-0"
                            >
                                <img
                                    src={displayData.posterUrl}
                                    alt={displayData.title}
                                    className="w-52 h-72 object-cover rounded-2xl shadow-2xl"
                                />
                            </motion.div>
                        )}

                        {/* 제목 및 회차 선택 */}
                        <div className="flex-1 min-w-0 pt-4">
                            {/* 제목 */}
                            <motion.h1
                                initial={{ opacity: 0, y: 20 }}
                                animate={{ opacity: 1, y: 0 }}
                                transition={{ delay: 0.1 }}
                                className="text-3xl font-bold text-white leading-tight mb-6"
                            >
                                {decodeHtmlEntities(displayData.title)}
                            </motion.h1>

                            {/* 회차 선택 드롭다운 */}
                            {hasMultipleDates && (
                                <motion.div
                                    initial={{ opacity: 0, y: 10 }}
                                    animate={{ opacity: 1, y: 0 }}
                                    transition={{ delay: 0.2 }}
                                    ref={dropdownRef}
                                    className="relative inline-block"
                                >
                                    <button
                                        onClick={() => setIsDropdownOpen(!isDropdownOpen)}
                                        className="group flex items-center gap-4 px-5 py-3.5 bg-white rounded-2xl shadow-lg hover:shadow-xl transition-all border border-gray-100"
                                    >
                                        {/* 회차 뱃지 */}
                                        <div className="flex items-center gap-2">
                                            <div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center">
                                                <span className="text-xs font-bold text-white">{selectedDisplayIndex}</span>
                                            </div>
                                            <span className="text-xs font-medium text-gray-400">회차</span>
                                        </div>
                                        
                                        {/* 구분선 */}
                                        <div className="w-px h-6 bg-gray-200" />
                                        
                                        {/* 날짜 정보 */}
                                        <div className="text-left">
                                            <div className="text-sm font-semibold text-gray-800">
                                                {formatShortDate(displayData.date, displayData.time)}
                                            </div>
                                        </div>
                                        
                                        <ChevronDown
                                            size={18}
                                            className={`text-gray-400 transition-transform duration-200 ${isDropdownOpen ? 'rotate-180' : ''}`}
                                        />
                                    </button>

                                    <AnimatePresence>
                                        {isDropdownOpen && (
                                            <motion.div
                                                initial={{ opacity: 0, y: -10, scale: 0.95 }}
                                                animate={{ opacity: 1, y: 0, scale: 1 }}
                                                exit={{ opacity: 0, y: -10, scale: 0.95 }}
                                                transition={{ duration: 0.2, ease: 'easeOut' }}
                                                className="absolute top-full left-0 mt-3 bg-white rounded-2xl shadow-2xl z-[100] w-80 overflow-hidden border border-gray-100"
                                            >
                                                {/* 드롭다운 헤더 */}
                                                <div className="px-4 py-3 bg-gray-50 border-b border-gray-100">
                                                    <span className="text-sm font-semibold text-gray-600">공연 일정 선택</span>
                                                </div>
                                                
                                                <div ref={dropdownListRef} className="py-2 max-h-72 overflow-y-auto">
                                                    {relatedDates.map((item, index) => {
                                                        const isSelected = item.id === selectedDateId;
                                                        return (
                                                            <button
                                                                key={item.id}
                                                                data-selected={isSelected}
                                                                onClick={() => handleSelectDate(item.id)}
                                                                className={`w-full flex items-center gap-4 px-4 py-3.5 transition-all ${
                                                                    isSelected
                                                                        ? 'bg-primary/5'
                                                                        : 'hover:bg-gray-50'
                                                                }`}
                                                            >
                                                                {/* 회차 번호 */}
                                                                <div className={`w-9 h-9 rounded-xl flex items-center justify-center text-sm font-bold transition-colors ${
                                                                    isSelected
                                                                        ? 'bg-primary text-white'
                                                                        : 'bg-gray-100 text-gray-500'
                                                                }`}>
                                                                    {index + 1}
                                                                </div>
                                                                
                                                                {/* 날짜 정보 */}
                                                                <div className="flex-1 text-left">
                                                                    <div className={`font-medium ${
                                                                        isSelected ? 'text-primary' : 'text-gray-800'
                                                                    }`}>
                                                                        {formatShortDate(item.date, item.time)}
                                                                    </div>
                                                                </div>
                                                                
                                                                {/* 체크 표시 */}
                                                                {isSelected && (
                                                                    <div className="w-6 h-6 bg-primary rounded-full flex items-center justify-center">
                                                                        <Check size={14} className="text-white" strokeWidth={3} />
                                                                    </div>
                                                                )}
                                                            </button>
                                                        );
                                                    })}
                                                </div>
                                            </motion.div>
                                        )}
                                    </AnimatePresence>
                                </motion.div>
                            )}
                        </div>
                    </div>
                </div>
            </motion.section>

            {/* ========== 장소 정보 카드 ========== */}
            {displayData.locationName && (
                <motion.section
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.3 }}
                    className="bg-white rounded-2xl shadow-sm ring-1 ring-gray-100 overflow-hidden"
                >
                    {/* 헤더 */}
                    <div className="p-6 border-b border-gray-100">
                        <div className="flex items-center justify-between">
                            <div className="flex items-center gap-4">
                                {/* 장소 아이콘 */}
                                <div className="w-12 h-12 bg-gray-100 rounded-xl flex items-center justify-center">
                                    <MapPin size={24} className="text-gray-600" />
                                </div>
                                {/* 텍스트 */}
                                <div>
                                    <h2 className="text-lg font-bold text-gray-900">{displayData.locationName}</h2>
                                    {displayData.locationAddress && (
                                        <p className="text-sm text-gray-500 mt-0.5">{displayData.locationAddress}</p>
                                    )}
                                </div>
                            </div>
                            
                            {/* 길찾기 버튼 - 카카오맵(국내) / 구글맵(해외) */}
                            <a
                                href={hasLocation
                                    ? `https://map.kakao.com/link/to/${encodeURIComponent(displayData.locationName)},${displayData.locationLat},${displayData.locationLng}`
                                    : `https://www.google.com/maps/dir/?api=1&destination=${encodeURIComponent(displayData.locationAddress || displayData.locationName)}`
                                }
                                target="_blank"
                                rel="noopener noreferrer"
                                className="flex items-center gap-2 px-4 py-2.5 text-white text-sm font-semibold rounded-lg transition-colors"
                                style={{ 
                                    backgroundColor: hasLocation ? '#0079f4' : '#4285F4'
                                }}
                            >
                                <Navigation size={16} />
                                길찾기
                            </a>
                        </div>
                    </div>

                    {/* 지도 - 높이 2배 */}
                    <div className="h-[32rem]">
                        {hasLocation ? (
                            <KakaoMap
                                lat={parseFloat(displayData.locationLat)}
                                lng={parseFloat(displayData.locationLng)}
                                name={displayData.locationName}
                            />
                        ) : (
                            <iframe
                                src={`https://maps.google.com/maps?q=${encodeURIComponent(displayData.locationAddress || displayData.locationName)}&output=embed&hl=ko`}
                                className="h-full w-full border-0"
                                loading="lazy"
                                referrerPolicy="no-referrer-when-downgrade"
                                title="Google Maps"
                            />
                        )}
                    </div>
                </motion.section>
            )}

            {/* ========== 공연 정보 카드 ========== */}
            {hasDescription && (
                <motion.section
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.4 }}
                    className="bg-white rounded-2xl shadow-sm ring-1 ring-gray-100 p-6"
                >
                    <div className="flex items-center gap-3 mb-4">
                        <div className="w-10 h-10 rounded-xl bg-purple-50 flex items-center justify-center">
                            <svg className="w-5 h-5 text-purple-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                            </svg>
                        </div>
                        <h2 className="text-lg font-bold text-gray-900">공연 정보</h2>
                    </div>
                    <p className="text-gray-600 leading-relaxed whitespace-pre-wrap">
                        {decodeHtmlEntities(displayData.description)}
                    </p>
                </motion.section>
            )}

            {/* ========== 외부 링크 버튼 ========== */}
            {displayData.sourceUrl && (
                <motion.div
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.5 }}
                    className="flex justify-center"
                >
                    <a
                        href={displayData.sourceUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="inline-flex items-center gap-2 px-6 py-3 bg-gray-900 text-white rounded-xl font-semibold hover:bg-gray-800 transition-colors"
                    >
                        <ExternalLink size={18} />
                        티켓 예매 및 상세 정보
                    </a>
                </motion.div>
            )}
        </div>
    );
}

export default ConcertSection;
