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'];

function getCookie(name: string): string | null {
  if (typeof document === 'undefined') return null;
  const match = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
  return match ? decodeURIComponent(match[1]) : null;
}

function setCookie(name: string, value: string, days = 365) {
  const expires = new Date(Date.now() + days * 864e5).toUTCString();
  document.cookie = `${name}=${encodeURIComponent(value)};expires=${expires};path=/;SameSite=Lax`;
}

function deleteCookie(name: string) {
  document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/;SameSite=Lax`;
}

type SessionState = 'loading' | 'guest' | 'has-size' | 'advanced' | 'no-size';

export default function SizePicker() {
  const [sessionState, setSessionState] = useState<SessionState>('loading');
  const [profileSize, setProfileSize] = useState<string | null>(null);
  const [selectedSize, setSelectedSize] = useState<string | null>(null);
  const [open, setOpen] = useState(false);
  const [hasAdvancedSizes, setHasAdvancedSizes] = useState(false);
  const [advancedOn, setAdvancedOn] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  // Load session + profile size on mount
  useEffect(() => {
    const getSession = (window as any).__spSession || (() => fetch('/api/auth/session').then(r => r.json()));
    getSession()
      .then((data: any) => {
        if (data.user?.has_advanced_sizes) {
          // Logged in with advanced sizes
          setHasAdvancedSizes(true);
          setAdvancedOn(data.user.advanced_size_mode === 'on');
          setSessionState('advanced');
        } else if (data.user?.shoe_size) {
          // Logged in with shoe_size (no advanced)
          setProfileSize(data.user.shoe_size);
          setSessionState('has-size');
          // Auto-sync profile size to cookie
          setCookie('sp_size', data.user.shoe_size);
          setSelectedSize(data.user.shoe_size);
        } else if (data.user) {
          // Logged in but no shoe_size
          setSessionState('no-size');
        } else {
          // Not logged in - use cookie
          setSessionState('guest');
          const saved = getCookie('sp_size');
          if (saved && EU_SIZES.includes(saved)) {
            setSelectedSize(saved);
          }
        }
      })
      .catch(() => {
        // Fallback to guest mode
        setSessionState('guest');
        const saved = getCookie('sp_size');
        if (saved && EU_SIZES.includes(saved)) {
          setSelectedSize(saved);
        }
      });
  }, []);

  // Close dropdown on outside click
  useEffect(() => {
    function handleClick(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) {
        setOpen(false);
      }
    }
    if (open) document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, [open]);

  function pickSize(size: string | null) {
    setSelectedSize(size);
    setOpen(false);
    if (size) {
      setCookie('sp_size', size);
    } else {
      deleteCookie('sp_size');
    }
    // Reload to apply filter server-side
    window.location.reload();
  }

  function toggleAdvancedMode() {
    const newMode = advancedOn ? 'off' : 'on';
    setAdvancedOn(!advancedOn);
    setCookie('sp_size_mode', newMode);
    // Reload to apply filter server-side
    window.location.reload();
  }

  if (sessionState === 'loading') {
    return (
      <button disabled className="h-8 w-8 animate-pulse rounded-full bg-bg-elevated" />
    );
  }

  // Guest: show dropdown picker
  if (sessionState === 'guest') {
    return (
      <div ref={ref} className="relative">
        <button
          onClick={() => setOpen(!open)}
          className={`flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-bold transition-all ${
            selectedSize
              ? 'bg-accent text-bg hover:bg-accent-dim'
              : 'bg-bg-elevated text-text-muted hover:text-text'
          }`}
          aria-label="Kies je schoenmaat"
          title="Kies je schoenmaat"
        >
          <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12.75l6 6 9-13.5" />
          </svg>
          {selectedSize ? `EU ${selectedSize}` : 'Kies je maat'}
        </button>

        {open && (
          <div className="absolute right-0 top-full z-50 mt-2 w-64 rounded-2xl border border-border/50 bg-bg-card p-4 shadow-xl">
            <div className="mb-3 flex items-center justify-between">
              <span className="text-xs font-bold uppercase tracking-widest text-text-muted">Jouw maat</span>
              {selectedSize && (
                <button
                  onClick={() => pickSize(null)}
                  className="text-xs font-bold text-accent hover:text-accent-dim"
                >
                  Wissen
                </button>
              )}
            </div>
            <div className="flex flex-wrap gap-1.5">
              {EU_SIZES.map((size) => (
                <button
                  key={size}
                  onClick={() => pickSize(size)}
                  className={`rounded-lg px-2.5 py-1.5 text-xs font-bold transition-all ${
                    selectedSize === size
                      ? 'bg-accent text-bg'
                      : 'bg-bg-elevated text-text-muted hover:text-text'
                  }`}
                >
                  {size}
                </button>
              ))}
            </div>
            <p className="mt-3 text-[10px] text-text-muted">
              Alle sneakers worden gefilterd op jouw maat
            </p>
          </div>
        )}
      </div>
    );
  }

  // Logged in with size: show toggle
  if (sessionState === 'has-size') {
    return (
      <button
        onClick={() => pickSize(selectedSize ? null : profileSize)}
        className={`flex items-center gap-1 rounded-full px-3 py-1.5 text-xs font-bold transition-all ${
          selectedSize
            ? 'bg-accent text-bg hover:bg-accent-dim'
            : 'border border-border/30 bg-bg-elevated text-text-muted hover:border-accent/30 hover:text-text'
        }`}
        title={selectedSize ? 'Filter uitschakelen' : 'Filter inschakelen'}
      >
        Mijn Maten: EU {profileSize}
        {selectedSize && (
          <span className="ml-1 font-bold">×</span>
        )}
      </button>
    );
  }

  // Advanced mode: toggle button with link to profile
  if (sessionState === 'advanced') {
    return (
      <div className="flex items-center gap-2">
        <button
          onClick={toggleAdvancedMode}
          className={`flex items-center gap-1 rounded-full px-3 py-1.5 text-xs font-bold transition-all ${
            advancedOn
              ? 'bg-accent text-bg hover:bg-accent-dim'
              : 'border border-border/30 bg-bg-elevated text-text-muted hover:border-accent/30 hover:text-text'
          }`}
          title={advancedOn ? 'Geavanceerde filter uit' : 'Geavanceerde filter aan'}
        >
          {advancedOn ? '✓ Mijn Maten' : 'Mijn Maten'}
        </button>
        <a
          href="/profiel#maatvoering"
          className="inline-flex items-center justify-center h-8 w-8 rounded-full border border-border/30 bg-bg-elevated text-text-muted transition-all hover:border-accent/30 hover:text-text"
          title="Beheer geavanceerde maten"
        >
          <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M10.5 6h12.75M10.5 12h12.75M10.5 18h12.75M4.5 6h.01M4.5 12h.01M4.5 18h.01" />
          </svg>
        </a>
      </div>
    );
  }

  // Logged in without size: show link to profile
  if (sessionState === 'no-size') {
    return (
      <a
        href="/profiel"
        className="flex items-center gap-1.5 rounded-full border border-border/30 bg-bg-elevated px-3 py-1.5 text-xs font-bold text-text-muted transition-all hover:border-accent/30 hover:text-text"
        title="Stel je maat in"
      >
        <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
          <path strokeLinecap="round" strokeLinejoin="round" d="M12 6v12m6-6H6" />
        </svg>
        Maat
      </a>
    );
  }

  return null;
}
