"use client";

import { useEffect, useState } from "react";
import Image from "next/image";
import {
  getAllGaleryFiles,
  getGaleryData,
  getGaleryFileData,
} from "@/service/galery";

export default function GallerySection() {
  const [data, setData] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const TABS = [
    "All",
    "Grand Opening",
    "IIMS",
    "GIIAS",
    "GJAW",
    "Exhibitions",
    "Test Drive",
  ];

  const [activeTab, setActiveTab] = useState("All");

  const fetchData = async () => {
    try {
      setLoading(true);

      // 1️⃣ Ambil gallery (ada status_id)
      const galleryRes = await getGaleryData({
        limit: "100",
        page: 1,
        search: "",
      });

      const galleries = galleryRes?.data?.data ?? [];

      // hanya approved
      const approvedGalleries = galleries.filter((g: any) => g.status_id === 2);

      // 2️⃣ Ambil SEMUA files
      const filesRes = await getAllGaleryFiles();
      const files = filesRes?.data?.data ?? [];

      // 3️⃣ Mapping gallery + file berdasarkan gallery_id
      const merged = approvedGalleries.map((gallery: any) => {
        const file = files.find((f: any) => f.gallery_id === gallery.id);

        return {
          ...gallery,
          image_url: file?.image_url ?? null,
        };
      });

      setData(merged);
    } catch (err) {
      console.error("Error fetch galeri:", err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  const filteredData = data.filter((item) => {
    if (activeTab === "All") return true;
    if (activeTab === "Grand Opening") return true; // sementara
    return false; // tab lain belum ada konten
  });

  return (
    <section className="py-16 px-4 max-w-[1400px] mx-auto">
      <h2 className="text-4xl font-bold mb-8">Galeri Kami</h2>
      <div className="flex justify-center  gap-2 mb-10">
        {TABS.map((tab) => (
          <button
            key={tab}
            onClick={() => setActiveTab(tab)}
            className={`px-4 py-2 rounded-full text-sm font-medium transition
        ${
          activeTab === tab
            ? "bg-black text-white"
            : "bg-gray-100 text-gray-600 hover:bg-gray-200"
        }`}
          >
            {tab}
          </button>
        ))}
      </div>

      {loading ? (
        <p className="text-center">Loading...</p>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
          {filteredData.length > 0 ? (
            filteredData.map((item: any) => (
              <div
                key={`gallery-${item.id}`}
                className="relative w-full aspect-[3/2] bg-gray-100 rounded overflow-hidden"
              >
                {item.image_url ? (
                  <Image
                    src={item.image_url}
                    alt={item.title}
                    fill
                    className="object-cover"
                    unoptimized
                  />
                ) : (
                  <div className="flex items-center justify-center h-full text-gray-400">
                    No Image
                  </div>
                )}
              </div>
            ))
          ) : (
            <p className="col-span-full text-center text-gray-400">
              Konten belum tersedia
            </p>
          )}
        </div>
      )}
    </section>
  );
}
