import { useEffect, useRef, useState } from 'react';
import type { ShipImageInfo } from '../../entities/shipImage/model/types';
import { fetchShipImagesByImo, toThumbnailUrl } from '../../entities/shipImage/api/fetchShipImages';

interface ShipImageGalleryProps {
  imo?: number;
  initialImagePath?: string | null;
  totalCount?: number;
  onOpenModal?: (index: number, images?: ShipImageInfo[]) => void;
}

const SCROLL_STEP = 86; // 80px thumb + 6px gap

const ShipImageGallery = ({ imo, initialImagePath, totalCount, onOpenModal }: ShipImageGalleryProps) => {
  const [images, setImages] = useState<ShipImageInfo[] | null>(null);
  const scrollRef = useRef<HTMLDivElement>(null);
  const [canScrollLeft, setCanScrollLeft] = useState(false);
  const [canScrollRight, setCanScrollRight] = useState(false);

  useEffect(() => {
    if (!imo || imo <= 0) return;
    const ac = new AbortController();
    fetchShipImagesByImo(imo, ac.signal).then((result) => {
      if (ac.signal.aborted) return;
      if (result.length > 0) setImages(result);
    });
    return () => ac.abort();
  }, [imo]);

  const updateScrollButtons = () => {
    const el = scrollRef.current;
    if (!el) return;
    setCanScrollLeft(el.scrollLeft > 0);
    setCanScrollRight(el.scrollLeft + el.clientWidth < el.scrollWidth - 1);
  };

  useEffect(() => {
    const el = scrollRef.current;
    if (!el || !images) return;
    const raf = requestAnimationFrame(updateScrollButtons);
    el.addEventListener('scroll', updateScrollButtons, { passive: true });
    return () => {
      cancelAnimationFrame(raf);
      el.removeEventListener('scroll', updateScrollButtons);
    };
  }, [images]);

  const handleScroll = (dir: 'left' | 'right') => {
    const el = scrollRef.current;
    if (!el) return;
    el.scrollBy({ left: dir === 'left' ? -SCROLL_STEP : SCROLL_STEP, behavior: 'smooth' });
  };

  // 전체 이미지 로드 완료
  if (images && images.length > 0) {
    const showArrows = images.length > 3;
    return (
      <div className="ship-image-gallery-wrap">
        {showArrows && canScrollLeft && (
          <button
            className="ship-image-gallery__arrow ship-image-gallery__arrow--left"
            onClick={() => handleScroll('left')}
            aria-label="이전 사진"
          >
            ‹
          </button>
        )}
        <div className="ship-image-gallery" ref={scrollRef}>
          {images.map((img, i) => (
            <button
              key={img.picId}
              className="ship-image-gallery__thumb"
              onClick={() => onOpenModal?.(i, images)}
              aria-label={`선박 사진 ${i + 1}`}
            >
              <img
                src={toThumbnailUrl(img.path)}
                alt={`사진 ${i + 1}`}
                loading="lazy"
              />
            </button>
          ))}
        </div>
        {showArrows && canScrollRight && (
          <button
            className="ship-image-gallery__arrow ship-image-gallery__arrow--right"
            onClick={() => handleScroll('right')}
            aria-label="다음 사진"
          >
            ›
          </button>
        )}
      </div>
    );
  }

  // fallback: 단일 이미지 (API 로딩 중이거나 imo 없음)
  if (!initialImagePath) return null;
  const count = totalCount ?? 1;

  return (
    <div className="ship-image-gallery">
      <button
        className="ship-image-gallery__thumb"
        onClick={() => onOpenModal?.(0)}
        aria-label="선박 사진 1"
        style={{ position: 'relative' }}
      >
        <img
          src={toThumbnailUrl(initialImagePath)}
          alt="사진 1"
          loading="lazy"
        />
        {count > 1 && (
          <span style={{
            position: 'absolute', top: 2, right: 2,
            background: 'rgba(30,120,255,0.92)', color: '#fff',
            borderRadius: '50%', width: 18, height: 18,
            fontSize: 10, fontWeight: 700,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            {count > 9 ? '9+' : count}
          </span>
        )}
      </button>
    </div>
  );
};

export default ShipImageGallery;
