import React, { useState, useEffect } from 'react';
import { X, User, Lock, Mail, AlertCircle, ShieldAlert, Sparkles } from 'lucide-react';
import { apiFetch, setAuthToken } from '../api/client';

export default function AuthModal({ onClose, onSuccess, claimToken, prefilledGuestName }) {
  const [isRegister, setIsRegister] = useState(Boolean(claimToken || prefilledGuestName));
  const [username, setUsername] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [displayName, setDisplayName] = useState(prefilledGuestName || '');

  const [restrictionSetting, setRestrictionSetting] = useState(null);
  const [error, setError] = useState('');
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    fetchRestrictionSetting();
  }, []);

  const fetchRestrictionSetting = async () => {
    try {
      const data = await apiFetch('/users/restriction-setting/');
      setRestrictionSetting(data);
    } catch (e) {
      // Ignore if fetch fails
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setSubmitting(true);

    try {
      if (isRegister) {
        const bodyObj = {
          username,
          email,
          password,
          display_name: displayName || username
        };
        if (claimToken) {
          bodyObj.claim_token = claimToken;
        }

        const data = await apiFetch('/users/register/', {
          method: 'POST',
          body: JSON.stringify(bodyObj)
        });

        if (data.requires_verification || data.requires_approval || !data.token) {
          onSuccess(null, data.message || 'Konto erfolgreich registriert! Bitte schau in deine E-Mail zur Bestätigung oder warte auf die Admin-Freischaltung.');
          onClose();
          return;
        }

        setAuthToken(data.token);
        onSuccess(data.user, data.message);
      } else {
        const data = await apiFetch('/users/login/', {
          method: 'POST',
          body: JSON.stringify({ username, password })
        });
        setAuthToken(data.token);
        onSuccess(data.user, 'Erfolgreich angemeldet!');
      }
      onClose();
    } catch (err) {
      setError(err.message || 'Authentifizierung fehlgeschlagen.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm">
      <div className="hallmark-panel w-full max-w-md rounded-sm border border-grid p-6 shadow-2xl relative animate-in fade-in zoom-in-95 duration-200">
        <button
          onClick={onClose}
          className="absolute top-4 right-4 p-2 text-muted hover:text-main rounded-sm transition"
        >
          <X className="w-5 h-5" />
        </button>

        <div className="flex items-center gap-3 mb-6">
          <div className="w-10 h-10 rounded-sm bg-blue-500/10 text-blue-500 border border-blue-500/20 flex items-center justify-center">
            <User className="w-5 h-5" />
          </div>
          <div>
            <h3 className="font-serif font-bold text-lg text-main">
              {isRegister ? 'Konto erstellen' : 'Anmelden'}
            </h3>
            <p className="text-xs text-muted font-sans">
              {isRegister ? 'Erstelle einen Account für volle Funktionen & Schichteinsicht' : 'Melde dich an, um Events zu verwalten'}
            </p>
          </div>
        </div>

        {prefilledGuestName && (
          <div className="mb-4 p-3 rounded-sm bg-amber-500/10 border border-amber-500/20 text-amber-500 text-xs flex items-center gap-2 font-mono">
            <Sparkles className="w-4 h-4 shrink-0 text-amber-500" />
            <span>
              Einladung für Gast: <strong>{prefilledGuestName}</strong>. Die Schicht wird deinem neuen Konto zugewiesen!
            </span>
          </div>
        )}

        {restrictionSetting?.is_restriction_enabled && isRegister && (
          <div className="mb-4 p-3 rounded-sm bg-indigo-500/10 border border-indigo-500/20 text-indigo-400 text-xs flex items-center gap-2 font-mono">
            <ShieldAlert className="w-4 h-4 shrink-0 text-indigo-400" />
            <span>
              Registrierungen beschränkt auf: <strong>{restrictionSetting.active_domains.join(', ')}</strong>
            </span>
          </div>
        )}

        {error && (
          <div className="mb-4 p-3 rounded-sm bg-red-500/10 border border-red-500/20 text-red-500 text-xs flex items-center gap-2 font-mono">
            <AlertCircle className="w-4 h-4 shrink-0" />
            <span>{error}</span>
          </div>
        )}

        {/* Quick Demo Login Box (Development Mode Only) */}
        {!isRegister && import.meta.env.DEV && (
          <div className="mb-5 p-3.5 rounded-sm bg-subtle border border-grid space-y-2 font-mono">
            <div className="text-[11px] font-semibold text-muted uppercase tracking-wider flex items-center justify-between">
              <span>⚡ Dev Schnell-Login</span>
            </div>
            <div className="grid grid-cols-2 gap-2">
              <button
                type="button"
                onClick={() => { setUsername('admin'); setPassword('adminpassword'); }}
                className="px-2.5 py-1.5 rounded-sm bg-indigo-500/10 hover:bg-indigo-500/20 text-indigo-400 border border-indigo-500/30 text-xs font-semibold transition text-left"
              >
                👑 Demo Admin
                <div className="text-[10px] text-indigo-400 font-normal">admin / adminpassword</div>
              </button>
              <button
                type="button"
                onClick={() => { setUsername('demouser'); setPassword('demouser123'); }}
                className="px-2.5 py-1.5 rounded-sm bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-500 border border-emerald-500/30 text-xs font-semibold transition text-left"
              >
                👤 Demo User
                <div className="text-[10px] text-emerald-500 font-normal">demouser / demouser123</div>
              </button>
            </div>
          </div>
        )}

        <form onSubmit={handleSubmit} className="space-y-4 font-sans">
          <div>
            <label className="block text-xs font-semibold text-main mb-1 font-mono">Benutzername</label>
            <div className="relative">
              <User className="w-4 h-4 absolute left-3 top-3 text-muted" />
              <input
                type="text"
                required
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                placeholder="z. B. max_muster"
                className="w-full pl-9 pr-3.5 py-2 rounded-sm input-field text-sm font-mono"
              />
            </div>
          </div>

          {isRegister && (
            <>
              <div>
                <label className="block text-xs font-semibold text-main mb-1 font-mono">E-Mail-Adresse</label>
                <div className="relative">
                  <Mail className="w-4 h-4 absolute left-3 top-3 text-muted" />
                  <input
                    type="email"
                    required
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    placeholder="max@beispiel.de"
                    className="w-full pl-9 pr-3.5 py-2 rounded-sm input-field text-sm font-mono"
                  />
                </div>
              </div>

              <div>
                <label className="block text-xs font-semibold text-main mb-1 font-mono">Anzeigename (für Schichtlisten)</label>
                <div className="relative">
                  <User className="w-4 h-4 absolute left-3 top-3 text-muted" />
                  <input
                    type="text"
                    value={displayName}
                    onChange={(e) => setDisplayName(e.target.value)}
                    placeholder="z. B. Max M."
                    className="w-full pl-9 pr-3.5 py-2 rounded-sm input-field text-sm font-mono"
                  />
                </div>
              </div>
            </>
          )}

          <div>
            <label className="block text-xs font-semibold text-main mb-1 font-mono">Passwort</label>
            <div className="relative">
              <Lock className="w-4 h-4 absolute left-3 top-3 text-muted" />
              <input
                type="password"
                required
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="••••••••"
                className="w-full pl-9 pr-3.5 py-2 rounded-sm input-field text-sm font-mono"
              />
            </div>
          </div>

          <button
            type="submit"
            disabled={submitting}
            style={{ backgroundColor: 'var(--brand-primary)' }}
            className="w-full py-2.5 rounded-sm text-xs font-mono font-bold text-white transition hover:brightness-110 shadow-sm"
          >
            {submitting ? 'Verarbeite...' : isRegister ? 'Registrieren' : 'Anmelden'}
          </button>
        </form>

        <div className="mt-4 pt-4 border-t border-grid text-center">
          <button
            type="button"
            onClick={() => { setIsRegister(!isRegister); setError(''); }}
            className="text-xs font-mono text-muted hover:text-main transition"
          >
            {isRegister ? 'Bereits ein Konto? Hier anmelden' : 'Noch kein Konto? Jetzt registrieren'}
          </button>
        </div>
      </div>
    </div>
  );
}
