"use client"

import { motion } from "framer-motion";
import Link from "next/link";
import { ArrowLeft, MapPin } from "lucide-react";
import { ImageViewer } from "@/components/ui/ImageViewer";
import { useState, useEffect } from "react";

export default function StationGalleryClient({ station }) {
  const [images, setImages] = useState([]);
  const [selectedImage, setSelectedImage] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // Dynamically discover images for this station
    const loadImages = async () => {
      const stationImages = [];
      // Try loading numbered images (1.jpg, 2.jpg, etc.)
      for (let i = 1; i <= 20; i++) {
        const src = `/stations/${station.id}/${i}.jpg`;
        try {
          const response = await fetch(src, { method: "HEAD" });
          if (response.ok) {
            stationImages.push({
              src,
              alt: `${station.name} - Photo ${i}`,
              category: station.name,
            });
          } else {
            break; // Stop when we hit a missing image
          }
        } catch {
          break;
        }
      }

      if (stationImages.length === 0) {
        // Fallback: add the main station image
        stationImages.push({
          src: station.image,
          alt: station.name,
          category: station.name,
        });
      }

      setImages(stationImages);
      setLoading(false);
    };

    loadImages();
  }, [station]);

  return (
    <div className="pt-20">
      <div className="py-16">
        <div className="container px-4">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5 }}
          >
            <Link
              href="/"
              className="inline-flex items-center text-primary hover:underline mb-8"
            >
              <ArrowLeft className="mr-2 h-4 w-4" />
              Back to Home
            </Link>

            {/* Station Header */}
            <div className="bg-primary/5 rounded-xl p-6 md:p-8 mb-8 border border-primary/20">
              <div className="flex items-start gap-4">
                <div className="h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center shrink-0">
                  <MapPin className="h-6 w-6 text-primary" />
                </div>
                <div>
                  <h1 className="text-3xl md:text-4xl font-bold mb-2">
                    {station.name}
                  </h1>
                  <p className="text-muted-foreground">{station.description}</p>
                  <span className="inline-block mt-2 px-3 py-1 rounded-full text-xs font-semibold bg-primary/10 text-primary">
                    {station.badge}
                  </span>
                </div>
              </div>
            </div>

            {/* Gallery Grid */}
            {loading ? (
              <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                {[1, 2, 3, 4, 5, 6].map((i) => (
                  <div
                    key={i}
                    className="aspect-square rounded-xl bg-muted animate-pulse"
                  />
                ))}
              </div>
            ) : (
              <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                {images.map((image, index) => (
                  <motion.div
                    key={index}
                    initial={{ opacity: 0, scale: 0.9 }}
                    whileInView={{ opacity: 1, scale: 1 }}
                    transition={{ delay: index * 0.05 }}
                    viewport={{ once: true }}
                    onClick={() => setSelectedImage(image)}
                    className={`rounded-xl overflow-hidden bg-muted relative group cursor-pointer ${
                      index === 0
                        ? "aspect-video md:col-span-2 md:row-span-2"
                        : "aspect-square"
                    }`}
                  >
                    <img
                      src={image.src}
                      alt={image.alt}
                      className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110"
                    />
                    <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex flex-col justify-end p-4">
                      <span className="text-white text-sm font-medium">
                        {image.alt}
                      </span>
                    </div>
                  </motion.div>
                ))}
              </div>
            )}
          </motion.div>
        </div>
      </div>

      <ImageViewer
        isOpen={!!selectedImage}
        onClose={() => setSelectedImage(null)}
        src={selectedImage?.src}
        alt={selectedImage?.alt}
        category={selectedImage?.category}
      />
    </div>
  );
}
