"use client";

import { useEffect, useState } from "react";
import { Image as ImageIcon, Filter, Building2 } from "lucide-react";

interface GalleryImage {
  id: string;
  image: string;
  title?: string | null;
  album?: string | null;
  sport?: { id: string; name: string } | null;
  board?: { id: string; name: string } | null;
}

interface Sport { id: string; name: string; }
interface Board { id: string; name: string; }

export default function GalleryPage() {
  const [images, setImages] = useState<GalleryImage[]>([]);
  const [sports, setSports] = useState<Sport[]>([]);
  const [boards, setBoards] = useState<Board[]>([]);
  const [selectedSport, setSelectedSport] = useState("");
  const [selectedBoard, setSelectedBoard] = useState("");
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    Promise.all([
      fetch("/api/gallery").then((r) => r.json()),
      fetch("/api/sports").then((r) => r.json()),
      fetch("/api/boards").then((r) => r.json()),
    ]).then(([imgs, sps, bds]) => {
      if (Array.isArray(imgs)) setImages(imgs);
      if (Array.isArray(sps)) setSports(sps);
      if (Array.isArray(bds)) setBoards(bds);
      setLoading(false);
    }).catch(() => setLoading(false));
  }, []);

  const filtered = images.filter((img) => {
    if (selectedSport && img.sport?.id !== selectedSport) return false;
    if (selectedBoard && (img as any).boardId !== selectedBoard && img.board?.id !== selectedBoard) return false;
    return true;
  });

  const albums = [...new Set(filtered.map((i) => i.album || "عمومی"))];

  return (
    <div>
      <div className="container mx-auto px-4 py-12">
        <div className="mb-10">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">گالری تصاویر</h1>
          <p className="text-gray-500">تصاویر مراسم، رویدادها و دوره‌های آموزشی</p>
        </div>

        <div className="space-y-3 mb-8">
          <div className="flex flex-wrap items-center gap-2">
            <Filter className="h-4 w-4 text-gray-400" />
            <select
              value={selectedBoard}
              onChange={(e) => setSelectedBoard(e.target.value)}
              className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#2563EB]/20 focus:border-[#2563EB] bg-white"
            >
              <option value="">همه هیئت‌ها</option>
              {boards.map((b) => (
                <option key={b.id} value={b.id}>{b.name}</option>
              ))}
            </select>
            <select
              value={selectedSport}
              onChange={(e) => setSelectedSport(e.target.value)}
              className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#2563EB]/20 focus:border-[#2563EB] bg-white"
            >
              <option value="">همه رشته‌ها</option>
              {sports.map((s) => (
                <option key={s.id} value={s.id}>{s.name}</option>
              ))}
            </select>
          </div>
        </div>

        {loading ? (
          <div className="text-center py-20">
            <p className="text-gray-500">در حال بارگذاری...</p>
          </div>
        ) : (
          <>
            {albums.map((album) => {
              const albumImages = filtered.filter((i) => (i.album || "عمومی") === album);
              return (
                <div key={album} className="mb-12 last:mb-0">
                  <h2 className="text-xl font-semibold text-gray-900 mb-5 flex items-center gap-2">
                    <div className="w-2 h-2 rounded-full bg-[#2563EB]" />
                    {album}
                  </h2>
                  <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
                    {albumImages.map((img) => (
                      <div
                        key={img.id}
                        className="group relative aspect-square rounded-2xl overflow-hidden border border-gray-100 bg-white shadow-sm hover:shadow-xl transition-all duration-200"
                      >
                        <img
                          src={img.image}
                          alt={img.title || ""}
                          className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500"
                        />
                        <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-black/0 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300" />
                        {img.title && (
                          <div className="absolute inset-x-0 bottom-0 p-4 translate-y-2 group-hover:translate-y-0 opacity-0 group-hover:opacity-100 transition-all duration-300">
                            <p className="text-white text-sm font-medium">{img.title}</p>
                          </div>
                        )}
                        {img.sport && (
                          <div className="absolute top-2 right-2">
                            <span className="text-[10px] bg-white/90 text-gray-700 px-2 py-0.5 rounded-full font-medium backdrop-blur-sm">
                              {img.sport.name}
                            </span>
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                </div>
              );
            })}

            {filtered.length === 0 && (
              <div className="text-center py-20">
                <div className="w-16 h-16 mx-auto mb-4 rounded-2xl bg-gray-100 flex items-center justify-center">
                  <ImageIcon className="h-8 w-8 text-gray-400" />
                </div>
                <p className="text-gray-500">تصویری یافت نشد</p>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}
