import { useState, useEffect, useCallback, memo } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { motion, AnimatePresence } from 'framer-motion';
import { Calendar, Music2, Clock, X, ChevronLeft, ChevronRight, Download, MoreVertical, FileText } from 'lucide-react';
import { getAlbumByName } from '../../../api/public/albums';
import { formatDate } from '../../../utils/date';
import LightboxIndicator from '../../../components/common/LightboxIndicator';

function AlbumDetail() {
    const { name } = useParams();
    const navigate = useNavigate();
    const [lightbox, setLightbox] = useState({ open: false, images: [], index: 0 });
    const [slideDirection, setSlideDirection] = useState(0);
    const [imageLoaded, setImageLoaded] = useState(false);
    const [preloadedImages] = useState(() => new Set());
    const [showDescriptionModal, setShowDescriptionModal] = useState(false);
    const [showMenu, setShowMenu] = useState(false);

    // useQuery로 앨범 데이터 로드
    const { data: album, isLoading: loading } = useQuery({
        queryKey: ['album', name],
        queryFn: () => getAlbumByName(name),
        enabled: !!name,
    });

    // 라이트박스 네비게이션 함수
    const goToPrev = useCallback(() => {
        if (lightbox.images.length <= 1) return;
        setImageLoaded(false);
        setSlideDirection(-1);
        setLightbox(prev => ({
            ...prev,
            index: (prev.index - 1 + prev.images.length) % prev.images.length
        }));
    }, [lightbox.images.length]);

    const goToNext = useCallback(() => {
        if (lightbox.images.length <= 1) return;
        setImageLoaded(false);
        setSlideDirection(1);
        setLightbox(prev => ({
            ...prev,
            index: (prev.index + 1) % prev.images.length
        }));
    }, [lightbox.images.length]);

    const closeLightbox = useCallback(() => {
        setLightbox(prev => ({ ...prev, open: false }));
    }, []);

    // 라이트박스 열릴 때 body 스크롤 숨기기
    useEffect(() => {
        if (lightbox.open) {
            document.documentElement.style.overflow = 'hidden';
            document.body.style.overflow = 'hidden';
        } else {
            document.documentElement.style.overflow = '';
            document.body.style.overflow = '';
        }
        return () => {
            document.documentElement.style.overflow = '';
            document.body.style.overflow = '';
        };
    }, [lightbox.open]);

    // 이미지 다운로드 함수
    const downloadImage = useCallback(async () => {
        const imageUrl = lightbox.images[lightbox.index];
        if (!imageUrl) return;
        
        try {
            const response = await fetch(imageUrl);
            const blob = await response.blob();
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = `fromis9_photo_${String(lightbox.index + 1).padStart(2, '0')}.webp`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
        } catch (error) {
            console.error('다운로드 오류:', error);
        }
    }, [lightbox.images, lightbox.index]);

    // 키보드 이벤트 핸들러
    useEffect(() => {
        if (!lightbox.open) return;

        const handleKeyDown = (e) => {
            switch (e.key) {
                case 'ArrowLeft':
                    goToPrev();
                    break;
                case 'ArrowRight':
                    goToNext();
                    break;
                case 'Escape':
                    closeLightbox();
                    break;
                default:
                    break;
            }
        };

        window.addEventListener('keydown', handleKeyDown);
        return () => window.removeEventListener('keydown', handleKeyDown);
    }, [lightbox.open, goToPrev, goToNext, closeLightbox]);

    // 이미지 프리로딩 (이전/다음 2개씩) - 백그라운드에서 프리로드만
    useEffect(() => {
        if (!lightbox.open || lightbox.images.length <= 1) return;
        
        // 양옆 이미지 프리로드
        const indicesToPreload = [];
        for (let offset = -2; offset <= 2; offset++) {
            if (offset === 0) continue;
            const idx = (lightbox.index + offset + lightbox.images.length) % lightbox.images.length;
            indicesToPreload.push(idx);
        }
        
        indicesToPreload.forEach(idx => {
            const url = lightbox.images[idx];
            if (preloadedImages.has(url)) return;
            
            const img = new Image();
            img.onload = () => preloadedImages.add(url);
            img.src = url;
        });
    }, [lightbox.open, lightbox.index, lightbox.images, preloadedImages]);

    // URL 헬퍼 함수는 더 이상 필요 없음 - API에서 직접 제공

    // 총 재생 시간 계산
    const getTotalDuration = () => {
        if (!album?.tracks) return '';
        let totalSeconds = 0;
        album.tracks.forEach(track => {
            if (track.duration) {
                const parts = track.duration.split(':');
                totalSeconds += parseInt(parts[0]) * 60 + parseInt(parts[1]);
            }
        });
        const mins = Math.floor(totalSeconds / 60);
        const secs = totalSeconds % 60;
        return `${mins}:${String(secs).padStart(2, '0')}`;
    };

    // 뒤로가기
    const handleBack = () => {
        navigate('/album');
    };

    if (loading) {
        return (
            <motion.div 
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                className="py-16 flex justify-center items-center min-h-[60vh]"
            >
                <div className="animate-spin rounded-full h-12 w-12 border-4 border-primary border-t-transparent"></div>
            </motion.div>
        );
    }

    if (!album) {
        return (
            <div className="py-16 text-center">
                <p className="text-gray-500">앨범을 찾을 수 없습니다.</p>
            </div>
        );
    }

    return (
        <>
        <motion.div 
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ duration: 0.3 }}
            className="py-16"
        >
            <div className="max-w-7xl mx-auto px-6">
                {/* 브레드크럼 네비게이션 */}
                <div className="flex items-center gap-2 text-sm text-gray-500 mb-6">
                    <button 
                        onClick={handleBack}
                        className="hover:text-primary transition-colors"
                    >
                        앨범
                    </button>
                    <span>/</span>
                    <span className="text-gray-700">{album?.title}</span>
                </div>

                {/* 앨범 정보 헤더 */}
                <div className="flex gap-8 mb-10">
                    {/* 앨범 커버 - 클릭하면 라이트박스 */}
                    <motion.div
                        initial={{ opacity: 0, scale: 0.9 }}
                        animate={{ opacity: 1, scale: 1 }}
                        transition={{ duration: 0.4 }}
                        className="w-80 h-80 flex-shrink-0 rounded-2xl overflow-hidden shadow-lg cursor-pointer group"
                        onClick={() => setLightbox({ 
                            open: true, 
                            images: [album.cover_original_url || album.cover_medium_url], 
                            index: 0 
                        })}
                    >
                        <img
                            src={album.cover_medium_url || album.cover_original_url}
                            alt={album.title}
                            className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                        />
                    </motion.div>

                    {/* 앨범 정보 */}
                    <motion.div
                        initial={{ opacity: 0, y: 20 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ delay: 0.1, duration: 0.4 }}
                        className="flex-1 flex flex-col"
                    >
                        <div>
                            <div className="flex items-center justify-between mb-3">
                                <span className="inline-block w-fit px-3 py-1 bg-primary/10 text-primary text-sm font-medium rounded-full">
                                    {album.album_type}
                                </span>
                                {/* 점3개 메뉴 - 소개글이 있을 때만 */}
                                {album.description && (
                                    <div className="relative">
                                        <button
                                            onClick={() => setShowMenu(!showMenu)}
                                            className="p-2 hover:bg-gray-100 rounded-full transition-colors relative z-20"
                                        >
                                            <MoreVertical size={20} className="text-gray-500" />
                                        </button>
                                        <AnimatePresence>
                                            {showMenu && (
                                                <>
                                                    <div 
                                                        className="fixed inset-0 z-10" 
                                                        onClick={() => setShowMenu(false)}
                                                    />
                                                    <motion.div 
                                                        initial={{ opacity: 0, scale: 0.95, y: -5 }}
                                                        animate={{ opacity: 1, scale: 1, y: 0 }}
                                                        exit={{ opacity: 0, scale: 0.95, y: -5 }}
                                                        transition={{ duration: 0.15 }}
                                                        className="absolute right-0 top-full mt-1 bg-white rounded-xl shadow-lg border border-gray-100 py-1 z-20 min-w-[140px]"
                                                    >
                                                        <button
                                                            onClick={() => {
                                                                setShowDescriptionModal(true);
                                                                setShowMenu(false);
                                                            }}
                                                            className="w-full flex items-center gap-2 px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50 transition-colors"
                                                        >
                                                            <FileText size={16} />
                                                            앨범 소개
                                                        </button>
                                                    </motion.div>
                                                </>
                                            )}
                                        </AnimatePresence>
                                    </div>
                                )}
                            </div>
                            <h1 className="text-4xl font-bold mb-3">{album.title}</h1>
                            
                            <div className="flex items-center gap-6 text-gray-500 mb-3">
                                <div className="flex items-center gap-2">
                                    <Calendar size={18} />
                                    <span>{formatDate(album.release_date, 'YYYY.MM.DD')}</span>
                                </div>
                                <div className="flex items-center gap-2">
                                    <Music2 size={18} />
                                    <span>{album.tracks?.length || 0}곡</span>
                                </div>
                                <div className="flex items-center gap-2">
                                    <Clock size={18} />
                                    <span>{getTotalDuration()}</span>
                                </div>
                            </div>
                        </div>

                        {/* 앨범 티저 이미지/영상 */}
                        {album.teasers && album.teasers.length > 0 && (
                            <div className="mt-auto">
                                <p className="text-xs text-gray-400 mb-2">티저 이미지</p>
                                <div className="flex gap-2">
                                    {album.teasers.map((teaser, index) => (
                                        <div 
                                            key={index}
                                            onClick={() => setLightbox({
                                                open: true,
                                                images: album.teasers.map(t =>
                                                    t.media_type === 'video' ? (t.video_url || t.original_url) : t.original_url
                                                ),
                                                index,
                                                teasers: album.teasers // media_type 정보 전달
                                            })}
                                            className="w-24 h-24 bg-gray-200 rounded-lg overflow-hidden cursor-pointer transition-all duration-300 ease-out hover:scale-105 hover:shadow-xl hover:z-10 relative"
                                        >
                                            <>
                                                <img
                                                    src={teaser.thumb_url}
                                                    alt={`Teaser ${index + 1}`}
                                                    className="w-full h-full object-cover"
                                                />
                                                {/* 비디오 아이콘 오버레이 */}
                                                {teaser.media_type === 'video' && (
                                                    <div className="absolute inset-0 flex items-center justify-center bg-black/30">
                                                        <div className="w-8 h-8 bg-white/90 rounded-full flex items-center justify-center">
                                                            <div className="w-0 h-0 border-l-[10px] border-l-gray-800 border-y-[6px] border-y-transparent ml-1" />
                                                        </div>
                                                    </div>
                                                )}
                                            </>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}
                    </motion.div>
                </div>

                {/* 수록곡 리스트 */}
                <motion.div
                    initial={{ opacity: 0, y: 30 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.2, duration: 0.4 }}
                >
                    <h2 className="text-xl font-bold mb-4">수록곡</h2>
                    <div className="bg-white rounded-2xl shadow-lg overflow-hidden">
                        {album.tracks?.map((track, index) => (
                            <div
                                key={track.id}
                                onClick={() => navigate(`/album/${encodeURIComponent(album.title)}/track/${encodeURIComponent(track.title)}`)}
                                className={`group flex items-center gap-4 p-4 hover:bg-primary/5 transition-all duration-200 cursor-pointer ${
                                    index !== album.tracks.length - 1 ? 'border-b border-gray-100' : ''
                                }`}
                            >
                                {/* 트랙 번호 */}
                                <div className="w-10 h-10 flex items-center justify-center rounded-full bg-gray-100 group-hover:bg-primary/10 transition-colors">
                                    <span className="text-gray-500 group-hover:text-primary transition-colors">
                                        {String(track.track_number).padStart(2, '0')}
                                    </span>
                                </div>

                                {/* 트랙 정보 */}
                                <div className="flex-1">
                                    <div className="flex items-center gap-2">
                                        <h3 className="font-semibold group-hover:text-primary transition-colors">{track.title}</h3>
                                        {track.is_title_track === 1 && (
                                            <span className="px-2 py-0.5 bg-primary text-white text-xs font-medium rounded-full">
                                                TITLE
                                            </span>
                                        )}
                                    </div>
                                </div>

                                {/* 재생 시간 */}
                                <div className="text-gray-400 tabular-nums text-sm">
                                    {track.duration || '-'}
                                </div>
                            </div>
                        ))}
                    </div>
                </motion.div>

                {/* 컨셉 포토 섹션 */}
                {album.conceptPhotos && Object.keys(album.conceptPhotos).length > 0 && (
                <motion.div
                    initial={{ opacity: 0, y: 30 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.4, duration: 0.4 }}
                    className="mt-10"
                >
                    {(() => {
                        // 모든 컨셉 포토를 하나의 배열로 합치고 처음 4개만 표시
                        const allPhotos = Object.values(album.conceptPhotos).flat();
                        const previewPhotos = allPhotos.slice(0, 4);
                        const totalCount = allPhotos.length;
                        
                        return (
                            <>
                                <div className="flex items-center justify-between mb-4">
                                    <h2 className="text-xl font-bold">컨셉 포토</h2>
                                    <button 
                                        className="text-sm text-primary hover:underline"
                                        onClick={() => navigate(`/album/${name}/gallery`)}
                                    >
                                        전체보기 ({totalCount}장)
                                    </button>
                                </div>
                                <div className="grid grid-cols-4 gap-4">
                                    {previewPhotos.map((photo, idx) => (
                                        <div 
                                            key={photo.id}
                                            onClick={() => setLightbox({ open: true, images: [photo.original_url], index: 0 })}
                                            className="aspect-square bg-gray-200 rounded-xl overflow-hidden cursor-pointer transition-all duration-300 ease-out hover:scale-[1.03] hover:shadow-xl hover:z-10"
                                        >
                                            <img 
                                                src={photo.medium_url} 
                                                alt={`컨셉 포토 ${idx + 1}`}
                                                loading="lazy"
                                                className="w-full h-full object-cover"
                                            />
                                        </div>
                                    ))}
                                </div>
                            </>
                        );
                    })()}
                </motion.div>
                )}
            </div>
        </motion.div>

        {/* 라이트박스 모달 */}
        <AnimatePresence>
        {lightbox.open && (
            <motion.div 
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                transition={{ duration: 0.2 }}
                className="fixed inset-0 bg-black/95 z-50 overflow-scroll lightbox-no-scrollbar"
                style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' }}
            >
                {/* 내부 컨테이너 - min-width, min-height 적용 */}
                <div className="min-w-[1400px] min-h-[1200px] w-full h-full relative flex items-center justify-center">
                    {/* 상단 버튼들 */}
                    <div className="absolute top-6 right-6 flex gap-3 z-10">
                        {/* 다운로드 버튼 */}
                        <button 
                            className="text-white/70 hover:text-white transition-colors"
                            onClick={(e) => {
                                e.stopPropagation();
                                downloadImage();
                            }}
                        >
                            <Download size={28} />
                        </button>
                        {/* 닫기 버튼 */}
                        <button 
                            className="text-white/70 hover:text-white transition-colors"
                            onClick={closeLightbox}
                        >
                            <X size={32} />
                        </button>
                    </div>

                    {/* 이전 버튼 */}
                    {lightbox.images.length > 1 && (
                        <button 
                            className="absolute left-6 p-2 text-white/70 hover:text-white transition-colors z-10"
                            onClick={(e) => {
                                e.stopPropagation();
                                goToPrev();
                            }}
                        >
                            <ChevronLeft size={48} />
                        </button>
                    )}

                    {/* 로딩 스피너 */}
                    {!imageLoaded && (
                        <div className="absolute inset-0 flex items-center justify-center">
                            <div className="animate-spin rounded-full h-12 w-12 border-4 border-white border-t-transparent"></div>
                        </div>
                    )}

                    {/* 이미지 또는 비디오 */}
                    <div className="flex flex-col items-center mx-24">
                        {lightbox.teasers?.[lightbox.index]?.media_type === 'video' ? (
                            <motion.video
                                key={lightbox.index}
                                src={lightbox.images[lightbox.index]}
                                className={`max-w-[1100px] max-h-[900px] object-contain transition-opacity duration-200 ${imageLoaded ? 'opacity-100' : 'opacity-0'}`}
                                onClick={(e) => e.stopPropagation()}
                                onCanPlay={() => setImageLoaded(true)}
                                initial={{ x: slideDirection * 100 }}
                                animate={{ x: 0 }}
                                transition={{ duration: 0.25, ease: 'easeOut' }}
                                controls
                                autoPlay
                            />
                        ) : (
                            <motion.img 
                                key={lightbox.index}
                                src={lightbox.images[lightbox.index]}
                                alt="확대 이미지"
                                className={`max-w-[1100px] max-h-[900px] object-contain transition-opacity duration-200 ${imageLoaded ? 'opacity-100' : 'opacity-0'}`}
                                onClick={(e) => e.stopPropagation()}
                                onLoad={() => setImageLoaded(true)}
                                initial={{ x: slideDirection * 100 }}
                                animate={{ x: 0 }}
                                transition={{ duration: 0.25, ease: 'easeOut' }}
                            />
                        )}
                    </div>

                    {/* 다음 버튼 */}
                    {lightbox.images.length > 1 && (
                        <button 
                            className="absolute right-6 p-2 text-white/70 hover:text-white transition-colors z-10"
                            onClick={(e) => {
                                e.stopPropagation();
                                goToNext();
                            }}
                        >
                            <ChevronRight size={48} />
                        </button>
                    )}

                    {/* 인디케이터 - 공통 컴포넌트 사용 */}
                    {lightbox.images.length > 1 && (
                        <LightboxIndicator
                            count={lightbox.images.length}
                            currentIndex={lightbox.index}
                            goToIndex={(i) => setLightbox(prev => ({ ...prev, index: i }))}
                        />
                    )}
                </div>
            </motion.div>
        )}
        </AnimatePresence>

        {/* 앨범 소개 다이얼로그 */}
        <AnimatePresence>
            {showDescriptionModal && album?.description && (
                <motion.div
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    exit={{ opacity: 0 }}
                    className="fixed inset-0 bg-black/60 z-50 flex items-center justify-center p-4"
                    onClick={() => setShowDescriptionModal(false)}
                >
                    <motion.div
                        initial={{ opacity: 0, scale: 0.95, y: 20 }}
                        animate={{ opacity: 1, scale: 1, y: 0 }}
                        exit={{ opacity: 0, scale: 0.95, y: 20 }}
                        className="bg-white rounded-2xl shadow-2xl max-w-xl w-full max-h-[80vh] overflow-hidden"
                        onClick={(e) => e.stopPropagation()}
                    >
                        {/* 헤더 */}
                        <div className="flex items-center justify-between p-5 border-b border-gray-100">
                            <h3 className="text-lg font-bold">앨범 소개</h3>
                            <button
                                onClick={() => setShowDescriptionModal(false)}
                                className="p-1.5 hover:bg-gray-100 rounded-full transition-colors"
                            >
                                <X size={20} className="text-gray-500" />
                            </button>
                        </div>
                        {/* 내용 */}
                        <div className="p-6 overflow-y-auto max-h-[60vh]">
                            <p className="text-gray-600 leading-relaxed whitespace-pre-line text-justify">
                                {album.description}
                            </p>
                        </div>
                    </motion.div>
                </motion.div>
            )}
        </AnimatePresence>
    </>
    );
}

export default AlbumDetail;

