import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { X, Download, ChevronRight, Info, Users, Tag } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Virtual } from 'swiper/modules';
import 'swiper/css';
import { getAlbumByName } from '@/api/albums';
import { LightboxIndicator } from '@/components/common';

/**
 * Mobile 앨범 갤러리 페이지
 */
function MobileAlbumGallery() {
  const { name } = useParams();
  const navigate = useNavigate();
  const [selectedIndex, setSelectedIndex] = useState(null);
  const [showInfo, setShowInfo] = useState(false);
  const swiperRef = useRef(null);

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

  // 앨범 데이터에서 사진 목록 추출
  const photos = useMemo(() => {
    if (!album?.conceptPhotos) return [];
    const allPhotos = [];
    Object.entries(album.conceptPhotos).forEach(([concept, conceptPhotos]) => {
      conceptPhotos.forEach((p) =>
        allPhotos.push({
          ...p,
          concept: concept !== 'Default' ? concept : null,
        })
      );
    });
    return allPhotos;
  }, [album]);

  // 라이트박스 열기
  const openLightbox = useCallback((index) => {
    setSelectedIndex(index);
    window.history.pushState({ lightbox: true }, '');
  }, []);

  // 정보 시트 열기
  const openInfo = useCallback(() => {
    setShowInfo(true);
    window.history.pushState({ infoSheet: true }, '');
  }, []);

  // 뒤로가기 처리
  useEffect(() => {
    const handlePopState = () => {
      if (showInfo) {
        setShowInfo(false);
      } else if (selectedIndex !== null) {
        setSelectedIndex(null);
      }
    };

    window.addEventListener('popstate', handlePopState);
    return () => window.removeEventListener('popstate', handlePopState);
  }, [showInfo, selectedIndex]);

  // 이미지 다운로드
  const downloadImage = useCallback(async () => {
    const photo = photos[selectedIndex];
    if (!photo) return;

    try {
      const response = await fetch(photo.original_url);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `fromis9_${album?.title || 'photo'}_${String(selectedIndex + 1).padStart(2, '0')}.webp`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    } catch (error) {
      console.error('다운로드 오류:', error);
    }
  }, [photos, selectedIndex, album?.title]);

  // 바디 스크롤 방지
  useEffect(() => {
    if (selectedIndex !== null) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = '';
    }
    return () => {
      document.body.style.overflow = '';
    };
  }, [selectedIndex]);

  // 사진을 2열로 균등 분배 (높이 기반)
  const distributePhotos = () => {
    const leftColumn = [];
    const rightColumn = [];
    let leftHeight = 0;
    let rightHeight = 0;

    photos.forEach((photo, index) => {
      const aspectRatio = photo.height && photo.width ? photo.height / photo.width : 1;

      if (leftHeight <= rightHeight) {
        leftColumn.push({ ...photo, originalIndex: index });
        leftHeight += aspectRatio;
      } else {
        rightColumn.push({ ...photo, originalIndex: index });
        rightHeight += aspectRatio;
      }
    });

    return { leftColumn, rightColumn };
  };

  const { leftColumn, rightColumn } = distributePhotos();

  // 현재 사진 정보
  const currentPhoto = selectedIndex !== null ? photos[selectedIndex] : null;
  const hasInfo = currentPhoto?.concept || currentPhoto?.members;

  // 정보 시트 드래그 핸들러
  const handleInfoDragEnd = (_, info) => {
    if (info.offset.y > 100 || info.velocity.y > 300) {
      window.history.back();
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="w-8 h-8 border-2 border-primary border-t-transparent rounded-full animate-spin" />
      </div>
    );
  }

  return (
    <>
      <div className="pb-4">
        {/* 앨범 헤더 카드 */}
        <div
          className="mx-4 mt-4 mb-4 p-4 bg-gradient-to-r from-primary/5 to-primary/10 rounded-2xl flex items-center gap-4"
          onClick={() => navigate(-1)}
        >
          {album?.cover_thumb_url && (
            <img
              src={album.cover_thumb_url}
              alt={album.title}
              className="w-14 h-14 rounded-xl object-cover shadow-sm"
            />
          )}
          <div className="flex-1 min-w-0">
            <p className="text-xs text-primary font-medium mb-0.5">컨셉 포토</p>
            <p className="font-bold truncate">{album?.title}</p>
            <p className="text-xs text-gray-500">{photos.length}장의 사진</p>
          </div>
          <ChevronRight size={20} className="text-gray-400 rotate-180" />
        </div>

        {/* 2열 그리드 */}
        <div className="px-3 flex gap-2">
          <div className="flex-1 flex flex-col gap-2">
            {leftColumn.map((photo) => (
              <motion.div
                key={photo.id || photo.originalIndex}
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: Math.min(photo.originalIndex * 0.02, 0.4) }}
                onClick={() => openLightbox(photo.originalIndex)}
                className="cursor-pointer overflow-hidden rounded-xl bg-gray-100"
              >
                <img
                  src={photo.thumb_url || photo.medium_url}
                  alt=""
                  className="w-full h-auto object-cover"
                  loading="lazy"
                />
              </motion.div>
            ))}
          </div>
          <div className="flex-1 flex flex-col gap-2">
            {rightColumn.map((photo) => (
              <motion.div
                key={photo.id || photo.originalIndex}
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: Math.min(photo.originalIndex * 0.02, 0.4) }}
                onClick={() => openLightbox(photo.originalIndex)}
                className="cursor-pointer overflow-hidden rounded-xl bg-gray-100"
              >
                <img
                  src={photo.thumb_url || photo.medium_url}
                  alt=""
                  className="w-full h-auto object-cover"
                  loading="lazy"
                />
              </motion.div>
            ))}
          </div>
        </div>
      </div>

      {/* 풀스크린 라이트박스 */}
      <AnimatePresence>
        {selectedIndex !== null && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black z-[60] flex flex-col"
          >
            {/* 상단 헤더 */}
            <div className="absolute top-0 left-0 right-0 flex items-center px-4 py-3 z-20">
              <div className="flex-1 flex justify-start">
                <button onClick={() => window.history.back()} className="text-white/80 p-1">
                  <X size={24} />
                </button>
              </div>
              <span className="text-white/70 text-sm tabular-nums">
                {selectedIndex + 1} / {photos.length}
              </span>
              <div className="flex-1 flex justify-end items-center gap-2">
                {hasInfo && (
                  <button onClick={openInfo} className="text-white/80 p-1">
                    <Info size={22} />
                  </button>
                )}
                <button onClick={downloadImage} className="text-white/80 p-1">
                  <Download size={22} />
                </button>
              </div>
            </div>

            {/* Swiper */}
            <Swiper
              modules={[Virtual]}
              virtual
              initialSlide={selectedIndex}
              onSwiper={(swiper) => {
                swiperRef.current = swiper;
              }}
              onSlideChange={(swiper) => setSelectedIndex(swiper.activeIndex)}
              className="w-full h-full"
              spaceBetween={0}
              slidesPerView={1}
              resistance={true}
              resistanceRatio={0.5}
            >
              {photos.map((photo, index) => (
                <SwiperSlide key={photo.id || index} virtualIndex={index}>
                  <div className="w-full h-full flex items-center justify-center">
                    <img
                      src={photo.medium_url || photo.original_url}
                      alt=""
                      className="max-w-full max-h-full object-contain"
                      loading={Math.abs(index - selectedIndex) <= 2 ? 'eager' : 'lazy'}
                    />
                  </div>
                </SwiperSlide>
              ))}
            </Swiper>

            {/* 모바일용 인디케이터 */}
            <LightboxIndicator
              count={photos.length}
              currentIndex={selectedIndex}
              goToIndex={(i) => swiperRef.current?.slideTo(i)}
              width={120}
            />

            {/* 정보 바텀시트 */}
            <AnimatePresence>
              {showInfo && hasInfo && (
                <motion.div
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  exit={{ opacity: 0 }}
                  className="absolute inset-0 bg-black/60 z-30"
                  onClick={() => window.history.back()}
                >
                  <motion.div
                    initial={{ y: '100%' }}
                    animate={{ y: 0 }}
                    exit={{ y: '100%' }}
                    transition={{ type: 'spring', damping: 25, stiffness: 300 }}
                    drag="y"
                    dragConstraints={{ top: 0, bottom: 0 }}
                    dragElastic={{ top: 0, bottom: 0.5 }}
                    onDragEnd={handleInfoDragEnd}
                    className="absolute bottom-0 left-0 right-0 bg-zinc-900 rounded-t-3xl"
                    onClick={(e) => e.stopPropagation()}
                  >
                    {/* 드래그 핸들 */}
                    <div className="flex justify-center pt-3 pb-2 cursor-grab active:cursor-grabbing">
                      <div className="w-10 h-1 bg-zinc-600 rounded-full" />
                    </div>

                    {/* 정보 내용 */}
                    <div className="px-5 pb-8 space-y-4">
                      <h3 className="text-white font-semibold text-lg">사진 정보</h3>

                      {currentPhoto?.members && (
                        <div className="flex items-start gap-3">
                          <div className="w-8 h-8 bg-primary/20 rounded-full flex items-center justify-center flex-shrink-0">
                            <Users size={16} className="text-primary" />
                          </div>
                          <div>
                            <p className="text-zinc-400 text-xs mb-1">멤버</p>
                            <p className="text-white">{currentPhoto.members}</p>
                          </div>
                        </div>
                      )}

                      {currentPhoto?.concept && (
                        <div className="flex items-start gap-3">
                          <div className="w-8 h-8 bg-white/10 rounded-full flex items-center justify-center flex-shrink-0">
                            <Tag size={16} className="text-zinc-400" />
                          </div>
                          <div>
                            <p className="text-zinc-400 text-xs mb-1">컨셉</p>
                            <p className="text-white">{currentPhoto.concept}</p>
                          </div>
                        </div>
                      )}
                    </div>
                  </motion.div>
                </motion.div>
              )}
            </AnimatePresence>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}

export default MobileAlbumGallery;
