import { useState, useMemo } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { motion } from 'framer-motion';
import { Clock, User, Music, Mic2, ChevronLeft, ChevronDown, ChevronUp } from 'lucide-react';
import { getTrack } from '../../../api/public/albums';

// 유튜브 URL에서 비디오 ID 추출
const getYoutubeVideoId = (url) => {
    if (!url) return null;
    const patterns = [
        /(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([^&\n?#]+)/,
    ];
    for (const pattern of patterns) {
        const match = url.match(pattern);
        if (match) return match[1];
    }
    return null;
};

// 쉼표 기준 줄바꿈 처리
const formatCredit = (text) => {
    if (!text) return null;
    return text.split(',').map((item, index) => (
        <span key={index} className="block">{item.trim()}</span>
    ));
};

// 모바일 곡 상세 페이지
function TrackDetail() {
    const { name: albumName, trackTitle } = useParams();
    const navigate = useNavigate();

    // useQuery로 트랙 데이터 로드
    const { data: track, isLoading: loading, error } = useQuery({
        queryKey: ['track', albumName, trackTitle],
        queryFn: () => getTrack(albumName, trackTitle),
        enabled: !!albumName && !!trackTitle,
    });

    const youtubeVideoId = useMemo(() => getYoutubeVideoId(track?.music_video_url), [track?.music_video_url]);
    
    // 가사 펼침 상태
    const [showFullLyrics, setShowFullLyrics] = useState(false);

    if (loading) {
        return (
            <div className="flex justify-center items-center min-h-[60vh]">
                <div className="animate-spin rounded-full h-10 w-10 border-4 border-primary border-t-transparent"></div>
            </div>
        );
    }

    if (error || !track) {
        return (
            <div className="py-12 text-center">
                <p className="text-gray-500">트랙을 찾을 수 없습니다.</p>
            </div>
        );
    }

    return (
        <motion.div 
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ duration: 0.3 }}
            className="pb-4"
        >
            {/* 헤더 - 뒤로가기 */}
            <div className="flex items-center gap-3 px-4 py-3 border-b border-gray-100">
                <button 
                    onClick={() => navigate(`/album/${encodeURIComponent(track.album?.title || albumName)}`)}
                    className="p-1"
                >
                    <ChevronLeft size={24} className="text-gray-600" />
                </button>
                <div className="flex-1 min-w-0">
                    <p className="text-xs text-gray-400">{track.album?.title}</p>
                    <p className="font-medium truncate">{track.title}</p>
                </div>
            </div>

            {/* 트랙 정보 헤더 */}
            <div className="px-4 py-5">
                <div className="flex gap-4 items-start">
                    {/* 앨범 커버 */}
                    <motion.div
                        initial={{ opacity: 0, scale: 0.9 }}
                        animate={{ opacity: 1, scale: 1 }}
                        transition={{ duration: 0.3 }}
                        className="w-24 h-24 rounded-xl overflow-hidden shadow-md flex-shrink-0"
                    >
                        <img
                            src={track.album?.cover_medium_url}
                            alt={track.album?.title}
                            className="w-full h-full object-cover"
                        />
                    </motion.div>

                    {/* 트랙 정보 */}
                    <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 mb-1.5">
                            {track.is_title_track === 1 && (
                                <span className="px-2 py-0.5 bg-primary text-white text-xs font-bold rounded-full">
                                    TITLE
                                </span>
                            )}
                            <span className="text-gray-400 text-xs">
                                Track {String(track.track_number).padStart(2, '0')}
                            </span>
                        </div>
                        
                        <h1 className="text-xl font-bold mb-1 text-gray-900 truncate">{track.title}</h1>
                        
                        <p className="text-sm text-gray-500 mb-2">
                            {track.album?.album_type} · {track.album?.title}
                        </p>

                        {track.duration && (
                            <div className="flex items-center gap-1.5 text-gray-400 text-sm">
                                <Clock size={14} />
                                <span>{track.duration}</span>
                            </div>
                        )}
                    </div>
                </div>
            </div>

            {/* 뮤직비디오 섹션 */}
            {youtubeVideoId && (
                <motion.div
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.1, duration: 0.3 }}
                    className="px-4 mb-5"
                >
                    <h2 className="text-base font-bold mb-3 flex items-center gap-2">
                        <div className="w-1 h-4 bg-red-500 rounded-full"></div>
                        뮤직비디오
                    </h2>
                    <div className="relative w-full aspect-video rounded-xl overflow-hidden shadow-md bg-black">
                        <iframe
                            src={`https://www.youtube.com/embed/${youtubeVideoId}`}
                            title={`${track.title} 뮤직비디오`}
                            className="absolute inset-0 w-full h-full"
                            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; fullscreen; web-share"
                            allowFullScreen
                        />
                    </div>
                </motion.div>
            )}

            {/* 크레딧 */}
            {(track.lyricist || track.composer || track.arranger) && (
                <motion.div
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.15, duration: 0.3 }}
                    className="px-4 mb-5"
                >
                    <h2 className="text-base font-bold mb-3 flex items-center gap-2">
                        <div className="w-1 h-4 bg-primary rounded-full"></div>
                        크레딧
                    </h2>
                    <div className="bg-gray-50 rounded-xl p-4 space-y-4">
                        {track.lyricist && (
                            <div className="flex items-start gap-3">
                                <div className="w-8 h-8 bg-white rounded-lg flex items-center justify-center flex-shrink-0 shadow-sm">
                                    <Mic2 size={14} className="text-gray-500" />
                                </div>
                                <div className="flex-1">
                                    <p className="text-xs text-gray-400 mb-0.5">작사</p>
                                    <p className="text-sm text-gray-700 leading-relaxed">
                                        {formatCredit(track.lyricist)}
                                    </p>
                                </div>
                            </div>
                        )}
                        {track.composer && (
                            <div className="flex items-start gap-3">
                                <div className="w-8 h-8 bg-white rounded-lg flex items-center justify-center flex-shrink-0 shadow-sm">
                                    <Music size={14} className="text-gray-500" />
                                </div>
                                <div className="flex-1">
                                    <p className="text-xs text-gray-400 mb-0.5">작곡</p>
                                    <p className="text-sm text-gray-700 leading-relaxed">
                                        {formatCredit(track.composer)}
                                    </p>
                                </div>
                            </div>
                        )}
                        {track.arranger && (
                            <div className="flex items-start gap-3">
                                <div className="w-8 h-8 bg-white rounded-lg flex items-center justify-center flex-shrink-0 shadow-sm">
                                    <User size={14} className="text-gray-500" />
                                </div>
                                <div className="flex-1">
                                    <p className="text-xs text-gray-400 mb-0.5">편곡</p>
                                    <p className="text-sm text-gray-700 leading-relaxed">
                                        {formatCredit(track.arranger)}
                                    </p>
                                </div>
                            </div>
                        )}
                    </div>
                </motion.div>
            )}

            {/* 가사 */}
            <motion.div
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.2, duration: 0.3 }}
                className="px-4"
            >
                <h2 className="text-base font-bold mb-3 flex items-center gap-2">
                    <div className="w-1 h-4 bg-primary rounded-full"></div>
                    가사
                </h2>
                <div className="bg-gray-50 rounded-xl p-4">
                    {track.lyrics ? (
                        <>
                            <div className={`text-gray-700 leading-[1.8] whitespace-pre-line text-sm overflow-hidden ${
                                !showFullLyrics ? 'max-h-32' : ''
                            }`}>
                                {track.lyrics}
                            </div>
                            <button
                                onClick={() => setShowFullLyrics(!showFullLyrics)}
                                className="w-full mt-3 pt-3 border-t border-gray-200 flex items-center justify-center gap-1 text-sm text-gray-500"
                            >
                                {showFullLyrics ? (
                                    <>
                                        접기
                                        <ChevronUp size={16} />
                                    </>
                                ) : (
                                    <>
                                        더보기
                                        <ChevronDown size={16} />
                                    </>
                                )}
                            </button>
                        </>
                    ) : (
                        <div className="text-center py-8 text-gray-400">
                            <Mic2 size={36} className="mx-auto mb-2 opacity-20" />
                            <p className="text-sm">가사 정보가 없습니다</p>
                        </div>
                    )}
                </div>
            </motion.div>
        </motion.div>
    );
}

export default TrackDetail;
