import { useState, useEffect } from 'react';

interface Props {
  productId: number;
  size?: 'sm' | 'md';
}

export default function WatchlistButton({ productId, size = 'sm' }: Props) {
  const [isOnList, setIsOnList] = useState(false);
  const [loading, setLoading] = useState(false);
  const [user, setUser] = useState<{ id: string; email: string } | null>(null);
  const [showModal, setShowModal] = useState(false);
  const [email, setEmail] = useState('');
  const [message, setMessage] = useState('');
  const [targetPrice, setTargetPrice] = useState('');

  useEffect(() => {
    // Check session
    fetch('/api/auth/session')
      .then(r => r.json())
      .then(data => {
        if (data.user) {
          setUser(data.user);
          // Check if product is on watchlist
          fetch('/api/watchlist')
            .then(r => r.json())
            .then(wl => {
              if (wl.items?.some((i: any) => i.product_id === productId)) {
                setIsOnList(true);
              }
            })
            .catch(() => {});
        }
      })
      .catch(() => {});
  }, [productId]);

  const handleClick = async (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();

    if (!user) {
      setShowModal(true);
      return;
    }

    setLoading(true);
    try {
      if (isOnList) {
        await fetch('/api/watchlist', {
          method: 'DELETE',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ product_id: productId }),
        });
        setIsOnList(false);
      } else {
        await fetch('/api/watchlist', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            product_id: productId,
            target_price: targetPrice ? parseFloat(targetPrice) : null,
          }),
        });
        setIsOnList(true);
      }
    } catch {}
    setLoading(false);
  };

  const handleRegister = async (e: React.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! 📧');
      } else if (data.error?.includes('al geregistreerd')) {
        // Try login instead
        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);
  };

  const iconSize = size === 'sm' ? 'w-5 h-5' : 'w-6 h-6';
  const btnSize = size === 'sm' ? 'p-1.5' : 'p-2';

  return (
    <>
      <button
        onClick={handleClick}
        disabled={loading}
        className={`${btnSize} rounded-full transition-all duration-200 ${
          isOnList
            ? 'bg-[#00FF6A]/20 text-[#00FF6A]'
            : 'bg-white/10 text-white/60 hover:bg-white/20 hover:text-white'
        } ${loading ? 'opacity-50' : ''}`}
        title={isOnList ? 'Verwijder van watchlist' : 'Voeg toe aan watchlist'}
      >
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill={isOnList ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth={2} className={iconSize}>
          <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>
      </button>

      {/* Email registration modal */}
      {showModal && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4"
          onClick={(e) => { if (e.target === e.currentTarget) setShowModal(false); }}
        >
          <div className="w-full max-w-sm rounded-2xl border border-white/10 bg-[#141414] p-6" onClick={e => e.stopPropagation()}>
            <h3 className="mb-2 text-lg font-bold text-white">Sneaker volgen 👟</h3>
            <p className="mb-4 text-sm text-white/60">
              Voer je email in om deze sneaker op je watchlist te zetten en prijsalerts te ontvangen.
            </p>
            <form onSubmit={handleRegister}>
              <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-white/10 bg-white/5 px-4 py-2.5 text-white placeholder-white/30 focus:border-[#00FF6A]/50 focus:outline-none"
              />
              
              <div className="mb-3 rounded-lg border border-white/10 bg-white/5 p-3">
                <p className="text-xs font-medium text-white/50 mb-1.5">🔔 Prijsalert (optioneel)</p>
                <div className="flex items-center gap-2">
                  <span className="text-sm text-white/60">Mail mij onder €</span>
                  <input
                    type="number"
                    value={targetPrice}
                    onChange={e => setTargetPrice(e.target.value)}
                    placeholder="0,00"
                    step="0.01"
                    min="0"
                    className="w-24 rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-white placeholder-white/30 focus:border-[#00FF6A]/50 focus:outline-none"
                  />
                </div>
              </div>

              {message && (
                <p className={`mb-3 text-sm ${message.includes('Check') ? 'text-[#00FF6A]' : 'text-red-400'}`}>
                  {message}
                </p>
              )}
              
              <button
                type="submit"
                disabled={loading}
                className="w-full rounded-lg bg-[#00FF6A] px-4 py-2.5 font-bold text-black transition-colors hover:bg-[#00FF6A]/90 disabled:opacity-50"
              >
                {loading ? 'Even geduld...' : 'Watchlist & Alerts activeren'}
              </button>
            </form>
            <button
              onClick={() => setShowModal(false)}
              className="mt-3 w-full text-center text-sm text-white/40 hover:text-white/60"
            >
              Annuleren
            </button>
          </div>
        </div>
      )}
    </>
  );
}
