"use client";

import { useState } from "react";

export function ShopGallery({
  photos,
  alt,
  aspect = "4/5",
}: {
  photos: string[];
  alt: string;
  aspect?: "4/5" | "4/3";
}) {
  const [index, setIndex] = useState(0);
  if (photos.length === 0) {
    return <div className="aspect-[4/5] rounded-3xl bg-black/10" />;
  }
  const current = photos[index] ?? photos[0]!;
  const go = (delta: number) => {
    setIndex((i) => (i + delta + photos.length) % photos.length);
  };

  return (
    <div className="w-full min-w-0" dir="ltr">
      <div className="relative overflow-hidden rounded-3xl bg-black/5">
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img
          src={`/api/media/${current}`}
          alt={alt}
          className={`w-full object-cover ${aspect === "4/3" ? "aspect-[4/3]" : "aspect-[4/5]"}`}
        />
        {photos.length > 1 ? (
          <>
            <button
              type="button"
              aria-label="Previous photo"
              onClick={() => go(-1)}
              className="absolute start-3 top-1/2 z-10 flex h-11 w-11 -translate-y-1/2 items-center justify-center rounded-full bg-black/55 text-2xl text-white"
            >
              ‹
            </button>
            <button
              type="button"
              aria-label="Next photo"
              onClick={() => go(1)}
              className="absolute end-3 top-1/2 z-10 flex h-11 w-11 -translate-y-1/2 items-center justify-center rounded-full bg-black/55 text-2xl text-white"
            >
              ›
            </button>
            <p className="absolute bottom-3 end-3 rounded-full bg-black/55 px-2.5 py-1 text-xs text-white">
              {index + 1} / {photos.length}
            </p>
          </>
        ) : null}
      </div>
      {photos.length > 1 ? (
        <div className="mt-3 flex gap-2 overflow-x-auto">
          {photos.map((file, i) => (
            <button
              key={file}
              type="button"
              onClick={() => setIndex(i)}
              className={`h-16 w-16 shrink-0 overflow-hidden rounded-xl ring-2 ${
                i === index ? "ring-black" : "ring-transparent opacity-70"
              }`}
            >
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src={`/api/media/${file}`} alt="" className="h-full w-full object-cover" />
            </button>
          ))}
        </div>
      ) : null}
    </div>
  );
}
