import { useState, useEffect, type FormEvent } from 'react';
import WatchlistItemCard, { type WatchlistItem } from './WatchlistItemCard';
import ForYouSection from './ForYouSection';

function LoginForm({ onLoggedIn }: { onLoggedIn: () => void }) {
  const [email, setEmail] = useState('');
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState('');

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setMessage('');
    try {
      const res = await fetch('/api/auth/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      const data = await res.json();
      if (data.ok) {
        setMessage('Check je email voor de bevestigingslink!');
      } else if (data.error?.includes('al geregistreerd')) {
        const loginRes = await fetch('/api/auth/login', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ email }),
        });
        const loginData = await loginRes.json();
        setMessage(loginData.message || 'Check je email voor de inloglink!');
      } else {
        setMessage(data.error || 'Er ging iets mis');
      }
    } catch {
      setMessage('Er ging iets mis');
    }
    setLoading(false);
  };

  return (
    <div className="mx-auto max-w-md py-12">
      <div className="rounded-2xl border border-border/30 bg-bg-card p-8 text-center">
        <svg className="mx-auto mb-4 h-10 w-10 text-accent" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
          <path strokeLinecap="round" strokeLinejoin="round" d="M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12z" />
        </svg>
        <h2 className="mb-2 text-xl font-bold text-text">Watchlist & Prijsalerts</h2>
        <p className="mb-6 text-sm text-text-muted">
          Houd je favoriete sneakers in de gaten en ontvang een melding zodra de prijs daalt.
        </p>
        <a
          href="/api/auth/google?return_to=/watchlist"
          className="mb-4 flex w-full items-center justify-center gap-3 rounded-lg border border-border/50 bg-bg-elevated px-4 py-3 font-semibold text-text transition-all hover:border-accent/30 hover:bg-bg-elevated/80"
        >
          <svg viewBox="0 0 24 24" className="h-5 w-5" xmlns="http://www.w3.org/2000/svg">
            <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
            <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
            <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/>
            <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/>
          </svg>
          Inloggen met Google
        </a>
        <div className="relative mb-4">
          <div className="absolute inset-0 flex items-center"><div className="w-full border-t border-border/30"></div></div>
          <div className="relative flex justify-center"><span className="bg-bg-card px-3 text-xs text-text-muted">of via e-mail</span></div>
        </div>
        <form onSubmit={handleSubmit}>
          <input
            type="email"
            value={email}
            onChange={e => setEmail(e.target.value)}
            placeholder="je@email.nl"
            required
            className="mb-3 w-full rounded-lg border border-border/30 bg-bg-elevated px-4 py-3 text-text placeholder-text-muted focus:border-accent/50 focus:outline-none"
          />
          {message && (
            <p className={`mb-3 text-sm ${message.includes('Check') ? 'text-accent' : 'text-red-400'}`}>
              {message}
            </p>
          )}
          <button
            type="submit"
            disabled={loading}
            className="w-full rounded-lg bg-accent px-4 py-3 font-bold text-bg transition-colors hover:bg-accent-dim disabled:opacity-50"
          >
            {loading ? 'Even geduld...' : 'Stuur magic link'}
          </button>
        </form>
        <p className="mt-4 text-xs text-text-muted">
          Via e-mail ontvang je een magic link — geen wachtwoord nodig.
        </p>
      </div>
    </div>
  );
}

type SortOption = 'newest' | 'price_low' | 'price_high' | 'discount' | 'price_drop';

function urlBase64ToUint8Array(base64String: string) {
  const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
  const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
  const rawData = atob(base64);
  const outputArray = new Uint8Array(rawData.length);
  for (let i = 0; i < rawData.length; ++i) outputArray[i] = rawData.charCodeAt(i);
  return outputArray;
}

