import { useState, useEffect } from 'react';
import api from '../../store/auth';
import { 
  Save, Building2, Calendar, Mail, Check, 
  ShieldCheck, RefreshCw, ChevronRight, Sparkles,
  Info, Bell, Database, Key, Globe, CheckCircle2
} from 'lucide-react';

interface SettingsForm {
  school_name: string;
  academic_year: string;
  system_email: string;
}

export default function Settings() {
  const [form, setForm] = useState<SettingsForm>({
    school_name: '',
    academic_year: '',
    system_email: '',
  });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState<string | null>(null);

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

  const loadSettings = async () => {
    try {
      setLoading(true);
      const res = await api.get('/settings');
      setForm(res.data);
    } catch (err) {
      console.error('Failed to load settings:', err);
      // Set defaults if not available
      setForm({
        school_name: 'Africa Alert School',
        academic_year: new Date().getFullYear().toString(),
        system_email: 'admin@school.edu',
      });
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      setSaving(true);
      setError(null);
      await api.put('/settings', form);
      setSuccess(true);
      setTimeout(() => setSuccess(false), 3000);
    } catch (err: any) {
      setError(err.response?.data?.message || 'Failed to save settings');
    } finally {
      setSaving(false);
    }
  };

  const handleChange = (field: keyof SettingsForm, value: string) => {
    setForm(prev => ({ ...prev, [field]: value }));
  };

  if (loading) return (
    <div className="flex flex-col justify-center items-center h-[60vh] gap-4 text-text-muted">
      <div className="w-10 h-10 border-4 border-primary border-t-transparent rounded-full animate-spin"></div>
      <p className="font-black uppercase tracking-[3px] text-[0.6rem]">Accessing System Parameters...</p>
    </div>
  );

  return (
    <div className="space-y-10 animate-in fade-in duration-700 pb-10">
      {/* Header Section */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <div>
          <h2 className="text-3xl font-black text-text tracking-tight text-capitalize dark:text-white uppercase">System Environment</h2>
          <nav className="flex text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted gap-2 items-center mt-1">
            <span>Administration</span>
            <ChevronRight size={12} className="text-text-muted/30" />
            <span className="text-primary">Master Configuration</span>
          </nav>
        </div>
        <div className="flex gap-3">
          <button 
            className="flex items-center gap-2 px-6 py-2.5 bg-primary text-white rounded-xl font-bold text-sm hover:bg-primary/90 transition-all shadow-lg shadow-blue-900/10 active:scale-95 disabled:opacity-50"
            onClick={handleSubmit}
            disabled={saving}
          >
            {saving ? <RefreshCw size={18} className="animate-spin" /> : <Save size={18} />}
            {saving ? 'Syncing...' : 'Commit Changes'}
          </button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-10">
        {/* Settings Form (8/12) */}
        <div className="lg:col-span-8 space-y-8">
            <div className="bg-card border border-border rounded-[2.5rem] p-10 shadow-sm relative overflow-hidden">
                <div className="absolute top-0 right-0 w-48 h-48 bg-primary/5 rounded-bl-full -mr-16 -mt-16 group-hover:bg-primary/10 transition-colors"></div>
                
                <div className="relative z-10 space-y-8">
                    <div className="flex items-center gap-4 mb-2">
                        <div className="p-3 rounded-2xl bg-primary/10 text-primary border border-primary/20 shadow-sm">
                            <ShieldCheck size={24} />
                        </div>
                        <div>
                            <h3 className="text-xl font-black text-text tracking-tight uppercase">Core Identity</h3>
                            <p className="text-[0.65rem] font-black text-text-muted uppercase tracking-widest mt-1">Institutional Identification Data</p>
                        </div>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                        <div className="space-y-2">
                            <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1 flex items-center gap-2">
                                <Building2 size={12} /> Institutional Name
                            </label>
                            <input
                                className="form-input text-text"
                                type="text"
                                value={form.school_name}
                                onChange={(e) => handleChange('school_name', e.target.value)}
                                placeholder="e.g., NextGen Academy"
                                required
                            />
                        </div>

                        <div className="space-y-2">
                            <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1 flex items-center gap-2">
                                <Calendar size={12} /> Academic Cycle
                            </label>
                            <input
                                className="form-input text-text"
                                type="text"
                                value={form.academic_year}
                                onChange={(e) => handleChange('academic_year', e.target.value)}
                                placeholder="e.g., 2024-2025"
                                required
                            />
                        </div>
                    </div>

                    <div className="space-y-2">
                        <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1 flex items-center gap-2">
                            <Mail size={12} /> System Communication Hub (Email)
                        </label>
                        <div className="relative">
                            <input
                                className="form-input pl-12 text-text"
                                type="email"
                                value={form.system_email}
                                onChange={(e) => handleChange('system_email', e.target.value)}
                                placeholder="admin@nextgen.edu"
                                required
                            />
                            <div className="absolute left-5 top-1/2 -translate-y-1/2 text-text-muted/50">
                               
                            </div>
                        </div>
                        <p className="text-[0.6rem] font-medium text-text-muted italic px-1 mt-1">* This address will be used for all system-wide transmissions and critical alerts.</p>
                    </div>

                    {error && (
                        <div className="p-4 bg-rose-50 dark:bg-rose-900/20 border border-rose-100 dark:border-rose-800 rounded-2xl flex items-center gap-3 animate-in shake-in duration-300">
                            <Info className="text-rose-600 dark:text-rose-400" size={18} />
                            <span className="text-rose-700 dark:text-rose-300 text-sm font-bold">{error}</span>
                        </div>
                    )}

                    {success && (
                        <div className="p-4 bg-emerald-50 dark:bg-emerald-900/20 border border-emerald-100 dark:border-emerald-800 rounded-2xl flex items-center gap-3 animate-in slide-in-from-bottom-2 duration-300">
                            <CheckCircle2 className="text-emerald-600 dark:text-emerald-400" size={18} />
                            <span className="text-emerald-700 dark:text-emerald-300 text-sm font-bold uppercase tracking-widest">Environment Parameters Synchronized Successfully</span>
                        </div>
                    )}
                </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                <div className="bg-card border border-border rounded-3xl p-8 shadow-sm group hover:border-primary transition-all">
                    <div className="flex items-center gap-4 mb-6">
                        <div className="p-3 rounded-2xl bg-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400 border border-orange-100 dark:border-orange-800">
                            <Key size={20} />
                        </div>
                        <h4 className="text-sm font-black uppercase tracking-widest text-text">Security Protocol</h4>
                    </div>
                    <p className="text-xs font-medium text-text-muted leading-relaxed mb-6">Manage global authentication policies, multi-factor settings, and password expiry intervals.</p>
                    <button className="text-primary text-[0.65rem] font-black uppercase tracking-[3px] hover:underline flex items-center gap-2">Configure Vault <ChevronRight size={14} /></button>
                </div>

                <div className="bg-card border border-border rounded-3xl p-8 shadow-sm group hover:border-primary transition-all">
                    <div className="flex items-center gap-4 mb-6">
                        <div className="p-3 rounded-2xl bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 border border-purple-100 dark:border-purple-800">
                            <Bell size={20} />
                        </div>
                        <h4 className="text-sm font-black uppercase tracking-widest text-text">Alert Intelligence</h4>
                    </div>
                    <p className="text-xs font-medium text-text-muted leading-relaxed mb-6">Define transmission rules for SMS, Email, and Push notifications across all user roles.</p>
                    <button className="text-primary text-[0.65rem] font-black uppercase tracking-[3px] hover:underline flex items-center gap-2">Manage Triggers <ChevronRight size={14} /></button>
                </div>
            </div>
        </div>

        {/* Info Sidebar (4/12) */}
        <div className="lg:col-span-4 space-y-8">
            <div className="bg-slate-900 rounded-[2.5rem] p-10 text-white shadow-2xl relative overflow-hidden group">
                <div className="absolute right-[-40px] bottom-[-40px] opacity-10 group-hover:rotate-12 transition-transform duration-700">
                    <Sparkles size={200} strokeWidth={1} />
                </div>
                <div className="relative z-10">
                    <div className="flex items-center gap-3 mb-6">
                        <div className="p-2.5 bg-white/10 rounded-xl backdrop-blur-md text-blue-400">
                            <Database size={20} />
                        </div>
                        <span className="text-[0.65rem] font-black uppercase tracking-[3px] text-white/40">System Pulse</span>
                    </div>
                    <h4 className="text-xl font-black mb-3 leading-tight tracking-tight uppercase">Platform Health: Optimal</h4>
                    <div className="space-y-4 mb-10">
                        {[
                            { label: 'Database Sync', val: 'Synchronized' },
                            { label: 'API Latency', val: '24ms' },
                            { label: 'System Version', val: '2.4.0-GEN' },
                        ].map(m => (
                            <div key={m.label} className="flex justify-between items-center border-b border-white/5 pb-2">
                                <span className="text-[0.6rem] font-black uppercase text-white/40">{m.label}</span>
                                <span className="text-xs font-bold text-blue-400">{m.val}</span>
                            </div>
                        ))}
                    </div>
                    <button className="w-full py-4 bg-white/10 hover:bg-white/20 text-white rounded-xl text-[0.65rem] font-black uppercase tracking-widest transition-all border border-white/10">
                        Run Diagnostic Audit
                    </button>
                </div>
            </div>

            <div className="bg-muted/50 border border-border rounded-[2rem] p-8">
                <div className="flex items-center gap-3 mb-6">
                    <Info className="text-primary" size={18} />
                    <h4 className="text-[0.7rem] font-black uppercase tracking-[3px] text-text">Technical Context</h4>
                </div>
                <p className="text-xs font-medium text-text-muted leading-relaxed">
                    System settings are applied globally. Modifications to the <span className="text-primary font-bold">Academic Cycle</span> may affect historical data visibility and report generation intelligence.
                </p>
            </div>
        </div>
      </div>
    </div>
  );
}
