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

const EU_SIZES = ['36', '37', '37.5', '38', '38.5', '39', '40', '40.5', '41', '42', '42.5', '43', '44', '44.5', '45', '46', '47', '48'];

interface SizePreference {
  brand_slug: string;
  size: string;
  subtypes: { category_slug: string; size: string }[];
}

interface BrandResult {
  name: string;
  slug: string;
  count?: number;
}

interface ModelResult {
  name: string;
  slug: string;
  brand_slug: string;
}

export default function AdvancedSizesSection() {
  const [preferences, setPreferences] = useState<SizePreference[]>([]);
  const [loading, setLoading] = useState(true);
  const [showBrandSearch, setShowBrandSearch] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<BrandResult[]>([]);
  const [popularBrands, setPopularBrands] = useState<BrandResult[]>([]);
  const [searching, setSearching] = useState(false);
  const [expandedBrand, setExpandedBrand] = useState<string | null>(null);
  const [subtypeResults, setSubtypeResults] = useState<ModelResult[]>([]);
  const [loadingSubtypes, setLoadingSubtypes] = useState(false);
  const debounceRef = useRef<ReturnType<typeof setTimeout>>();

  useEffect(() => {
    Promise.all([
      fetch('/api/user/size-preferences', { credentials: 'include' })
        .then(r => r.json())
        .then(data => setPreferences(data.preferences || []))
        .catch(() => {}),
      fetch('/api/search/suggest?popular=1', { credentials: 'include' })
        .then(r => r.json())
        .then(data => {
          if (data.brands) {
            setPopularBrands(data.brands.map((b: any) => ({
              name: b.name,
              slug: b.slug.toLowerCase(),
              count: b.count,
            })));
          }
        })
        .catch(() => {}),
    ]).finally(() => setLoading(false));
  }, []);

  // Live search brands as user types
  useEffect(() => {
    if (!showBrandSearch) return;
    if (searchQuery.length < 2) {
      setSearchResults([]);
      return;
    }

    clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(async () => {
      setSearching(true);
      try {
        const res = await fetch(`/api/search/suggest?q=${encodeURIComponent(searchQuery)}`, { credentials: 'include' });
        const data = await res.json();
        if (data.brands) {
          setSearchResults(
            data.brands
              .map((b: any) => ({ name: b.name, slug: b.slug.toLowerCase(), count: b.count }))
              .filter((b: any) => !preferences.some(p => p.brand_slug === b.slug))
          );
        }
      } catch {}
      setSearching(false);
    }, 250);

    return () => clearTimeout(debounceRef.current);
  }, [searchQuery, showBrandSearch, preferences]);

  // Load subtypes when expanding a brand
  async function loadSubtypes(brandSlug: string) {
    if (expandedBrand === brandSlug) {
      setExpandedBrand(null);
      return;
    }
    setExpandedBrand(brandSlug);
    setLoadingSubtypes(true);
    try {
      const res = await fetch(`/api/search/suggest?q=${encodeURIComponent(brandSlug)}`, { credentials: 'include' });
      const data = await res.json();
      const models = (data.models || [])
        .filter((m: any) => m.brand_slug === brandSlug)
        .map((m: any) => ({ name: m.name, slug: m.slug, brand_slug: m.brand_slug }));
      setSubtypeResults(models);
    } catch {
      setSubtypeResults([]);
    }
    setLoadingSubtypes(false);
  }

  async function addSubtype(brandSlug: string, modelSlug: string, modelName: string) {
    const pref = preferences.find(p => p.brand_slug === brandSlug);
    const size = pref?.size || '44';
    const categorySlug = `${brandSlug}/${modelSlug}`;
    const res = await fetch('/api/user/size-preferences', {
      method: 'POST',
      credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ brand_slug: brandSlug, category_slug: categorySlug, size }),
    });
    if (res.ok) {
      setPreferences(preferences.map(p =>
        p.brand_slug === brandSlug
          ? { ...p, subtypes: [...p.subtypes, { category_slug: categorySlug, size }] }
          : p
      ));
    }
  }

  async function addBrand(brandSlug: string) {
    const size = '44';
    const res = await fetch('/api/user/size-preferences', {
      method: 'POST',
      credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ brand_slug: brandSlug, size }),
    });
    if (res.ok) {
      setPreferences([...preferences, { brand_slug: brandSlug, size, subtypes: [] }]);
      setShowBrandSearch(false);
      setSearchQuery('');
      setSearchResults([]);
    }
  }

  async function updateSize(brandSlug: string, newSize: string, categorySlug?: string) {
    const res = await fetch('/api/user/size-preferences', {
      method: 'POST',
      credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ brand_slug: brandSlug, category_slug: categorySlug || null, size: newSize }),
    });
    if (res.ok) {
      if (categorySlug) {
        setPreferences(preferences.map(p =>
          p.brand_slug === brandSlug
            ? { ...p, subtypes: p.subtypes.map(s => s.category_slug === categorySlug ? { ...s, size: newSize } : s) }
            : p
        ));
      } else {
        setPreferences(preferences.map(p => p.brand_slug === brandSlug ? { ...p, size: newSize } : p));
      }
    }
  }

  async function deleteSize(brandSlug: string, categorySlug?: string) {
    const res = await fetch('/api/user/size-preferences', {
      method: 'DELETE',
      credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ brand_slug: brandSlug, category_slug: categorySlug || null }),
    });
    if (res.ok) {
      if (categorySlug) {
        setPreferences(preferences.map(p =>
          p.brand_slug === brandSlug
            ? { ...p, subtypes: p.subtypes.filter(s => s.category_slug !== categorySlug) }
            : p
        ));
      } else {
        setPreferences(preferences.filter(p => p.brand_slug !== brandSlug));
        if (expandedBrand === brandSlug) setExpandedBrand(null);
      }
    }
  }

  // Brands to show in search: either search results or popular brands (filtered)
  const displayBrands = searchQuery.length >= 2
    ? searchResults
    : popularBrands.filter(b => !preferences.some(p => p.brand_slug === b.slug));

  if (loading) {
    return <div className="text-center text-text-muted">Laden...</div>;
  }

  return (
    <div id="maatvoering" className="rounded-2xl border border-border/30 bg-bg-card p-6">
      <h2 className="mb-4 text-lg font-bold text-text">Geavanceerde maten</h2>
      <p className="mb-6 text-sm text-text-muted">
        Stel per merk (en optioneel per model) je maat in. Dit wordt gebruikt voor alle filters op de site.
      </p>

      {/* Saved preferences */}
      {preferences.length > 0 && (
        <div className="mb-6 space-y-3 border-b border-border/30 pb-6">
          {preferences.map(pref => (
            <div key={pref.brand_slug} className="rounded-lg bg-bg-elevated p-3">
              <div className="flex items-center justify-between gap-3">
                <div className="flex items-center gap-2">
                  <span className="font-semibold text-text capitalize">{pref.brand_slug}</span>
                  <select
                    value={pref.size}
                    onChange={e => updateSize(pref.brand_slug, e.target.value)}
                    className="rounded border border-border/30 bg-bg px-2 py-1 text-xs text-text"
                  >
                    {EU_SIZES.map(s => <option key={s} value={s}>EU {s}</option>)}
                  </select>
                </div>
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => loadSubtypes(pref.brand_slug)}
                    className={`text-xs transition-colors ${expandedBrand === pref.brand_slug ? 'text-accent' : 'text-text-muted hover:text-accent'}`}
                    title="Subtypes beheren"
                  >
                    {expandedBrand === pref.brand_slug ? 'Inklappen' : '+ Model'}
                  </button>
                  <button
                    onClick={() => deleteSize(pref.brand_slug)}
                    className="text-text-muted transition-all hover:text-red-400"
                  >
                    ✕
                  </button>
                </div>
              </div>

              {/* Saved subtypes */}
              {pref.subtypes.length > 0 && (
                <div className="mt-2 ml-4 space-y-1 border-l border-border/30 pl-3">
                  {pref.subtypes.map(subtype => (
                    <div key={subtype.category_slug} className="flex items-center justify-between gap-2">
                      <span className="text-xs text-text-muted capitalize">
                        {subtype.category_slug.split('/').pop()?.replace(/-/g, ' ')}
                      </span>
                      <div className="flex items-center gap-2">
                        <select
                          value={subtype.size}
                          onChange={e => updateSize(pref.brand_slug, e.target.value, subtype.category_slug)}
                          className="rounded border border-border/30 bg-bg px-2 py-1 text-xs text-text"
                        >
                          {EU_SIZES.map(s => <option key={s} value={s}>EU {s}</option>)}
                        </select>
                        <button
                          onClick={() => deleteSize(pref.brand_slug, subtype.category_slug)}
                          className="text-xs text-text-muted hover:text-red-400"
                        >
                          ✕
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
              )}

              {/* Subtype picker (expanded) */}
              {expandedBrand === pref.brand_slug && (
                <div className="mt-3 ml-4 rounded border border-border/20 bg-bg p-2">
                  <p className="mb-2 text-xs font-semibold text-text-muted">Model toevoegen:</p>
                  {loadingSubtypes ? (
                    <p className="text-xs text-text-muted">Laden...</p>
                  ) : subtypeResults.length === 0 ? (
                    <p className="text-xs text-text-muted">Geen modellen gevonden voor dit merk</p>
                  ) : (
                    <div className="flex flex-wrap gap-1">
                      {subtypeResults
                        .filter(m => !pref.subtypes.some(s => s.category_slug === `${pref.brand_slug}/${m.slug}`))
                        .map(model => (
                          <button
                            key={model.slug}
                            onClick={() => addSubtype(pref.brand_slug, model.slug, model.name)}
                            className="rounded-full border border-border/30 px-2.5 py-1 text-xs text-text-secondary hover:border-accent/40 hover:text-accent transition-colors"
                          >
                            + {model.name}
                          </button>
                        ))}
                    </div>
                  )}
                </div>
              )}
            </div>
          ))}
        </div>
      )}

      {/* Add brand */}
      <div className="relative">
        <button
          onClick={() => { setShowBrandSearch(!showBrandSearch); setSearchQuery(''); setSearchResults([]); }}
          className="flex w-full items-center justify-center gap-2 rounded-lg border border-dashed border-border/50 px-4 py-2.5 text-sm font-semibold text-text-muted transition-all hover:border-accent/50 hover:text-accent"
        >
          <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4" />
          </svg>
          Merk toevoegen
        </button>

        {showBrandSearch && (
          <div className="absolute left-0 right-0 top-full z-10 mt-2 rounded-lg border border-border/30 bg-bg-card p-3 shadow-lg">
            <input
              autoFocus
              type="text"
              placeholder="Zoek merk..."
              value={searchQuery}
              onChange={e => setSearchQuery(e.target.value)}
              className="mb-2 w-full rounded border border-border/30 bg-bg-elevated px-3 py-2 text-sm text-text placeholder-text-muted focus:border-accent/50 focus:outline-none"
            />
            <div className="flex max-h-48 flex-col gap-1 overflow-y-auto">
              {searchQuery.length >= 2 && searching ? (
                <p className="py-2 text-center text-xs text-text-muted">Zoeken...</p>
              ) : displayBrands.length === 0 ? (
                <p className="py-2 text-center text-xs text-text-muted">
                  {searchQuery.length >= 2 ? 'Geen merken gevonden' : 'Typ om te zoeken'}
                </p>
              ) : (
                <>
                  {searchQuery.length < 2 && (
                    <p className="mb-1 text-[10px] font-bold uppercase tracking-widest text-text-muted">Populair</p>
                  )}
                  {displayBrands.map(brand => (
                    <button
                      key={brand.slug}
                      onClick={() => addBrand(brand.slug)}
                      className="flex items-center justify-between rounded px-2 py-1.5 text-left text-sm font-medium text-text transition-all hover:bg-bg-elevated"
                    >
                      <span>{brand.name}</span>
                      {brand.count && <span className="text-xs text-text-muted">{brand.count}</span>}
                    </button>
                  ))}
                </>
              )}
            </div>
          </div>
        )}
      </div>

      <p className="mt-4 text-xs text-text-muted">
        Voor merken die je niet hebt ingesteld, wordt je standaardmaat gebruikt.
      </p>
    </div>
  );
}
