"use client";

import {
  JustifiedImage,
  justifyPortfolioImages,
} from "@/utils/justifyPortfolioImages";
import { useEffect, useRef, useState } from "react";
import { ImageCard } from "./ImageCard";
import { Lightbox } from "./Lightbox";

interface Props {
  images: JustifiedImage[];
  rowHeight?: number;
  gap?: number;
}

export function JustifiedGallery({ images, rowHeight = 200, gap = 4 }: Props) {
  const containerRef = useRef<HTMLDivElement>(null);
  const [containerWidth, setContainerWidth] = useState(1200);
  const [rows, setRows] = useState<JustifiedImage[][]>([]);
  const [selectedIndex, setSelectedIndex] = useState<number | null>(null);

  useEffect(() => {
    if (!containerRef.current) return;
    const observer = new ResizeObserver(([entry]) => {
      setContainerWidth(entry.contentRect.width);
    });
    observer.observe(containerRef.current);
    return () => observer.disconnect();
  }, []);

  useEffect(() => {
    const newRows = justifyPortfolioImages(images, containerWidth, rowHeight, gap);
    setRows(newRows);
  }, [images, containerWidth, rowHeight, gap]);

  const openModal = (index: number) => setSelectedIndex(index);

  return (
    <>
      <div ref={containerRef} className="w-full flex flex-col" style={{ rowGap: `${gap}px` }}>
        {rows.length === 0 && (
          <p className="text-muted-foreground text-center py-20">No images to display</p>
        )}
        {rows.map((row, i) => (
          <div
            key={i}
            className="flex" // Vertical gap between rows
            style={{ columnGap: `${gap}px` }} // Horizontal gap between images
          >
            {row.map((img) => {
              const index = images.findIndex((i) => i.id === img.id);
              return (
                <div
                  key={img.id}
                  style={{ width: img.width, height: img.height }}
                  onClick={() => openModal(index)}
                  className="cursor-zoom-in"
                >
                  <ImageCard
                    image={{
                      id: img.id,
                      altText: img.altText,
                      url: img.url,
                      backgroundColor: img.backgroundColor,
                    }}
                    variant="mosaic"
                  />
                </div>
              )
            })}
          </div>
        ))}
      </div>
      {selectedIndex !== null && (
        <Lightbox
          image={images[selectedIndex]}
          onClose={() => setSelectedIndex(null)}
          hasPrev={selectedIndex > 0}
          hasNext={selectedIndex < images.length - 1}
          onPrev={() => setSelectedIndex((i) => (i !== null ? i - 1 : null))}
          onNext={() => setSelectedIndex((i) => (i !== null ? i + 1 : null))}
        />
      )}
    </>
  );
}
