import { useState, useEffect } from 'react';
import api, { useAuthStore } from '../store/auth';
import { 
  User, Mail, Phone, MapPin, Key, Save, 
  Camera, ChevronRight, CheckCircle2, Sparkles,
  Shield, Info, LogOut
} from 'lucide-react';

export default function Profile() {
  const { user, logout } = useAuthStore();
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);
  
  const [form, setForm] = useState({
    first_name: '',
    last_name: '',
    email: '',
    phone: '',
    address: '',
    current_password: '',
    new_password: '',
    confirm_password: '',
  });

  useEffect(() => {
    if (user) {
      setForm(prev => ({
        ...prev,
        first_name: user.first_name || '',
        last_name: user.last_name || '',
        email: user.email || '',
        // phone and address might need fetching or be in user object
      }));
      
      // Fetch full profile if needed
      api.get(`/users/${user.id}`).then(res => {
          setForm(prev => ({
              ...prev,
              phone: res.data.phone || '',
              address: res.data.address || '',
          }));
      }).catch(console.error);
    }
  }, [user]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (form.new_password && form.new_password !== form.confirm_password) {
        alert("Passwords do not match");
        return;
    }

    setLoading(true);
    try {
      await api.put(`/users/${user?.id}`, {
        first_name: form.first_name,
        last_name: form.last_name,
        email: form.email,
        phone: form.phone,
        address: form.address,
        ...(form.new_password ? { password: form.new_password } : {})
      });
      setSuccess(true);
      setTimeout(() => setSuccess(false), 3000);
    } catch (err) {
      alert('Failed to update profile records.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="max-w-5xl mx-auto space-y-10 animate-in fade-in duration-700 pb-10">
      {/* Premium Header */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-end gap-6">
        <div>
          <div className="flex items-center gap-3 mb-2">
            <div className="p-2 bg-primary/10 rounded-xl text-primary">
              <User size={20} />
            </div>
            <span className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted">Account Identity</span>
          </div>
          <h1 className="text-4xl font-black text-text tracking-tighter capitalize">Personal Profile</h1>
          <p className="text-text-muted text-lg font-medium">Manage your digital identity and system credentials.</p>
        </div>
        
        <button 
            onClick={logout}
            className="flex items-center gap-2 px-6 py-3 bg-rose-50 dark:bg-rose-900/20 text-rose-600 dark:text-rose-400 rounded-2xl font-bold text-sm hover:bg-rose-100 dark:hover:bg-rose-900/30 transition-all active:scale-95 border border-rose-100 dark:border-rose-800"
        >
            <LogOut size={18} />
            Secure Logout
        </button>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-10">
        
        {/* Left Column: Visual Profile (4/12) */}
        <div className="lg:col-span-4 space-y-8">
            <div className="bg-card border border-border rounded-[3rem] p-10 text-center shadow-sm relative overflow-hidden group">
                <div className="absolute top-0 left-0 w-full h-32 bg-slate-900 group-hover:h-36 transition-all duration-500"></div>
                
                <div className="relative z-10 mt-12 inline-block">
                    <div className="w-32 h-32 rounded-[2.5rem] bg-card p-1.5 shadow-2xl relative border border-border">
                        <div className="w-full h-full rounded-[2.2rem] bg-gradient-to-br from-primary to-slate-900 flex items-center justify-center text-white text-4xl font-black shadow-inner overflow-hidden">
                            {user?.first_name?.[0]}{user?.last_name?.[0]}
                        </div>
                        <button className="absolute -bottom-2 -right-2 w-10 h-10 bg-card border border-border rounded-xl flex items-center justify-center text-primary shadow-lg hover:scale-110 transition-transform">
                            <Camera size={18} />
                        </button>
                    </div>
                </div>

                <div className="mt-8 relative z-10">
                    <h2 className="text-2xl font-black text-text tracking-tight">{user?.first_name} {user?.last_name}</h2>
                    <div className="inline-flex items-center gap-2 px-3 py-1 bg-primary/5 text-primary rounded-full border border-primary/10 text-[0.6rem] font-black uppercase tracking-widest mt-2">
                        <Shield size={12} />
                        {user?.role} Portal
                    </div>
                    <p className="text-text-muted text-[0.8rem] font-medium mt-4 font-mono">UID-2024-{user?.id.toString().padStart(4, '0')}</p>
                </div>

                <div className="mt-10 pt-8 border-t border-border grid grid-cols-2 gap-4 relative z-10">
                    <div className="text-center">
                        <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-widest">Active Since</p>
                        <p className="text-sm font-black text-text">Jan 2024</p>
                    </div>
                    <div className="text-center border-l border-border">
                        <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-widest">Status</p>
                        <p className="text-sm font-black text-emerald-500">Verified</p>
                    </div>
                </div>
            </div>

            <div className="bg-slate-900 rounded-[2.5rem] p-8 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={180} strokeWidth={1} />
                </div>
                <div className="relative z-10">
                    <h4 className="text-[0.6rem] font-black uppercase tracking-[3px] text-white/40 mb-4 px-1">Security Intel</h4>
                    <p className="text-[0.85rem] font-medium text-blue-50/80 leading-relaxed mb-6">
                        Keep your system credentials unique and updated regularly to ensure maximum security for your academic records.
                    </p>
                    <div className="flex items-center gap-3 p-4 bg-white/5 rounded-2xl border border-white/5 backdrop-blur-sm">
                        <div className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></div>
                        <span className="text-[0.65rem] font-black uppercase tracking-widest text-emerald-400">Two-Factor Enabled</span>
                    </div>
                </div>
            </div>
        </div>

        {/* Right Column: Edit Form (8/12) */}
        <div className="lg:col-span-8">
            <div className="bg-card border border-border rounded-[3rem] overflow-hidden shadow-sm">
                <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center">
                    <div className="flex items-center gap-3">
                        <div className="p-2 bg-primary/10 rounded-xl text-primary">
                            <Info size={18} />
                        </div>
                        <p className="text-[0.7rem] font-black uppercase tracking-[3px] text-text">Intelligence Records</p>
                    </div>
                    {success && (
                        <div className="flex items-center gap-2 text-emerald-500 animate-in fade-in slide-in-from-right-4">
                            <CheckCircle2 size={16} />
                            <span className="text-[0.65rem] font-black uppercase tracking-widest">Records Updated</span>
                        </div>
                    )}
                </div>

                <form onSubmit={handleSubmit} className="p-10 space-y-10">
                    {/* Identification Section */}
                    <div className="space-y-6">
                        <h3 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted border-l-4 border-primary pl-4">Account Identity</h3>
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div className="space-y-2">
                                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Legal First Name</label>
                                <div className="relative">
                                    <User size={16} className="absolute left-5 top-1/2 -translate-y-1/2 text-text-muted/50" />
                                    <input className="w-full bg-muted/50 border border-border rounded-2xl pl-12 pr-4 py-4 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-primary/5 focus:bg-card focus:border-primary transition-all text-text" value={form.first_name} onChange={e => setForm({...form, first_name: e.target.value})} />
                                </div>
                            </div>
                            <div className="space-y-2">
                                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Legal Last Name</label>
                                <input className="w-full bg-muted/50 border border-border rounded-2xl px-5 py-4 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-primary/5 focus:bg-card focus:border-primary transition-all text-text" value={form.last_name} onChange={e => setForm({...form, last_name: e.target.value})} />
                            </div>
                        </div>
                    </div>

                    {/* Contact Section */}
                    <div className="space-y-6">
                        <h3 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted border-l-4 border-emerald-500 pl-4">Contact Intelligence</h3>
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div className="space-y-2">
                                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">System Email</label>
                                <div className="relative">
                                    <Mail size={16} className="absolute left-5 top-1/2 -translate-y-1/2 text-text-muted/50" />
                                    <input className="w-full bg-muted/50 border border-border rounded-2xl pl-12 pr-4 py-4 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-primary/5 focus:bg-card focus:border-primary transition-all text-text" type="email" value={form.email} onChange={e => setForm({...form, email: e.target.value})} />
                                </div>
                            </div>
                            <div className="space-y-2">
                                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Direct Line</label>
                                <div className="relative">
                                    <Phone size={16} className="absolute left-5 top-1/2 -translate-y-1/2 text-text-muted/50" />
                                    <input className="w-full bg-muted/50 border border-border rounded-2xl pl-12 pr-4 py-4 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-primary/5 focus:bg-card focus:border-primary transition-all text-text" value={form.phone} onChange={e => setForm({...form, phone: e.target.value})} placeholder="+1 (234) 567-890" />
                                </div>
                            </div>
                        </div>
                        <div className="space-y-2">
                            <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Physical Address Registry</label>
                            <div className="relative">
                                <MapPin size={16} className="absolute left-5 top-6 text-text-muted/50" />
                                <textarea className="w-full bg-muted/50 border border-border rounded-2xl pl-12 pr-4 py-4 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-primary/5 focus:bg-card focus:border-primary transition-all text-text" rows={3} value={form.address} onChange={e => setForm({...form, address: e.target.value})} placeholder="Enter full residence details..." />
                            </div>
                        </div>
                    </div>

                    {/* Security Section */}
                    <div className="space-y-6">
                        <h3 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted border-l-4 border-orange-500 pl-4">Security Protocol</h3>
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div className="space-y-2">
                                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Initialize New Password</label>
                                <div className="relative">
                                    <Key size={16} className="absolute left-5 top-1/2 -translate-y-1/2 text-text-muted/50" />
                                    <input className="w-full bg-muted/50 border border-border rounded-2xl pl-12 pr-4 py-4 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-primary/5 focus:bg-card focus:border-primary transition-all text-text" type="password" placeholder="Leave blank to maintain current" value={form.new_password} onChange={e => setForm({...form, new_password: e.target.value})} />
                                </div>
                            </div>
                            <div className="space-y-2">
                                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Confirm Protocol</label>
                                <input className="w-full bg-muted/50 border border-border rounded-2xl px-5 py-4 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-primary/5 focus:bg-card focus:border-primary transition-all text-text" type="password" placeholder="Repeat new password" value={form.confirm_password} onChange={e => setForm({...form, confirm_password: e.target.value})} />
                            </div>
                        </div>
                    </div>

                    <div className="pt-8 border-t border-border">
                        <button 
                            type="submit" 
                            disabled={loading}
                            className="w-full py-5 bg-primary hover:bg-primary/90 text-white font-black uppercase tracking-widest text-xs rounded-2xl transition-all shadow-xl shadow-blue-900/10 active:scale-95 flex items-center justify-center gap-3 disabled:opacity-50 disabled:grayscale"
                        >
                            {loading ? <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" /> : <Save size={18} />}
                            {loading ? 'Committing Changes...' : 'Commit Profile Intelligence'}
                        </button>
                    </div>
                </form>
            </div>
        </div>
      </div>
    </div>
  );
}
