'use client';

import { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';

interface GalleryCategory { id: number; name: string; slug: string; }
interface GalleryItem { id: number; title: string | null; image_url: string; category: GalleryCategory | null; }

export default function GalleryPage() {
  const [categories, setCategories] = useState<GalleryCategory[]>([]);
  const [items, setItems] = useState<GalleryItem[]>([]);
  const [activeCategory, setActiveCategory] = useState<string>('all');
  const [centerIndex, setCenterIndex] = useState(0);
  const [loading, setLoading] = useState(true);

  const API = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost/agrivet_web/backend';

  useEffect(() => {
    fetch(`${API}/api/homepage/gallery/categories`)
      .then(r => r.json())
      .then(res => { if (res.success) setCategories(res.data); })
      .catch(() => {});
  }, []);

  useEffect(() => {
    setLoading(true);
    const url = activeCategory === 'all'
      ? `${API}/api/homepage/gallery/items`
      : `${API}/api/homepage/gallery/items?category=${activeCategory}`;
    fetch(url)
      .then(r => r.json())
      .then(res => { if (res.success) { setItems(res.data); setCenterIndex(0); } })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [activeCategory]);

  const prev = useCallback(() => setCenterIndex(i => (i - 1 + items.length) % items.length), [items.length]);
  const next = useCallback(() => setCenterIndex(i => (i + 1) % items.length), [items.length]);

  const getPos = (idx: number) => {
    if (items.length === 0) return 99;
    let diff = idx - centerIndex;
    if (diff > items.length / 2) diff -= items.length;
    if (diff < -items.length / 2) diff += items.length;
    return diff;
  };

  const visibleItems = items.map((item, idx) => ({ ...item, idx, pos: getPos(idx) }))
    .filter(i => Math.abs(i.pos) <= 2);

  return (
    <>
      <div className="op-hero" style={{ background: 'linear-gradient(135deg,rgba(6,18,10,.92) 0%,rgba(10,30,18,.72) 60%,rgba(8,24,14,.55) 100%), url(\'/images/agrivet-research.webp\') center/cover no-repeat' }}>
        <div className="op-hero-deco" aria-hidden="true">
          <svg className="deco-leaf-1" viewBox="0 0 200 300" fill="none">
            <path d="M100 10 C160 40 190 120 160 200 C130 280 40 290 20 220 C0 150 40 80 100 10Z" fill="#7abf9e"/>
            <path d="M100 50 C140 70 160 130 140 190 C120 250 60 260 40 200" stroke="#a9d4bc" strokeWidth="1.5" fill="none"/>
          </svg>
          <svg className="deco-leaf-2" viewBox="0 0 200 300" fill="none">
            <path d="M100 10 C160 40 190 120 160 200 C130 280 40 290 20 220 C0 150 40 80 100 10Z" fill="#7abf9e"/>
          </svg>
        </div>
        <div className="container op-hero-inner">
          <nav className="op-breadcrumb" aria-label="Breadcrumb">
            <Link href="/" className="op-bc-item">Home</Link>
            <span className="op-bc-sep" aria-hidden="true">/</span>
            <span className="op-bc-item active">Gallery</span>
          </nav>
          <h1>Agrivet in <em>Pictures</em></h1>
        </div>
        <div className="op-hero-wave" aria-hidden="true">
          <svg viewBox="0 0 1440 60" preserveAspectRatio="none" fill="#ffffff">
            <path d="M0,40 C360,70 1080,10 1440,40 L1440,60 L0,60Z"/>
          </svg>
        </div>
      </div>

      <section className="gal-section">
        <div className="container">
          <div className="gal-filters">
            <button className={`gal-filter-pill${activeCategory === 'all' ? ' active' : ''}`} onClick={() => setActiveCategory('all')}>All</button>
            {categories.map(cat => (
              <button key={cat.id} className={`gal-filter-pill${activeCategory === cat.slug ? ' active' : ''}`} onClick={() => setActiveCategory(cat.slug)}>{cat.name}</button>
            ))}
          </div>

          {loading ? (
            <div className="gal-loading"><i className="fas fa-spinner" style={{ animation: 'op-spin 1s linear infinite' }} /></div>
          ) : items.length === 0 ? (
            <div className="gal-empty"><i className="fas fa-images" /><p>No photos in this category yet.</p></div>
          ) : (
            <>
              <div className="gal-fan-stage">
                {visibleItems.map(item => (
                  <div
                    key={item.id}
                    className={`gal-fan-card gal-pos-${item.pos < 0 ? 'n' + Math.abs(item.pos) : item.pos}`}
                    onClick={() => item.pos !== 0 && setCenterIndex(item.idx)}
                    style={{ cursor: item.pos !== 0 ? 'pointer' : 'default' }}
                  >
                    <img src={item.image_url} alt={item.title || 'Gallery photo'} />
                    {item.pos === 0 && item.title && <div className="gal-fan-caption">{item.title}</div>}
                  </div>
                ))}
              </div>

              <div className="gal-nav-row">
                <button className="gal-nav-btn" onClick={prev} aria-label="Previous"><i className="fas fa-arrow-left" /></button>
                <span className="gal-nav-count">{centerIndex + 1} / {items.length}</span>
                <button className="gal-nav-btn" onClick={next} aria-label="Next"><i className="fas fa-arrow-right" /></button>
              </div>
            </>
          )}
        </div>
      </section>
    </>
  );
}
