import React, { useState, useEffect } from 'react';
import { X, Shield, Settings, Plus, Trash2, Palette, CheckCircle2, AlertCircle, UserCheck, Clock, UserX, Layout } from 'lucide-react';
import { apiFetch } from '../api/client';

export default function AdminSettingsModal({ branding, onClose, onRefreshBranding }) {
  const [restrictionEnabled, setRestrictionEnabled] = useState(false);
  const [requireApproval, setRequireApproval] = useState(false);
  const [domainRules, setDomainRules] = useState([]);
  const [newDomain, setNewDomain] = useState('');

  const [pendingUsers, setPendingUsers] = useState([]);
  const [loadingRules, setLoadingRules] = useState(true);

  // Branding & Sidebar boxes form state
  const [appName, setAppName] = useState(branding?.app_name || 'Veranstaltungsschichtplaner');
  const [logoUrl, setLogoUrl] = useState(branding?.logo_url || '');
  const [primaryColor, setPrimaryColor] = useState(branding?.primary_color || '#E05A47');
  const [bannerText, setBannerText] = useState(branding?.custom_banner_text || '');

  // Community Info Box
  const [showCommunityInfoBox, setShowCommunityInfoBox] = useState(branding?.show_community_info_box ?? true);
  const [communityInfoTitle, setCommunityInfoTitle] = useState(branding?.community_info_title || '📌 Verein & Infos');
  const [communityInfoText, setCommunityInfoText] = useState(branding?.community_info_text || 'Initiative e.V. Hausverein\nOffene Angebote, DIY-Kultur & engagierte Schichten.');

  // Support Box
  const [showSupportBox, setShowSupportBox] = useState(branding?.show_support_box ?? true);
  const [supportBoxTitle, setSupportBoxTitle] = useState(branding?.support_box_title || '❤️ Unterstützen');
  const [supportBoxText, setSupportBoxText] = useState(branding?.support_box_text || 'Hilf mit als Helfer*in an der Bar, beim Essen kochen oder beim Auf- & Abbau.');

  const [savingBranding, setSavingBranding] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

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

  const fetchAdminSettings = async () => {
    try {
      const setting = await apiFetch('/users/restriction-setting/');
      setRestrictionEnabled(setting.is_restriction_enabled);
      setRequireApproval(setting.require_admin_approval);

      const rules = await apiFetch('/users/domain-rules/');
      setDomainRules(rules.results || rules);

      const pending = await apiFetch('/users/pending/');
      setPendingUsers(pending.results || pending);
    } catch (err) {
      setError(err.message || 'Laden der Admin-Einstellungen fehlgeschlagen.');
    } finally {
      setLoadingRules(false);
    }
  };

  const handleToggleRestriction = async () => {
    try {
      const updated = await apiFetch('/users/restriction-setting/', {
        method: 'POST',
        body: JSON.stringify({ is_restriction_enabled: !restrictionEnabled })
      });
      setRestrictionEnabled(updated.is_restriction_enabled);
      setSuccess(`Domain-Beschränkung ist jetzt ${updated.is_restriction_enabled ? 'AKTIV' : 'INAKTIV'}`);
    } catch (err) {
      setError(err.message || 'Fehler beim Umschalten.');
    }
  };

  const handleToggleRequireApproval = async () => {
    try {
      const updated = await apiFetch('/users/restriction-setting/', {
        method: 'POST',
        body: JSON.stringify({ require_admin_approval: !requireApproval })
      });
      setRequireApproval(updated.require_admin_approval);
      setSuccess(`Manuelle Admin-Freischaltung ist jetzt ${updated.require_admin_approval ? 'AKTIV' : 'INAKTIV'}`);
    } catch (err) {
      setError(err.message || 'Fehler beim Umschalten.');
    }
  };

  const handleAddDomain = async (e) => {
    e.preventDefault();
    if (!newDomain.trim()) return;

    try {
      const created = await apiFetch('/users/domain-rules/', {
        method: 'POST',
        body: JSON.stringify({ domain: newDomain.trim(), is_active: true })
      });
      setDomainRules([...domainRules, created]);
      setNewDomain('');
      setSuccess('Domain erfolgreich hinzugefügt!');
    } catch (err) {
      setError(err.message || 'Fehler beim Hinzufügen der Domain.');
    }
  };

  const handleDeleteDomain = async (id) => {
    try {
      await apiFetch(`/users/domain-rules/${id}/`, { method: 'DELETE' });
      setDomainRules(domainRules.filter(r => r.id !== id));
      setSuccess('Domain entfernt.');
    } catch (err) {
      setError(err.message || 'Fehler beim Löschen der Domain.');
    }
  };

  const handleApproveUser = async (userId) => {
    try {
      const res = await apiFetch(`/users/${userId}/approve/`, { method: 'POST' });
      setPendingUsers(pendingUsers.filter(u => u.id !== userId));
      setSuccess(res.message || 'Nutzer wurde erfolgreich freigeschaltet!');
    } catch (err) {
      setError(err.message || 'Freischaltung fehlgeschlagen.');
    }
  };

  const handleRejectUser = async (userId) => {
    try {
      const res = await apiFetch(`/users/${userId}/approve/`, { method: 'DELETE' });
      setPendingUsers(pendingUsers.filter(u => u.id !== userId));
      setSuccess(res.message || 'Registrierung abgelehnt und gelöscht.');
    } catch (err) {
      setError(err.message || 'Ablehnen fehlgeschlagen.');
    }
  };

  const handleSaveBranding = async (e) => {
    e.preventDefault();
    setSavingBranding(true);
    setError('');
    setSuccess('');

    try {
      await apiFetch('/branding/', {
        method: 'POST',
        body: JSON.stringify({
          app_name: appName,
          logo_url: logoUrl,
          primary_color: primaryColor,
          custom_banner_text: bannerText,
          show_community_info_box: showCommunityInfoBox,
          community_info_title: communityInfoTitle,
          community_info_text: communityInfoText,
          show_support_box: showSupportBox,
          support_box_title: supportBoxTitle,
          support_box_text: supportBoxText
        })
      });
      setSuccess('Branding & Info-Boxen erfolgreich gespeichert!');
      onRefreshBranding();
    } catch (err) {
      setError(err.message || 'Fehler beim Speichern der Einstellungen.');
    } finally {
      setSavingBranding(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm overflow-y-auto">
      <div className="hallmark-panel w-full max-w-2xl rounded-sm border border-grid p-6 shadow-2xl relative my-8 font-sans">
        <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 border-b border-grid pb-4">
          <div className="w-10 h-10 rounded-sm bg-indigo-500/10 text-indigo-400 border border-indigo-500/20 flex items-center justify-center">
            <Settings className="w-5 h-5" />
          </div>
          <div>
            <h3 className="font-serif font-bold text-lg text-main">Admin-Einstellungen</h3>
            <p className="text-xs text-muted font-mono">Freischaltungen, Info-Boxen & Branding verwalten</p>
          </div>
        </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>
        )}

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

        {/* Section 1: Admin Approval for Registrations */}
        <div className="space-y-4 mb-6">
          <div className="flex items-center justify-between p-4 rounded-sm bg-subtle border border-grid">
            <div>
              <h4 className="font-mono font-bold text-xs uppercase tracking-wider text-main flex items-center gap-2">
                <UserCheck className="w-4 h-4 text-blue-400" /> Manuelle Admin-Freischaltung erforderlich
              </h4>
              <p className="text-xs text-muted mt-0.5">
                Wenn aktiviert, müssen sich neue Konten registrieren, können sich aber erst nach deiner Freigabe anmelden.
              </p>
            </div>
            <button
              onClick={handleToggleRequireApproval}
              className={`px-3 py-1.5 rounded-sm text-xs font-mono font-bold transition ${
                requireApproval
                  ? 'bg-blue-600 text-white'
                  : 'bg-surface text-muted border border-grid hover:text-main'
              }`}
            >
              {requireApproval ? 'AKTIV' : 'INAKTIV'}
            </button>
          </div>

          {/* Pending Users List */}
          {requireApproval && (
            <div className="p-4 rounded-sm bg-subtle border border-grid space-y-3 font-mono">
              <h5 className="font-bold text-xs text-main flex items-center gap-2 uppercase tracking-wider">
                <Clock className="w-3.5 h-3.5 text-amber-400" /> Ausstehende Registrierungen ({pendingUsers.length})
              </h5>

              {pendingUsers.length === 0 ? (
                <p className="text-xs text-muted italic">[ Keine ausstehenden Registrierungen ]</p>
              ) : (
                <div className="space-y-2">
                  {pendingUsers.map((pUser) => (
                    <div key={pUser.id} className="flex items-center justify-between p-3 rounded-sm bg-surface border border-grid text-xs">
                      <div>
                        <div className="font-bold text-main">{pUser.display_name || pUser.username}</div>
                        <div className="text-[11px] text-muted">{pUser.email}</div>
                      </div>
                      <div className="flex items-center gap-2">
                        <button
                          onClick={() => handleApproveUser(pUser.id)}
                          className="px-3 py-1 rounded-sm font-bold bg-emerald-600 hover:bg-emerald-500 text-white transition flex items-center gap-1"
                        >
                          <UserCheck className="w-3.5 h-3.5" /> Freischalten
                        </button>
                        <button
                          onClick={() => handleRejectUser(pUser.id)}
                          className="px-2.5 py-1 rounded-sm font-semibold bg-red-500/10 hover:bg-red-500/20 text-red-400 border border-red-500/20 transition flex items-center gap-1"
                        >
                          <UserX className="w-3.5 h-3.5" /> Ablehnen
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}
        </div>

        {/* Section 2: Email Domain Restriction */}
        <div className="space-y-4 mb-8 border-t border-grid pt-6">
          <div className="flex items-center justify-between p-4 rounded-sm bg-subtle border border-grid">
            <div>
              <h4 className="font-mono font-bold text-xs uppercase tracking-wider text-main flex items-center gap-2">
                <Shield className="w-4 h-4 text-emerald-400" /> Registrierung auf E-Mail-Domains beschränken
              </h4>
              <p className="text-xs text-muted mt-0.5">
                Wenn aktiviert, können sich neue Nutzer nur mit freigegebenen E-Mail-Domains (z. B. @verein.de) registrieren.
              </p>
            </div>
            <button
              onClick={handleToggleRestriction}
              className={`px-3 py-1.5 rounded-sm text-xs font-mono font-bold transition ${
                restrictionEnabled
                  ? 'bg-emerald-600 text-white'
                  : 'bg-surface text-muted border border-grid hover:text-main'
              }`}
            >
              {restrictionEnabled ? 'AKTIV' : 'INAKTIV'}
            </button>
          </div>

          {restrictionEnabled && (
            <div className="p-4 rounded-sm bg-subtle border border-grid space-y-3 font-mono">
              <form onSubmit={handleAddDomain} className="flex gap-2">
                <input
                  type="text"
                  placeholder="E-Mail-Domain z. B. verein.de oder @beispiel.org"
                  value={newDomain}
                  onChange={(e) => setNewDomain(e.target.value)}
                  className="flex-1 px-3 py-1.5 rounded-sm input-field text-xs"
                />
                <button
                  type="submit"
                  className="px-4 py-1.5 rounded-sm text-xs font-bold bg-blue-600 hover:bg-blue-500 text-white transition flex items-center gap-1"
                >
                  <Plus className="w-3.5 h-3.5" /> Domain erlauben
                </button>
              </form>

              <div className="space-y-1.5">
                {domainRules.length === 0 ? (
                  <p className="text-xs text-muted italic">[ Noch keine E-Mail-Domains konfiguriert ]</p>
                ) : (
                  domainRules.map((rule) => (
                    <div key={rule.id} className="flex items-center justify-between p-2.5 rounded-sm bg-surface border border-grid text-xs">
                      <span className="font-semibold text-main">{rule.domain}</span>
                      <button
                        onClick={() => handleDeleteDomain(rule.id)}
                        className="text-muted hover:text-red-400 transition"
                      >
                        <Trash2 className="w-3.5 h-3.5" />
                      </button>
                    </div>
                  ))
                )}
              </div>
            </div>
          )}
        </div>

        {/* Section 3: Sidebar Info & Support Boxes */}
        <div className="space-y-4 mb-8 border-t border-grid pt-6">
          <h4 className="font-serif font-bold text-base text-main flex items-center gap-2">
            <Layout className="w-4 h-4 text-amber-500" /> Startseiten Info- & Unterstützen-Boxen
          </h4>

          {/* Community Info Box Settings */}
          <div className="p-4 rounded-sm bg-subtle border border-grid space-y-3">
            <div className="flex items-center justify-between border-b border-grid pb-2">
              <span className="font-mono font-bold text-xs uppercase text-main">📌 Verein & Infos Box</span>
              <button
                type="button"
                onClick={() => setShowCommunityInfoBox(!showCommunityInfoBox)}
                className={`px-2.5 py-1 rounded-sm text-xs font-mono font-bold transition ${
                  showCommunityInfoBox ? 'bg-emerald-600 text-white' : 'bg-surface text-muted border border-grid'
                }`}
              >
                {showCommunityInfoBox ? 'AN' : 'AUS'}
              </button>
            </div>

            {showCommunityInfoBox && (
              <div className="space-y-2 font-mono text-xs">
                <div>
                  <label className="block text-muted mb-1">Titel</label>
                  <input
                    type="text"
                    value={communityInfoTitle}
                    onChange={(e) => setCommunityInfoTitle(e.target.value)}
                    className="w-full px-3 py-1.5 rounded-sm input-field text-xs"
                  />
                </div>
                <div>
                  <label className="block text-muted mb-1">Inhalt</label>
                  <textarea
                    rows={2}
                    value={communityInfoText}
                    onChange={(e) => setCommunityInfoText(e.target.value)}
                    className="w-full px-3 py-1.5 rounded-sm input-field text-xs"
                  />
                </div>
              </div>
            )}
          </div>

          {/* Support Box Settings */}
          <div className="p-4 rounded-sm bg-subtle border border-grid space-y-3">
            <div className="flex items-center justify-between border-b border-grid pb-2">
              <span className="font-mono font-bold text-xs uppercase text-main">❤️ Unterstützen Box</span>
              <button
                type="button"
                onClick={() => setShowSupportBox(!showSupportBox)}
                className={`px-2.5 py-1 rounded-sm text-xs font-mono font-bold transition ${
                  showSupportBox ? 'bg-emerald-600 text-white' : 'bg-surface text-muted border border-grid'
                }`}
              >
                {showSupportBox ? 'AN' : 'AUS'}
              </button>
            </div>

            {showSupportBox && (
              <div className="space-y-2 font-mono text-xs">
                <div>
                  <label className="block text-muted mb-1">Titel</label>
                  <input
                    type="text"
                    value={supportBoxTitle}
                    onChange={(e) => setSupportBoxTitle(e.target.value)}
                    className="w-full px-3 py-1.5 rounded-sm input-field text-xs"
                  />
                </div>
                <div>
                  <label className="block text-muted mb-1">Inhalt</label>
                  <textarea
                    rows={2}
                    value={supportBoxText}
                    onChange={(e) => setSupportBoxText(e.target.value)}
                    className="w-full px-3 py-1.5 rounded-sm input-field text-xs"
                  />
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Section 4: Branding Settings */}
        <form onSubmit={handleSaveBranding} className="border-t border-grid pt-6 space-y-4">
          <h4 className="font-serif font-bold text-base text-main flex items-center gap-2">
            <Palette className="w-4 h-4 text-indigo-400" /> App Branding & Design anpassen
          </h4>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 font-mono text-xs">
            <div>
              <label className="block text-muted mb-1">App Name</label>
              <input
                type="text"
                required
                value={appName}
                onChange={(e) => setAppName(e.target.value)}
                className="w-full px-3 py-1.5 rounded-sm input-field text-xs"
              />
            </div>

            <div>
              <label className="block text-muted mb-1">Primärfarbe</label>
              <div className="flex items-center gap-2">
                <input
                  type="color"
                  value={primaryColor}
                  onChange={(e) => setPrimaryColor(e.target.value)}
                  className="w-8 h-8 rounded-sm border-0 cursor-pointer bg-subtle p-0.5"
                />
                <input
                  type="text"
                  value={primaryColor}
                  onChange={(e) => setPrimaryColor(e.target.value)}
                  className="flex-1 px-3 py-1.5 rounded-sm input-field text-xs font-mono"
                />
              </div>
            </div>

            <div className="sm:col-span-2">
              <label className="block text-muted mb-1">Logo Bild-URL (optional)</label>
              <input
                type="text"
                placeholder="https://beispiel.de/logo.png"
                value={logoUrl}
                onChange={(e) => setLogoUrl(e.target.value)}
                className="w-full px-3 py-1.5 rounded-sm input-field text-xs"
              />
            </div>

            <div className="sm:col-span-2">
              <label className="block text-muted mb-1">Benutzerdefinierte Ankündigung (Banner)</label>
              <textarea
                rows={2}
                placeholder="z. B. Willkommen beim Sommerfest Schichtplaner!"
                value={bannerText}
                onChange={(e) => setBannerText(e.target.value)}
                className="w-full px-3 py-1.5 rounded-sm input-field text-xs"
              />
            </div>
          </div>

          <div className="pt-3 flex justify-end border-t border-grid">
            <button
              type="submit"
              disabled={savingBranding}
              style={{ backgroundColor: 'var(--brand-primary)' }}
              className="px-5 py-2 rounded-sm text-xs font-mono font-bold text-white transition shadow-sm hover:brightness-110"
            >
              {savingBranding ? 'Speichern...' : 'Einstellungen speichern'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
