import React, { useState, useEffect, useCallback } from 'react';
import { AuthProvider, AuthGuard, useAuth } from './AdminAuth';
import AdminLayout from './AdminLayout';

interface Product {
  id: number;
  name: string;
  slug: string;
  brand: string;
  image_url: string | null;
  cutout_image_url: string | null;
  is_sneaker: boolean;
  lowest_price: number;
  offer_count: number;
  created_at: string;
}

function ProductTableContent() {
  const { token } = useAuth();
  const [products, setProducts] = useState<Product[]>([]);
  const [brands, setBrands] = useState<{ brand: string; count: number }[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [selected, setSelected] = useState<Set<number>>(new Set());

  // Filters
  const [search, setSearch] = useState('');
  const [brandFilter, setBrandFilter] = useState('');
  const [sneakerFilter, setSneakerFilter] = useState('');
  const [cutoutFilter, setCutoutFilter] = useState('');
  const [sortBy, setSortBy] = useState('created_at');
  const [sortDir, setSortDir] = useState('desc');
  const [page, setPage] = useState(1);
  const limit = 50;

  const headers = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' };

  const loadProducts = useCallback(() => {
    setLoading(true);
    const params = new URLSearchParams({
      page: String(page), limit: String(limit),
      sort: sortBy, dir: sortDir,
    });
    if (search) params.set('search', search);
    if (brandFilter) params.set('brand', brandFilter);
    if (sneakerFilter) params.set('is_sneaker', sneakerFilter);
    if (cutoutFilter) params.set('has_cutout', cutoutFilter);

    fetch(`/api/admin/products?${params}`, { headers: { Authorization: `Bearer ${token}` } })
      .then(r => r.json())
      .then(d => {
        setProducts(d.products || []);
        setTotal(d.total || 0);
        if (d.brands) setBrands(d.brands);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [token, page, search, brandFilter, sneakerFilter, cutoutFilter, sortBy, sortDir]);

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

  // Debounce search
  const [searchInput, setSearchInput] = useState('');
  useEffect(() => {
    const t = setTimeout(() => { setSearch(searchInput); setPage(1); }, 300);
    return () => clearTimeout(t);
  }, [searchInput]);

  const toggleSelect = (id: number) => {
    setSelected(prev => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; });
  };

  const toggleAll = () => {
    if (selected.size === products.length) setSelected(new Set());
    else setSelected(new Set(products.map(p => p.id)));
  };

  const bulkUpdate = async (field: string, value: any) => {
    await fetch('/api/admin/products', {
      method: 'PUT', headers,
      body: JSON.stringify({ ids: [...selected], [field]: value }),
    });
    setSelected(new Set());
    loadProducts();
  };

  const toggleSneaker = async (product: Product) => {
    await fetch('/api/admin/products', {
      method: 'PUT', headers,
      body: JSON.stringify({ id: product.id, is_sneaker: !product.is_sneaker }),
    });
    setProducts(prev => prev.map(p => p.id === product.id ? { ...p, is_sneaker: !p.is_sneaker } : p));
  };

  const handleSort = (col: string) => {
    if (sortBy === col) setSortDir(d => d === 'asc' ? 'desc' : 'asc');
    else { setSortBy(col); setSortDir('desc'); }
    setPage(1);
  };

  const totalPages = Math.ceil(total / limit);
  const sortIcon = (col: string) => sortBy === col ? (sortDir === 'asc' ? ' ↑' : ' ↓') : '';

  return (
    <AdminLayout title="Products">
      <div className="flex flex-wrap gap-3 mb-6">
        <input type="text" placeholder="Zoeken op naam of merk..." value={searchInput} onChange={e => setSearchInput(e.target.value)}
          className="bg-[#141414] border border-[#333] rounded-lg px-4 py-2 text-sm text-[#F5F5F5] focus:outline-none focus:border-[#00FF6A] flex-1 min-w-[200px] max-w-md" />
        <select value={brandFilter} onChange={e => { setBrandFilter(e.target.value); setPage(1); }}
          className="bg-[#141414] border border-[#333] rounded-lg px-3 py-2 text-sm text-[#999]">
          <option value="">Alle merken</option>
          {brands.map(b => <option key={b.brand} value={b.brand}>{b.brand} ({b.count})</option>)}
        </select>
        <select value={sneakerFilter} onChange={e => { setSneakerFilter(e.target.value); setPage(1); }}
          className="bg-[#141414] border border-[#333] rounded-lg px-3 py-2 text-sm text-[#999]">
          <option value="">Sneaker: Alles</option>
          <option value="true">Alleen sneakers</option>
          <option value="false">Geen sneakers</option>
        </select>
        <select value={cutoutFilter} onChange={e => { setCutoutFilter(e.target.value); setPage(1); }}
          className="bg-[#141414] border border-[#333] rounded-lg px-3 py-2 text-sm text-[#999]">
          <option value="">Cutout: Alles</option>
          <option value="true">Met cutout</option>
          <option value="false">Zonder cutout</option>
        </select>
      </div>

      {selected.size > 0 && (
        <div className="flex gap-2 mb-4 items-center">
          <span className="text-sm text-[#999]">{selected.size} geselecteerd</span>
          <button onClick={() => bulkUpdate('is_sneaker', true)}
            className="text-xs bg-[#00FF6A]/10 border border-[#00FF6A]/20 px-3 py-1 rounded text-[#00FF6A] hover:bg-[#00FF6A]/20">
            ✓ Markeer als sneaker
          </button>
          <button onClick={() => bulkUpdate('is_sneaker', false)}
            className="text-xs bg-[#FF3B3B]/10 border border-[#FF3B3B]/20 px-3 py-1 rounded text-[#FF3B3B] hover:bg-[#FF3B3B]/20">
            ✗ Niet-sneaker
          </button>
          <button onClick={() => setSelected(new Set())} className="text-xs text-[#666] hover:text-[#999] ml-2">Deselecteer</button>
        </div>
      )}

      {loading ? (
        <div className="text-[#666] text-center py-12">Laden...</div>
      ) : products.length === 0 ? (
        <div className="bg-[#141414] border border-[#333] rounded-xl p-8 text-center">
          <div className="text-[#666] text-lg mb-2">📦</div>
          <div className="text-[#999] text-sm">Geen producten gevonden</div>
        </div>
      ) : (
        <div className="bg-[#141414] border border-[#333] rounded-xl overflow-hidden overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-[#333] text-[#999] text-left">
                <th className="px-4 py-3 w-8">
                  <input type="checkbox" onChange={toggleAll} checked={selected.size === products.length && products.length > 0} className="accent-[#00FF6A]" />
                </th>
                <th className="px-4 py-3 font-medium">Product</th>
                <th className="px-4 py-3 font-medium cursor-pointer hover:text-[#F5F5F5]" onClick={() => handleSort('name')}>
                  Merk{sortIcon('name')}
                </th>
                <th className="px-4 py-3 font-medium cursor-pointer hover:text-[#F5F5F5]" onClick={() => handleSort('price')}>
                  Laagste prijs{sortIcon('price')}
                </th>
                <th className="px-4 py-3 font-medium cursor-pointer hover:text-[#F5F5F5]" onClick={() => handleSort('offers')}>
                  Aanbiedingen{sortIcon('offers')}
                </th>
                <th className="px-4 py-3 font-medium">Sneaker</th>
                <th className="px-4 py-3 font-medium">Cutout</th>
              </tr>
            </thead>
            <tbody>
              {products.map(p => (
                <tr key={p.id} className="border-b border-[#222] hover:bg-[#1A1A1A] transition-colors">
                  <td className="px-4 py-3">
                    <input type="checkbox" checked={selected.has(p.id)} onChange={() => toggleSelect(p.id)} className="accent-[#00FF6A]" />
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-3">
                      {p.image_url ? (
                        <img src={p.image_url} alt="" className="w-10 h-10 rounded-lg object-cover bg-[#1A1A1A]" loading="lazy" />
                      ) : (
                        <div className="w-10 h-10 bg-[#1A1A1A] rounded-lg flex items-center justify-center text-[#666] text-xs">?</div>
                      )}
                      <span className="text-[#F5F5F5] font-medium truncate max-w-[250px]">{p.name}</span>
                    </div>
                  </td>
                  <td className="px-4 py-3 text-[#999]">{p.brand || '-'}</td>
                  <td className="px-4 py-3 text-[#F5F5F5]">
                    {Number(p.lowest_price) > 0 ? `€${Number(p.lowest_price).toFixed(2)}` : '-'}
                  </td>
                  <td className="px-4 py-3 text-[#999]">{p.offer_count}</td>
                  <td className="px-4 py-3">
                    <button onClick={() => toggleSneaker(p)}
                      className={`text-xs px-2 py-1 rounded transition-colors ${p.is_sneaker ? 'bg-[#00FF6A]/10 text-[#00FF6A]' : 'bg-[#333] text-[#666] hover:text-[#999]'}`}>
                      {p.is_sneaker ? '👟 Ja' : 'Nee'}
                    </button>
                  </td>
                  <td className="px-4 py-3">
                    {p.cutout_image_url ? (
                      <span className="text-xs text-[#00FF6A]">✓</span>
                    ) : (
                      <span className="text-xs text-[#666]">✗</span>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      <div className="flex items-center justify-between mt-4 text-sm text-[#999]">
        <span>{total.toLocaleString()} producten</span>
        <div className="flex gap-2 items-center">
          <button onClick={() => setPage(Math.max(1, page - 1))} disabled={page <= 1}
            className="px-3 py-1 bg-[#141414] border border-[#333] rounded hover:bg-[#1A1A1A] disabled:opacity-30">← Vorige</button>
          <span className="px-3 py-1">Pagina {page} / {totalPages || 1}</span>
          <button onClick={() => setPage(Math.min(totalPages, page + 1))} disabled={page >= totalPages}
            className="px-3 py-1 bg-[#141414] border border-[#333] rounded hover:bg-[#1A1A1A] disabled:opacity-30">Volgende →</button>
        </div>
      </div>
    </AdminLayout>
  );
}

export default function ProductTablePage() {
  return <AuthProvider><AuthGuard><ProductTableContent /></AuthGuard></AuthProvider>;
}
