import { useState, useMemo, useEffect, useLayoutEffect } 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, ChevronDown, ChevronUp } from 'lucide-react';
import { getTrack } from '@/api';
import { getYoutubeVideoId, parseCredits } from '@/utils';

/**
 * 크레딧 텍스트를 줄바꿈으로 렌더링
 */
function formatCredit(text) {
  const credits = parseCredits(text);
  if (credits.length === 0) return null;
  return credits.map((item, index) => (
    <span key={index} className="block">
      {item}
    </span>
  ));
}

/**
 * Mobile 곡 상세 페이지
 */
function MobileTrackDetail() {
  const { name: albumName, trackTitle } = useParams();
  const navigate = useNavigate();

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

  const youtubeVideoId = useMemo(() => getYoutubeVideoId(track?.video_url), [track?.video_url]);
  const videoLabel = track?.video_type === 'special' ? '스페셜 영상' : '뮤직비디오';

  // 트랙 변경 시 스크롤 맨 위로
  useLayoutEffect(() => {
    window.scrollTo({ top: 0, behavior: 'instant' });
  }, [trackTitle]);

  // 가사 펼침 상태
  const [showFullLyrics, setShowFullLyrics] = useState(false);

  // 전체화면 시 자동 가로 회전 처리
  useEffect(() => {
    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);
    };
  }, []);

  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>
    );
  }

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

  return (
    <div key={trackTitle} className="pb-4">
      {/* 트랙 정보 헤더 */}
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="px-4 py-5"
      >
        <div className="flex gap-4 items-start">
          {/* 앨범 커버 */}
          <div 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" />
          </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>
      </motion.div>

      {/* 뮤직비디오 섹션 */}
      {youtubeVideoId && (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.15 }}
          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" />
            {videoLabel}
          </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} ${videoLabel}`}
              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: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
          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" />
            크레딧
          </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: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.25 }}
        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" />
          가사
        </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>
    </div>
  );
}

export default MobileTrackDetail;
