import { useState, useEffect } from 'react';

interface Props {
  productId: number;
  currentLowestPrice: number;
  productName: string;
}

export default function PriceAlertForm({ productId, currentLowestPrice, productName }: Props) {
  const [user, setUser] = useState<{ id: string; email: string } | null>(null);
  const [email, setEmail] = useState('');
  const [targetPrice, setTargetPrice] = useState(
    (Math.floor(currentLowestPrice * 0.9 * 100) / 100).toFixed(2).replace('.', ',')
  );
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);
  const [message, setMessage] = useState('');
  const [isOnWatchlist, setIsOnWatchlist] = useState(false);
  const [expanded, setExpanded] = useState(false);

  useEffect(() => {
    fetch('/api/auth/session')
      .then(r => r.json())
      .then(data => {
        if (data.user) {
          setUser(data.user);
          setEmail(data.user.email);
          // Check if already on watchlist
          fetch('/api/watchlist')
            .then(r => r.json())
            .then(wl => {
              const item = wl.items?.find((i: any) => i.product_id === productId);
              if (item) {
                setIsOnWatchlist(true);
                if (item.target_price) {
                  setTargetPrice(item.target_price.toFixed(2).replace('.', ','));
                }
              }
            })
            .catch(() => {});
        }
      })
      .catch(() => {});
  }, [productId]);

  const parsePrice = (val: string) => parseFloat(val.replace(',', '.'));

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setMessage('');

    const price = parsePrice(targetPrice);
    if (isNaN(price) || price <= 0) {
      setMessage('Voer een geldig bedrag in');
      setLoading(false);
      return;
    }

    try {
      // If no user, register first
      if (!user) {
        const regRes = await fetch('/api/auth/register', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ email }),
        });
        const regData = await regRes.json();
        
        if (regData.error && !regData.error.includes('al geregistreerd')) {
          setMessage(regData.error);
          setLoading(false);
          return;
        }

        // If already registered, send login link
        if (regData.error?.includes('al geregistreerd')) {
          await fetch('/api/auth/login', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ email }),
          });
        }

        setSuccess(true);
        setMessage('Check je email om je account te bevestigen. Daarna is je prijsalert actief!');
        setLoading(false);
        return;
      }

      // User is logged in — add to watchlist with target price
      const res = await fetch('/api/watchlist', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          product_id: productId,
          target_price: price,
        }),
      });

      if (res.ok) {
        setSuccess(true);
        setIsOnWatchlist(true);
        setMessage(`Je ontvangt een mail als de prijs onder €${targetPrice} komt`);
      } else {
        const data = await res.json();
        setMessage(data.error || 'Er ging iets mis');
      }
    } catch {
      setMessage('Er ging iets mis, probeer het opnieuw');
    }
    setLoading(false);
  };

  if (success && isOnWatchlist) {
    return (
      <div className="rounded-2xl border-2 border-accent/30 bg-accent/5 p-6">
        <div className="flex items-center gap-3 mb-2">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="w-6 h-6 text-accent"><path d="M5.85 3.5a.75.75 0 0 0-1.117-1 9.719 9.719 0 0 0-2.348 4.876.75.75 0 0 0 1.479.248A8.219 8.219 0 0 1 5.85 3.5ZM19.267 2.5a.75.75 0 1 0-1.118 1 8.22 8.22 0 0 1 1.987 4.124.75.75 0 0 0 1.48-.248A9.72 9.72 0 0 0 19.266 2.5Z" /><path fillRule="evenodd" d="M12 2.25A6.75 6.75 0 0 0 5.25 9v.75a8.217 8.217 0 0 1-2.119 5.52.75.75 0 0 0 .298 1.206c1.544.57 3.16.99 4.831 1.243a3.75 3.75 0 1 0 7.48 0 24.583 24.583 0 0 0 4.83-1.244.75.75 0 0 0 .298-1.205 8.217 8.217 0 0 1-2.118-5.52V9A6.75 6.75 0 0 0 12 2.25ZM9.75 18c0-.034 0-.067.002-.1a25.05 25.05 0 0 0 4.496 0l.002.1a2.25 2.25 0 1 1-4.5 0Z" clipRule="evenodd" /></svg>
          <h3 className="text-lg font-bold">Prijsalert actief</h3>
        </div>
        <p className="text-text-secondary text-sm">
          We mailen je zodra de <span className="font-medium">{productName}</span> onder{' '}
          <span className="text-accent font-bold">€{targetPrice}</span> zakt.
        </p>
      </div>
    );
  }

  return (
    <div className="rounded-2xl border-2 border-border bg-bg-card overflow-hidden">
      <button
        type="button"
        onClick={() => setExpanded(!expanded)}
        className="w-full flex items-center justify-between p-5 hover:bg-bg-elevated/50 transition-colors"
      >
        <div className="flex items-center gap-3">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="w-5 h-5 text-accent"><path d="M5.85 3.5a.75.75 0 0 0-1.117-1 9.719 9.719 0 0 0-2.348 4.876.75.75 0 0 0 1.479.248A8.219 8.219 0 0 1 5.85 3.5ZM19.267 2.5a.75.75 0 1 0-1.118 1 8.22 8.22 0 0 1 1.987 4.124.75.75 0 0 0 1.48-.248A9.72 9.72 0 0 0 19.266 2.5Z" /><path fillRule="evenodd" d="M12 2.25A6.75 6.75 0 0 0 5.25 9v.75a8.217 8.217 0 0 1-2.119 5.52.75.75 0 0 0 .298 1.206c1.544.57 3.16.99 4.831 1.243a3.75 3.75 0 1 0 7.48 0 24.583 24.583 0 0 0 4.83-1.244.75.75 0 0 0 .298-1.205 8.217 8.217 0 0 1-2.118-5.52V9A6.75 6.75 0 0 0 12 2.25ZM9.75 18c0-.034 0-.067.002-.1a25.05 25.05 0 0 0 4.496 0l.002.1a2.25 2.25 0 1 1-4.5 0Z" clipRule="evenodd" /></svg>
          <span className="font-bold text-sm">Prijsalert instellen</span>
          <span className="text-xs text-text-muted">— mail me als de prijs daalt</span>
        </div>
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" className={`w-5 h-5 text-text-muted transition-transform duration-200 ${expanded ? 'rotate-180' : ''}`}>
          <path fillRule="evenodd" d="M5.22 8.22a.75.75 0 0 1 1.06 0L10 11.94l3.72-3.72a.75.75 0 1 1 1.06 1.06l-4.25 4.25a.75.75 0 0 1-1.06 0L5.22 9.28a.75.75 0 0 1 0-1.06Z" clipRule="evenodd" />
        </svg>
      </button>

      {expanded && (
      <div className="px-5 pb-5 border-t border-border">
      <div className="mt-4 mb-4 flex items-baseline gap-2">
        <span className="text-sm text-text-secondary">Huidige laagste prijs:</span>
        <span className="text-lg font-bold text-accent">
          €{currentLowestPrice.toFixed(2).replace('.', ',')}
        </span>
      </div>

      <form onSubmit={handleSubmit} className="space-y-3">
        <div>
          <label className="block text-sm font-medium text-text-secondary mb-1.5">
            Alert mij onder
          </label>
          <div className="relative">
            <span className="absolute left-3.5 top-1/2 -translate-y-1/2 text-text-muted font-medium">€</span>
            <input
              type="text"
              value={targetPrice}
              onChange={e => setTargetPrice(e.target.value)}
              className="w-full rounded-xl border border-border bg-bg-elevated pl-8 pr-4 py-3 text-lg font-bold placeholder-text-muted focus:border-accent/50 focus:outline-none"
              placeholder="0,00"
              required
            />
          </div>
        </div>

        {!user && (
          <div>
            <label className="block text-sm font-medium text-text-secondary mb-1.5">
              Je e-mailadres
            </label>
            <input
              type="email"
              value={email}
              onChange={e => setEmail(e.target.value)}
              placeholder="je@email.nl"
              required
              className="w-full rounded-xl border border-border bg-bg-elevated px-4 py-3 placeholder-text-muted focus:border-accent/50 focus:outline-none"
            />
          </div>
        )}

        {message && (
          <p className={`text-sm ${message.includes('Check') || message.includes('ontvangt') ? 'text-accent' : 'text-red-400'}`}>
            {message}
          </p>
        )}

        <button
          type="submit"
          disabled={loading}
          className="w-full rounded-xl bg-accent px-4 py-3.5 text-base font-bold text-black transition-colors hover:bg-accent/90 disabled:opacity-50"
        >
          {loading ? 'Even geduld...' : 'Alert me als de prijs daalt'}
        </button>
      </form>
      </div>
      )}
    </div>
  );
}