export default function WatchlistPageApp() {
  const [items, setItems] = useState<WatchlistItem[]>([]);
  const [user, setUser] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [sortBy, setSortBy] = useState<SortOption>('newest');
  const [filterBrand, setFilterBrand] = useState<string>('all');
  const [filterDealsOnly, setFilterDealsOnly] = useState(false);
  const [pushEnabled, setPushEnabled] = useState(false);
  const [pushSubscribing, setPushSubscribing] = useState(false);

  useEffect(() => {
    Promise.all([
      fetch('/api/auth/session').then(r => r.json()),
      fetch('/api/watchlist').then(r => r.json()).catch(() => ({ items: [] })),
    ]).then(([session, watchlist]) => {
      setUser(session.user);
      setItems(watchlist.items || []);
      setLoading(false);
    });
    // Check push status from localStorage
    setPushEnabled(localStorage.getItem('sp_push_subscribed') === '1');
  }, []);

  const enablePush = async () => {
    if (!('PushManager' in window) || !('serviceWorker' in navigator)) {
      alert('Je browser ondersteunt geen push notificaties.');
      return;
    }
    setPushSubscribing(true);
    try {
      const reg = await navigator.serviceWorker.ready;
      const vapidKey = (import.meta as any).env?.PUBLIC_VAPID_KEY;
      const sub = await reg.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: urlBase64ToUint8Array(vapidKey),
      });
      await fetch('/api/push/subscribe', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(sub.toJSON()),
      });
      localStorage.setItem('sp_push_subscribed', '1');
      localStorage.removeItem('sp_push_dismissed');
      setPushEnabled(true);
    } catch {
      alert('Push notificaties konden niet worden ingeschakeld. Controleer je browserinstellingen.');
    }
    setPushSubscribing(false);
  };

  const removeItem = async (productId: number) => {
    await fetch('/api/watchlist', {
      method: 'DELETE',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ product_id: productId }),
    });
    setItems(items.filter(i => i.product_id !== productId));
  };

  const updateTargetPrice = async (productId: number, price: number | null) => {
    await fetch('/api/watchlist', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ product_id: productId, target_price: price }),
    });
    setItems(items.map(i => i.product_id === productId ? { ...i, target_price: price } : i));
  };

  const toggleNotification = async (productId: number, field: 'notify_price_drop' | 'notify_back_in_stock' | 'notify_push_price_drop' | 'notify_push_back_in_stock', value: boolean) => {
    await fetch('/api/watchlist', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ product_id: productId, [field]: value }),
    });
    setItems(items.map(i => i.product_id === productId ? { ...i, [field]: value } : i));
  };

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

  if (!user) {
    return <LoginForm onLoggedIn={() => window.location.reload()} />;
  }

  if (items.length === 0) {
    return (
      <div className="text-center py-12">
        <p className="text-4xl mb-4">👟</p>
        <p className="text-text-muted mb-4">Je watchlist is nog leeg</p>
        <a href="/" className="inline-block rounded-lg bg-accent px-6 py-2.5 font-bold text-bg">
          Ontdek sneakers
        </a>
      </div>
    );
  }

  // Derive unique brands from items
  const brands = [...new Set(items.map(i => i.brand))].sort();

  // Filter
  let filtered = items;
  if (filterBrand !== 'all') {
    filtered = filtered.filter(i => i.brand === filterBrand);
  }
  if (filterDealsOnly) {
    filtered = filtered.filter(i => {
      const lp = i.lowest_price ? parseFloat(String(i.lowest_price)) : null;
      const tp = i.target_price ? parseFloat(String(i.target_price)) : null;
      return lp && tp && lp <= tp;
    });
  }

  // Sort
  const sorted = [...filtered].sort((a, b) => {
    const aPrice = a.lowest_price ? parseFloat(String(a.lowest_price)) : Infinity;
    const bPrice = b.lowest_price ? parseFloat(String(b.lowest_price)) : Infinity;
    const aOrig = a.original_price ? parseFloat(String(a.original_price)) : aPrice;
    const bOrig = b.original_price ? parseFloat(String(b.original_price)) : bPrice;
    const aDiscount = aOrig > 0 ? (aOrig - aPrice) / aOrig : 0;
    const bDiscount = bOrig > 0 ? (bOrig - bPrice) / bOrig : 0;

    switch (sortBy) {
      case 'price_low': return aPrice - bPrice;
      case 'price_high': return bPrice - aPrice;
      case 'discount': return bDiscount - aDiscount;
      case 'price_drop': {
        const aDelta = (a.price_7d_ago && a.lowest_price) ? parseFloat(String(a.lowest_price)) - parseFloat(String(a.price_7d_ago)) : 0;
        const bDelta = (b.price_7d_ago && b.lowest_price) ? parseFloat(String(b.lowest_price)) - parseFloat(String(b.price_7d_ago)) : 0;
        return aDelta - bDelta; // Most negative (biggest drop) first
      }
      default: return 0; // 'newest' keeps API order (created_at DESC)
    }
  });

  return (
    <div className="space-y-4">
      {/* Push activation banner */}
      {!pushEnabled && 'PushManager' in window && (
        <div className="flex items-center gap-3 rounded-xl border border-accent/20 bg-accent/5 px-4 py-3">
          <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="shrink-0 text-accent"><path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10.3 21a1.94 1.94 0 0 0 3.4 0"/></svg>
          <p className="flex-1 text-xs text-text-secondary">
            Ontvang direct een browsermelding bij een prijsdaling — geen e-mail nodig.
          </p>
          <button
            onClick={enablePush}
            disabled={pushSubscribing}
            className="shrink-0 rounded-lg bg-accent px-3 py-1.5 text-xs font-bold text-bg transition-all hover:opacity-90 disabled:opacity-50"
          >
            {pushSubscribing ? 'Even wachten...' : 'Inschakelen'}
          </button>
        </div>
      )}
      {/* Sort & Filter controls */}
      <div className="flex flex-wrap items-center gap-3">
        <p className="text-sm text-text-muted">{filtered.length} sneaker{filtered.length !== 1 ? 's' : ''}</p>
        <div className="ml-auto flex flex-wrap items-center gap-2">
          {brands.length > 1 && (
            <select
              value={filterBrand}
              onChange={e => setFilterBrand(e.target.value)}
              className="rounded-lg border border-border/30 bg-bg-elevated px-2 py-1.5 text-xs text-text focus:border-accent/50 focus:outline-none"
            >
              <option value="all">Alle merken</option>
              {brands.map(b => <option key={b} value={b}>{b}</option>)}
            </select>
          )}
          <select
            value={sortBy}
            onChange={e => setSortBy(e.target.value as SortOption)}
            className="rounded-lg border border-border/30 bg-bg-elevated px-2 py-1.5 text-xs text-text focus:border-accent/50 focus:outline-none"
          >
            <option value="newest">Nieuwste eerst</option>
            <option value="price_low">Laagste prijs</option>
            <option value="price_high">Hoogste prijs</option>
            <option value="discount">Hoogste korting</option>
            <option value="price_drop">Grootste prijsdaling</option>
          </select>
          <label className="flex items-center gap-1.5 cursor-pointer">
            <input
              type="checkbox"
              checked={filterDealsOnly}
              onChange={e => setFilterDealsOnly(e.target.checked)}
              className="rounded border-border/30 accent-accent"
            />
            <span className="text-xs text-text-muted">Alleen deals</span>
          </label>
        </div>
      </div>

      {sorted.length === 0 ? (
        <div className="rounded-xl border border-border/30 bg-bg-card p-8 text-center">
          <p className="text-text-muted">Geen sneakers gevonden met deze filters</p>
        </div>
      ) : (
        sorted.map(item => (
          <WatchlistItemCard
            key={item.id}
            item={item}
            onRemove={removeItem}
            onUpdateTargetPrice={updateTargetPrice}
            onToggleNotification={toggleNotification}
            pushEnabled={pushEnabled}
            onEnablePush={enablePush}
          />
        ))
      )}

      <ForYouSection />
    </div>
  );
}
