"use client";

import Image from "next/image";
import { useState } from "react";

interface TripImage {
  id: string;
  url: string;
  caption: string | null;
}

export function ImageGallery({ images }: { images: TripImage[] }) {
  const [activeIndex, setActiveIndex] = useState(0);

  if (images.length === 0) {
    return (
      <div className="flex h-56 items-center justify-center bg-linear-to-br from-primary-800 to-secondary-900 sm:h-72">
        <span className="text-6xl">🏔️</span>
      </div>
    );
  }

  const activeImage = images[activeIndex];

  return (
    <div>
      {/* Main Image */}
      <div className="relative h-56 bg-neutral-900 sm:h-72">
        <Image
          src={activeImage.url}
          alt={activeImage.caption || "Foto trip"}
          fill
          className="object-cover"
          sizes="(max-width: 768px) 100vw, 768px"
          priority
        />
        {activeImage.caption && (
          <div className="absolute bottom-0 left-0 right-0 bg-linear-to-t from-black/60 to-transparent px-4 pb-3 pt-8">
            <p className="text-sm font-medium text-white">
              {activeImage.caption}
            </p>
          </div>
        )}
        {/* Counter */}
        <div className="absolute right-3 top-3 rounded-full bg-black/50 px-2.5 py-1 text-xs font-medium text-white backdrop-blur-sm">
          {activeIndex + 1} / {images.length}
        </div>
      </div>

      {/* Thumbnails */}
      {images.length > 1 && (
        <div className="flex gap-1.5 overflow-x-auto bg-neutral-100 p-2">
          {images.map((img, i) => (
            <button
              key={img.id}
              onClick={() => setActiveIndex(i)}
              className={`relative h-14 w-20 shrink-0 overflow-hidden rounded-lg transition-all ${
                i === activeIndex
                  ? "ring-2 ring-primary-500 ring-offset-1"
                  : "opacity-60 hover:opacity-100"
              }`}
            >
              <Image
                src={img.url}
                alt={img.caption || `Foto ${i + 1}`}
                fill
                className="object-cover"
                sizes="80px"
              />
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
