'use client';

import { useState, useEffect, useRef, useCallback } from 'react';

interface ApartItem {
  id: number;
  icon: string;
  title: string;
  description: string;
  order: number;
}

interface ApartSection {
  eyebrow: string;
  title_regular: string;
  title_emphasized: string;
  description: string;
}

interface ApartData {
  section: ApartSection;
  items: ApartItem[];
}

export default function Apart() {
  const [apartData, setApartData] = useState<ApartData | null>(null);
  const [loading, setLoading] = useState(true);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [perView, setPerView] = useState(5);
  const [mounted, setMounted] = useState(false);
  const [isPaused, setIsPaused] = useState(false);
  const trackRef = useRef<HTMLDivElement>(null);
  const autoPlayRef = useRef<ReturnType<typeof setInterval> | null>(null);

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

  const fetchApartData = async () => {
    try {
      const apiBaseUrl = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost/agrivet_web/backend';
      const response = await fetch(`${apiBaseUrl}/api/homepage/apart`);
      const result = await response.json();
      
      if (result.success && result.data) {
        setApartData(result.data);
      }
    } catch (error) {
      console.error('Error fetching apart data:', error);
    } finally {
      setLoading(false);
    }
  };

  const getPerView = () => {
    if (typeof window === 'undefined') return 5;
    const w = window.innerWidth;
    if (w <= 400) return 1;
    if (w <= 540) return 1;
    if (w <= 768) return 2;
    if (w <= 1024) return 3;
    if (w <= 1200) return 4;
    return 5;
  };

  const maxIndex = apartData ? Math.max(0, apartData.items.length - perView) : 0;

  useEffect(() => {
    setMounted(true);
    const handleResize = () => {
      const newPerView = getPerView();
      if (newPerView !== perView) {
        setPerView(newPerView);
        setCurrentIndex(0);
      }
    };

    handleResize();
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, [perView]);

  useEffect(() => {
    if (!trackRef.current || !apartData) return;
    const cardWidth = 100 / perView;
    const offset = -(currentIndex * cardWidth);
    trackRef.current.style.transform = `translateX(${offset}%)`;
  }, [currentIndex, perView, apartData]);

  const handlePrev = () => {
    setCurrentIndex((prev) => (prev <= 0 ? maxIndex : prev - 1));
  };

  const handleNext = useCallback(() => {
    setCurrentIndex((prev) => (prev >= maxIndex ? 0 : prev + 1));
  }, [maxIndex]);

  // Auto-play
  useEffect(() => {
    if (!apartData || isPaused) return;
    autoPlayRef.current = setInterval(handleNext, 3500);
    return () => { if (autoPlayRef.current) clearInterval(autoPlayRef.current); };
  }, [apartData, isPaused, handleNext]);

  // Show loading spinner
  if (loading) {
    return (
      <section className="apart" id="apart" style={{
        minHeight: '100vh',
        background: 'linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%)',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center'
      }}>
        <div style={{ textAlign: 'center' }}>
          <div style={{ 
            fontSize: '4rem',
            color: '#52b788',
            animation: 'spin 1s linear infinite'
          }}>
            <i className="fas fa-spinner"></i>
          </div>
        </div>
        <style jsx>{`
          @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
          }
        `}</style>
      </section>
    );
  }

  // If no data, don't render
  if (!apartData || !apartData.items || apartData.items.length === 0) {
    return null;
  }

  const { section, items } = apartData;
  const currentEnd = Math.min(currentIndex + perView, items.length);

  return (
    <section className="apart" id="apart">
      <div className="apart-deco" aria-hidden="true">
        <svg viewBox="0 0 400 500" fill="none">
          <path d="M200 20C90 90 40 200 80 340C120 480 280 480 320 340C360 200 310 90 200 20Z" fill="url(#adg)" opacity="0.05"/>
          <defs>
            <linearGradient id="adg" x1="0" y1="0" x2="400" y2="500">
              <stop offset="0%" stopColor="#52b788"/>
              <stop offset="100%" stopColor="#c9a84c"/>
            </linearGradient>
          </defs>
        </svg>
      </div>
      <div className="container-apart">
        <div className="section-header center">
          <div className="section-eyebrow">{section.eyebrow}</div>
          <h2 className="section-title">
            {section.title_regular} <em>{section.title_emphasized}</em>
          </h2>
          <p className="section-desc">{section.description}</p>
        </div>

        <div
          className="apart-carousel-outer"
          onMouseEnter={() => setIsPaused(true)}
          onMouseLeave={() => setIsPaused(false)}
        >
          <button
            className="apart-btn apart-prev"
            onClick={handlePrev}
            aria-label="Previous"
          >
            <i className="fas fa-chevron-left"></i>
          </button>
          <div className="apart-track-wrap">
            <div className="apart-track" ref={trackRef}>
              {items.map((item, index) => (
                <div className="apart-card" key={item.id}>
                  <div className="apart-card-inner">
                    <div className="apart-num">{String(index + 1).padStart(2, '0')}</div>
                    <div className="apart-icon-box">
                      <i className={`fas ${item.icon}`}></i>
                    </div>
                    <h3>{item.title}</h3>
                    <p>{item.description}</p>
                    <div className="apart-line"></div>
                  </div>
                </div>
              ))}
            </div>
          </div>
          <button
            className="apart-btn apart-next"
            onClick={handleNext}
            aria-label="Next"
          >
            <i className="fas fa-chevron-right"></i>
          </button>
        </div>

        {/* Dot indicators */}
        <div className="apart-dots">
          {Array.from({ length: maxIndex + 1 }).map((_, i) => (
            <button
              key={i}
              className={`apart-dot${i === currentIndex ? ' apart-dot--active' : ''}`}
              onClick={() => setCurrentIndex(i)}
              aria-label={`Go to slide ${i + 1}`}
            />
          ))}
        </div>
      </div>
    </section>
  );
}
