import { useState, useEffect, useRef, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { fetchEquipment, fetchCategories } from '../api/equipment';
import type { EquipmentItem, SortOption, PaginatedEquipment } from '../types';
import { useCart } from '../store/CartContext';
import EquipmentCard from '../components/EquipmentCard';
import LoadingSkeleton from '../components/LoadingSkeleton';
import ErrorState from '../components/ErrorState';
import EmptyState from '../components/EmptyState';

export default function Mietkatalog() {
  const navigate = useNavigate();
  const { addItemByFields } = useCart();
  const [searchQuery, setSearchQuery] = useState('');
  const [activeCategory, setActiveCategory] = useState('alle');
  const [sortBy, setSortBy] = useState<SortOption>('name_asc');
  const [currentPage, setCurrentPage] = useState(1);
  const [categories, setCategories] = useState<string[]>(['alle']);
  const [data, setData] = useState<PaginatedEquipment | null>(null);
  const [pending, setPending] = useState(true);
  const [error, setError] = useState(false);
  const searchTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
  const mountedRef = useRef(true);

  const load = useCallback(async () => {
    setPending(true);
    setError(false);
    try {
      const result = await fetchEquipment({
        search: searchQuery.trim() || undefined,
        category: activeCategory !== 'alle' ? activeCategory : undefined,
        sort: sortBy,
        page: currentPage,
        page_size: 24,
      });
      if (mountedRef.current) {
        setData(result);
        setPending(false);
      }
    } catch (e) {
      if (mountedRef.current) {
        setError(true);
        setPending(false);
      }
    }
  }, [searchQuery, activeCategory, sortBy, currentPage]);

  useEffect(() => {
    mountedRef.current = true;
    load();
    return () => { mountedRef.current = false; };
  }, [load]);

  useEffect(() => {
    fetchCategories().then(cats => {
      if (cats && cats.length > 0 && mountedRef.current) {
        setCategories(['alle', ...cats.filter(c => c && c.trim() !== '')]);
      }
    }).catch(() => {});
  }, []);

  function onSearchInput() {
    if (searchTimeout.current) clearTimeout(searchTimeout.current);
    searchTimeout.current = setTimeout(() => {
      setCurrentPage(1);
      load();
    }, 300);
  }

  function reload() {
    load();
  }

  function navigateTo(route: string) {
    navigate(route);
    window.scrollTo(0, 0);
  }

  function navigateToDetail(item: any) {
    navigate('/mietkatalog/' + item.id);
    window.scrollTo(0, 0);
  }

  function addToCart(item: any) {
    addItemByFields({
      equipment_id: item.id,
      name: item.name,
      rental_price: null,
      image_url: item.image_url || null,
    });
  }

  function mapItem(item: EquipmentItem) {
    return {
      ...item,
      code: item.number || item.rentman_id,
      image: item.image_url || '',
    };
  }

  const equipment = data?.items || [];
  const total = data?.total || 0;
  const totalPages = data?.total_pages || 0;

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
      <div className="flex flex-col sm:flex-row sm:items-end sm:justify-between gap-4 mb-8">
        <div>
          <h1 className="text-3xl sm:text-4xl font-bold mb-2" style={{ color: 'var(--text)' }}>Mietkatalog</h1>
          <p style={{ color: 'var(--secondary)' }}>Durchsuchen Sie unser Equipment-Sortiment und stellen Sie Ihre Mietanfrage zusammen.</p>
        </div>
        <button onClick={() => navigateTo('/warenkorb')} className="hms-btn hms-btn-secondary text-sm self-start sm:self-auto">🛒 Warenkorb ansehen</button>
      </div>
      <div className="hms-card p-4 mb-6">
        <div className="flex flex-col lg:flex-row gap-4">
          <div className="relative flex-1">
            <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5" style={{ color: 'var(--secondary)' }} fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>
            <input value={searchQuery} onChange={e => { setSearchQuery(e.target.value); onSearchInput(); }} type="search" className="hms-input pl-10" placeholder="Gerät, Marke oder Artikelnummer suchen..." aria-label="Equipment suchen" />
          </div>
          <select value={sortBy} onChange={e => { setSortBy(e.target.value as SortOption); setCurrentPage(1); reload(); }} className="hms-input lg:w-48" aria-label="Sortieren nach">
            <option value="name_asc">Sortieren: Name (A-Z)</option>
            <option value="name_desc">Sortieren: Name (Z-A)</option>
          </select>
        </div>
        {categories.length > 1 && (
          <div className="flex flex-wrap gap-2 mt-4" role="tablist" aria-label="Kategorie-Filter">
            {categories.map(cat => (
              <button key={cat} onClick={() => { setActiveCategory(cat); setCurrentPage(1); reload(); }}
                className={`hms-chip ${activeCategory === cat ? 'active' : ''}`} role="tab" aria-selected={activeCategory === cat}>
                {cat === 'alle' ? 'Alle Kategorien' : cat}
              </button>
            ))}
          </div>
        )}
      </div>
      {!pending && !error && (
        <div className="text-sm mb-4" style={{ color: 'var(--secondary)' }} aria-live="polite">{total} {total === 1 ? 'Gerät' : 'Geräte'} gefunden</div>
      )}
      {pending && <LoadingSkeleton count={6} />}
      {error && <ErrorState title="Katalog nicht erreichbar" message="Der Equipment-Katalog ist aktuell nicht verfügbar." onRetry={reload} />}
      {!pending && !error && equipment.length === 0 && (
        <EmptyState icon="🔍" title="Keine Geräte gefunden" message="Für Ihre Suchanfrage wurden keine Geräte gefunden." actionLabel="Filter zurücksetzen" onAction={() => { setSearchQuery(''); setActiveCategory('alle'); setCurrentPage(1); reload(); }} />
      )}
      {!pending && !error && equipment.length > 0 && (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
          {equipment.map(item => (
            <EquipmentCard key={item.id} item={mapItem(item)} onClick={navigateToDetail} onAddToCart={addToCart} />
          ))}
        </div>
      )}
      {totalPages > 1 && (
        <div className="flex items-center justify-center gap-2 mt-8">
          <button disabled={currentPage <= 1} onClick={() => { setCurrentPage(c => c - 1); reload(); }} className="hms-btn hms-btn-secondary px-4 py-2 disabled:opacity-40" aria-label="Vorherige Seite">←</button>
          <span className="text-sm" style={{ color: 'var(--secondary)' }}>Seite {currentPage} von {totalPages}</span>
          <button disabled={currentPage >= totalPages} onClick={() => { setCurrentPage(c => c + 1); reload(); }} className="hms-btn hms-btn-secondary px-4 py-2 disabled:opacity-40" aria-label="Nächste Seite">→</button>
        </div>
      )}
    </div>
  );
}
