'use client';

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

interface Member {
  id: number;
  name: string;
  role: string;
  qualification: string | null;
  image_url: string;
  is_head: boolean;
  order: number;
}

interface TabData {
  head: Member | null;
  members: Member[];
}

interface FamilyData {
  science: TabData;
  farm: TabData;
  allied: TabData;
}

const TAB_CONFIG = {
  science: { id: 'science', icon: 'fa-microscope', label: 'Science & Innovation',  headIcon: 'fa-star'      },
  farm:    { id: 'farm',    icon: 'fa-tractor',    label: 'Farm, Feed Mill & QC',   headIcon: 'fa-tractor'   },
  allied:  { id: 'allied',  icon: 'fa-briefcase',  label: 'Allied Services',         headIcon: 'fa-briefcase' },
} as const;

type TabKey = keyof typeof TAB_CONFIG;
const TAB_KEYS = Object.keys(TAB_CONFIG) as TabKey[];

export default function AgrivetFamily() {
  const [data, setData] = useState<FamilyData | null>(null);
  const [loading, setLoading] = useState(true);
  const [mobileIdx, setMobileIdx] = useState(0);
  const carouselRef = useRef<HTMLDivElement>(null);
  const programmatic = useRef(false);
  const total = TAB_KEYS.length;

  useEffect(() => {
    const apiBaseUrl = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost/agrivet_web/backend';
    fetch(`${apiBaseUrl}/api/homepage/family`)
      .then((res) => res.json())
      .then((result) => {
        if (result.success && result.data) setData(result.data);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    const el = carouselRef.current;
    if (!el) return;
    programmatic.current = true;
    el.scrollTo({ left: mobileIdx * el.offsetWidth, behavior: 'smooth' });
    const t = setTimeout(() => { programmatic.current = false; }, 500);
    return () => clearTimeout(t);
  }, [mobileIdx]);

  useEffect(() => {
    const el = carouselRef.current;
    if (!el) return;
    const onScroll = () => {
      if (programmatic.current) return;
      setMobileIdx(Math.round(el.scrollLeft / el.offsetWidth));
    };
    el.addEventListener('scroll', onScroll, { passive: true });
    return () => el.removeEventListener('scroll', onScroll);
  }, []);

  const prevSlide = useCallback(() => setMobileIdx((i) => Math.max(0, i - 1)), []);
  const nextSlide = useCallback(() => setMobileIdx((i) => Math.min(total - 1, i + 1)), [total]);

  if (loading) {
    return (
      <section className="agrivet-family" id="family" style={{ minHeight: '60vh', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
        <div style={{ color: '#52b788', fontSize: '3rem', animation: 'op-spin 1s linear infinite' }}>
          <i className="fas fa-spinner"></i>
        </div>
      </section>
    );
  }

  if (!data) return null;

  return (
    <section className="agrivet-family" id="family">
      <div className="family-bg" aria-hidden="true">
        <div className="family-blob family-blob-1"></div>
        <div className="family-blob family-blob-2"></div>
      </div>
      <div className="container">
        <div className="section-header center">
          <div className="section-eyebrow">Our People</div>
          <h2 className="section-title">The Agrivet <em>Family</em></h2>
          <p className="section-desc">
            The brilliant minds and dedicated hands that power every breakthrough, every day.
          </p>
        </div>

        {/* Desktop: 3-column horizontal layout */}
        <div className="fam-cols">
          {TAB_KEYS.map((key) => {
            const t = TAB_CONFIG[key];
            const d = data[key];
            return (
              <div key={key} className="fam-col-card">
                <div className="fam-col-header">
                  <div className="fam-col-icon">
                    <i className={`fas ${t.icon}`} />
                  </div>
                  <span className="fam-col-label">{t.label}</span>
                </div>
                {d.head && (
                  <>
                    <div className="fam-col-img-wrap">
                      <img src={d.head.image_url} alt={d.head.name} />
                    </div>
                    <div className="fam-col-info">
                      <div className="fam-hl-badge">
                        <i className={`fas ${t.headIcon}`}></i> {d.head.role}
                      </div>
                      <h3>{d.head.name}</h3>
                      {d.head.qualification && <p>{d.head.qualification}</p>}
                    </div>
                  </>
                )}
                <Link href={`/our-people/${key}`} className="fam-view-link">
                  Meet the full team <i className="fas fa-arrow-right"></i>
                </Link>
              </div>
            );
          })}
        </div>

        {/* Mobile: swipe carousel */}
        <div className="fam-mobile-carousel">
          <div className="fam-carousel-track" ref={carouselRef}>
            {TAB_KEYS.map((key) => {
              const t = TAB_CONFIG[key];
              const d = data[key];
              return (
                <div key={key} className="fam-carousel-slide">
                  <div className="fam-slide-label">
                    <i className={`fas ${t.icon}`}></i> {t.label}
                  </div>
                  {d.head && (
                    <div className="fam-slide-head">
                      <img src={d.head.image_url} alt={d.head.name} />
                      <div className="fam-slide-info">
                        <div className="fam-hl-badge">
                          <i className={`fas ${t.headIcon}`}></i> {d.head.role}
                        </div>
                        <h3>{d.head.name}</h3>
                        {d.head.qualification && <p>{d.head.qualification}</p>}
                      </div>
                    </div>
                  )}
                  <Link href={`/our-people/${key}`} className="fam-view-link">
                    Meet the full team <i className="fas fa-arrow-right"></i>
                  </Link>
                </div>
              );
            })}
          </div>
          <div className="fam-nav-row">
            <button className="fam-arrow fam-arrow-prev" onClick={prevSlide} disabled={mobileIdx === 0} aria-label="Previous">&#8249;</button>
            <div className="fam-dots">
              {TAB_KEYS.map((key, i) => (
                <button key={key} className={`fam-dot${i === mobileIdx ? ' active' : ''}`} onClick={() => setMobileIdx(i)} aria-label={`Slide ${i + 1}`} />
              ))}
            </div>
            <button className="fam-arrow fam-arrow-next" onClick={nextSlide} disabled={mobileIdx === total - 1} aria-label="Next">&#8250;</button>
          </div>
        </div>
      </div>
    </section>
  );
}
