import { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import api, { useAuthStore } from '../store/auth';
import {
  User, Mail, Phone, MapPin, Key, Save,
  Camera, ChevronRight, CheckCircle2, Sparkles,
  Shield, Info, LogOut, CreditCard, Calendar, Clock, Download, FileText, Plus,
  X, AlertCircle, FileSignature, Type
} from 'lucide-react';
import FontSizeController from '../components/FontSizeController';

const STAFF_ROLES = [
  'school_admin', 'systems_admin', 'principal', 'hr', 'bursar',
  'teacher', 'accountant', 'librarian', 'nurse', 'clubs_head',
];

type Gender = 'male' | 'female' | 'other';

export default function Profile() {
  const { user, logout, updateUser } = useAuthStore();
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);
  const [successMsg, setSuccessMsg] = useState('');
  const [errorMsg, setErrorMsg] = useState('');
  const [activeTab, setActiveTab] = useState('settings'); // settings, payslips, leave
  const [payslips, setPayslips] = useState<any[]>([]);
  const [leaveRequests, setLeaveRequests] = useState<any[]>([]);

  const isStaff = user ? STAFF_ROLES.includes(user.role) : false;

  const [showLeaveModal, setShowLeaveModal] = useState(false);
  const [leaveDetail, setLeaveDetail] = useState<any | null>(null);
  const [leaveResultModal, setLeaveResultModal] = useState<{ tone: 'success' | 'error'; title: string; message: string } | null>(null);
  const [leaveTypes, setLeaveTypes] = useState<any[]>([]);

  const [form, setForm] = useState({
    first_name: '',
    last_name: '',
    email: '',
    phone: '',
    address: '',
    gender: '' as Gender | '',
    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 || '',
      }));
      
      api.get(`/users/${user.id}`).then(res => {
          setForm(prev => ({
              ...prev,
              phone: res.data.phone || '',
              address: res.data.address || '',
              gender: res.data.gender || '',
          }));
      }).catch(console.error);

      if (isStaff) {
          loadStaffData();
      }
    }
  }, [user]);

  const loadStaffData = async () => {
      try {
          const [ps, lr, lt] = await Promise.all([
              api.get('/hr/payslips'),
              api.get('/hr/leave-requests'),
              api.get('/hr/leave-types'),
          ]);
          setPayslips(ps.data || []);
          setLeaveRequests(lr.data || []);
          setLeaveTypes(lt.data || []);
      } catch (err) {}
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setErrorMsg('');
    setSuccessMsg('');

    if (form.new_password) {
      if (form.new_password.length < 6) {
        setErrorMsg("New password must be at least 6 characters");
        return;
      }
      if (form.new_password !== form.confirm_password) {
        setErrorMsg("Passwords do not match");
        return;
      }
      if (!form.current_password) {
        setErrorMsg("Current password is required to update security key");
        return;
      }
    }

    setLoading(true);
    try {
      const res = 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,
        gender: form.gender,
      });
      updateUser(res.data);

      let passwordChanged = false;
      if (form.new_password) {
        await api.put(`/users/${user?.id}/password`, {
          current_password: form.current_password,
          new_password: form.new_password,
        });
        passwordChanged = true;
        setForm(prev => ({
          ...prev,
          current_password: '',
          new_password: '',
          confirm_password: '',
        }));
      }

      setSuccess(true);
      setSuccessMsg(passwordChanged ? 'Profile and security credentials updated successfully!' : 'Profile records updated successfully!');
      setTimeout(() => {
        setSuccess(false);
        setSuccessMsg('');
      }, 4000);
    } catch (err: any) {
      setErrorMsg(err.response?.data?.error || 'Failed to update profile or security records.');
    } finally {
      setLoading(false);
    }
  };

  const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

  return (
    <div className="max-w-6xl 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">Digital Identity</span>
          </div>
          <h1 className="text-4xl font-black text-text tracking-tighter capitalize">{`${user?.first_name}'s Profile`}</h1>
          <p className="text-text-muted text-lg font-medium">System access profile and personal information.</p>
        </div>
        
        <div className="flex gap-3">
            <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 transition-all active:scale-95 border border-rose-100 dark:border-rose-800"
            >
                <LogOut size={18} />
                Logout
            </button>
        </div>
      </div>

      {/* Tabs */}
      {isStaff && (
      <div className="flex p-1 bg-card border border-border rounded-2xl w-fit">
          {[
              { id: 'settings', label: 'Security & Profile', icon: Shield },
              { id: 'payslips', label: 'My Payslips', icon: CreditCard },
              { id: 'leave', label: 'Leave History', icon: Calendar },
          ].map(tab => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`flex items-center gap-2 px-6 py-2.5 rounded-xl text-[0.7rem] font-black uppercase tracking-widest transition-all ${activeTab === tab.id ? 'bg-primary text-white shadow-lg shadow-blue-900/10' : 'text-text-muted hover:text-text'}`}
              >
                  <tab.icon size={14} />
                  {tab.label}
              </button>
          ))}
      </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 sm:gap-10 min-w-0 max-w-full">
        
        {/* Left Column: Visual Profile (4/12) */}
        <div className="lg:col-span-4 min-w-0 max-w-full 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">
                        <img 
                            src={user?.profile_image || '/avatar-placeholder.jpg'} 
                            alt="Avatar" 
                            className="w-full h-full rounded-[2.2rem] object-cover" 
                        />
                        <button
                            onClick={() => {
                                const input = document.createElement('input');
                                input.type = 'file';
                                input.accept = 'image/*';
                                input.onchange = async (e: any) => {
                                    const file = e.target.files?.[0];
                                    if (!file) return;
                                    
                                    const formData = new FormData();
                                    formData.append('avatar', file);
                                    
                                    try {
                                        setLoading(true);
                                        const res = await api.post(`/users/${user?.id}/avatar`, formData, {
                                            headers: {
                                                'Content-Type': 'multipart/form-data'
                                            }
                                        });
                                        if (res.data.success && res.data.avatarUrl) {
                                            updateUser({ profile_image: res.data.avatarUrl });
                                            setSuccessMsg('Avatar updated successfully!');
                                            setTimeout(() => setSuccessMsg(''), 3000);
                                        }
                                    } catch (err: any) {
                                        setErrorMsg(err.response?.data?.error || 'Failed to upload avatar.');
                                        setTimeout(() => setErrorMsg(''), 4000);
                                    } finally {
                                        setLoading(false);
                                    }
                                };
                                input.click();
                            }}
                            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"
                            title="Change avatar"
                        >
                            <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">REG-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">Digital Auth</p>
                        <p className="text-sm font-black text-emerald-500">Verified</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-text">Active</p>
                    </div>
                </div>
            </div>

            {activeTab === 'settings' && (
                <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</h4>
                        <p className="text-[0.85rem] font-medium text-blue-50/80 leading-relaxed mb-6">
                            Maintain profile integrity by updating credentials periodically. System access logs are monitored for security protocol compliance.
                        </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">Identity Secure</span>
                        </div>
                    </div>
                </div>
            )}
        </div>

        {/* Right Column: Dynamic Content (8/12) */}
        <div className="lg:col-span-8">
            {activeTab === 'settings' ? (
                <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">Personal Info</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">
                        {errorMsg && (
                            <div className="p-4 bg-rose-50 dark:bg-rose-950/20 border border-rose-100 dark:border-rose-900/50 rounded-2xl flex items-center gap-3 text-rose-600 dark:text-rose-400 animate-in slide-in-from-top-2 duration-300">
                                <Info size={16} />
                                <span className="text-xs font-bold">{errorMsg}</span>
                            </div>
                        )}
                        {successMsg && (
                            <div className="p-4 bg-emerald-50 dark:bg-emerald-950/20 border border-emerald-100 dark:border-emerald-900/50 rounded-2xl flex items-center gap-3 text-emerald-600 dark:text-emerald-400 animate-in slide-in-from-top-2 duration-300">
                                <CheckCircle2 size={16} />
                                <span className="text-xs font-bold">{successMsg}</span>
                            </div>
                        )}
                        <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">Identification</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>
                                    <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.first_name} onChange={e => setForm({...form, first_name: e.target.value})} />
                                </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 className="space-y-2 md:col-span-2">
                                    <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Gender</label>
                                    <select 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 appearance-none cursor-pointer" value={form.gender} onChange={e => setForm({...form, gender: e.target.value as Gender | ''})}>
                                        <option value="">Not specified</option>
                                        <option value="male">Male</option>
                                        <option value="female">Female</option>
                                        <option value="other">Other</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <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 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">System Email</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="email" value={form.email} onChange={e => setForm({...form, email: e.target.value})} />
                                </div>
                                <div className="space-y-2">
                                    <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Direct Line</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.phone} onChange={e => setForm({...form, phone: e.target.value})} />
                                </div>
                            </div>
                        </div>

                        <div className="space-y-6 min-w-0 max-w-full">
                            <h3 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted border-l-4 border-amber-500 pl-4 break-words">User Preferences & Accessibility</h3>
                            <div className="p-6 rounded-2xl border border-border bg-muted/30 flex flex-col md:flex-row md:items-center justify-between gap-6 min-w-0 max-w-full">
                                <div className="space-y-1 min-w-0 flex-1">
                                    <h4 className="font-bold text-sm text-text flex items-center gap-2 break-words">
                                        <Type size={16} className="text-primary shrink-0" />
                                        <span>Interface Text Size Scale</span>
                                    </h4>
                                    <p className="text-xs text-text-muted leading-relaxed break-words">
                                        Customize font scale (100% to 200%) for optimal readability across all portal pages. Layout adapts dynamically without horizontal clipping.
                                    </p>
                                </div>
                                <div className="shrink-0 max-w-full">
                                    <FontSizeController />
                                </div>
                            </div>
                        </div>

                        <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-3 gap-6">
                                <div className="space-y-2">
                                    <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Current Password</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="••••••••" value={form.current_password} onChange={e => setForm({...form, current_password: e.target.value})} />
                                </div>
                                <div className="space-y-2">
                                    <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">New Password</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="••••••••" value={form.new_password} onChange={e => setForm({...form, new_password: e.target.value})} />
                                </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="••••••••" 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 active:scale-95 flex items-center justify-center gap-3"
                            >
                                {loading ? <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin" /> : <Save size={18} />}
                                {loading ? 'Updating...' : 'Save Profile'}
                            </button>
                        </div>
                    </form>
                </div>
            ) : activeTab === 'payslips' ? (
                <div className="space-y-6">
                    <div className="bg-card border border-border rounded-[3rem] overflow-hidden shadow-sm">
                        <div className="p-8 border-b border-border bg-muted/50 flex justify-between items-center">
                            <div className="flex items-center gap-3">
                                <div className="p-2 bg-emerald-500/10 rounded-xl text-emerald-600">
                                    <CreditCard size={18} />
                                </div>
                                <h3 className="text-[0.7rem] font-black uppercase tracking-[3px] text-text">Remuneration Archive</h3>
                            </div>
                        </div>
                        <div className="divide-y divide-border">
                            {payslips.length === 0 ? (
                                <div className="p-20 text-center">
                                    <FileText size={48} className="mx-auto text-text-muted/20 mb-4" />
                                    <p className="text-text-muted font-bold uppercase tracking-widest text-[0.6rem]">No remuneration records identified</p>
                                </div>
                            ) : payslips.map(ps => (
                                <div key={ps.id} className="p-8 hover:bg-muted/30 transition-all flex flex-col md:flex-row justify-between items-center gap-6">
                                    <div className="flex items-center gap-4">
                                        <div className="w-14 h-14 rounded-2xl bg-card border border-border flex items-center justify-center text-primary shadow-sm">
                                            <Calendar size={24} />
                                        </div>
                                        <div>
                                            <p className="text-lg font-black text-text">{months[ps.period_month - 1]} {ps.period_year}</p>
                                            <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-widest mt-1">Status: {ps.status}</p>
                                        </div>
                                    </div>
                                    <div className="flex items-center gap-10">
                                        <div className="text-right">
                                            <p className="text-xl font-black text-emerald-500">${ps.net_salary.toLocaleString()}</p>
                                            <p className="text-[0.55rem] font-black text-text-muted uppercase tracking-widest mt-1">Net Allocation</p>
                                        </div>
                                        <button
                                            onClick={() => {
                                                // Build a minimal payslip CSV for the current record (download-only stub).
                                                const headers = ['Field', 'Value'];
                                                const rows = [
                                                    ['Period', `${months[ps.period_month - 1]} ${ps.period_year}`],
                                                    ['Status', ps.status],
                                                    ['Net Salary', `$${ps.net_salary.toLocaleString()}`],
                                                ];
                                                const csv = [headers, ...rows].map(r => r.map(c => `"${String(c).replace(/"/g, '""')}"`).join(',')).join('\n');
                                                const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
                                                const url = URL.createObjectURL(blob);
                                                const a = document.createElement('a');
                                                a.href = url;
                                                a.download = `payslip_${ps.period_year}_${String(ps.period_month).padStart(2, '0')}.csv`;
                                                document.body.appendChild(a);
                                                a.click();
                                                document.body.removeChild(a);
                                                URL.revokeObjectURL(url);
                                            }}
                                            className="p-4 bg-primary text-white rounded-2xl shadow-lg hover:bg-primary/90 transition-all active:scale-95"
                                            title="Download payslip"
                                        >
                                            <Download size={20} />
                                        </button>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                </div>
            ) : (
                <div className="bg-card border border-border rounded-[3rem] overflow-hidden shadow-sm">
                    <div className="p-8 border-b border-border bg-muted/50 flex justify-between items-center">
                        <div className="flex items-center gap-3">
                            <div className="p-2 bg-orange-500/10 rounded-xl text-orange-600">
                                <Calendar size={18} />
                            </div>
                            <h3 className="text-[0.7rem] font-black uppercase tracking-[3px] text-text">Absence Management</h3>
                        </div>
                        <button
                            onClick={() => setShowLeaveModal(true)}
                            className="flex items-center gap-2 px-5 py-2.5 bg-primary text-white rounded-xl font-black text-[0.65rem] uppercase tracking-widest shadow-lg hover:bg-primary/90 transition-all active:scale-95"
                        >
                            <Plus size={14} /> Request Leave
                        </button>
                    </div>
                    <div className="overflow-x-auto">
                        <table className="w-full text-left">
                            <thead>
                                <tr className="bg-muted/30 border-b border-border">
                                    <th className="px-8 py-5 text-[0.6rem] font-black text-primary uppercase tracking-widest">Protocol Type</th>
                                    <th className="px-8 py-5 text-[0.6rem] font-black text-primary uppercase tracking-widest">Duration Profile</th>
                                    <th className="px-8 py-5 text-[0.6rem] font-black text-primary uppercase tracking-widest">Auth Status</th>
                                    <th className="px-8 py-5 text-[0.6rem] font-black text-primary uppercase tracking-widest text-right">Records</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-border">
                                {leaveRequests.length === 0 ? (
                                    <tr>
                                        <td colSpan={4} className="p-20 text-center">
                                            <Clock size={40} className="mx-auto text-text-muted/20 mb-4" />
                                            <p className="text-text-muted font-bold uppercase tracking-widest text-[0.6rem]">No leave records</p>
                                        </td>
                                    </tr>
                                ) : leaveRequests.map(lr => (
                                    <tr key={lr.id} className="hover:bg-muted/30 transition-colors">
                                        <td className="px-8 py-5">
                                            <p className="text-sm font-bold text-text">{lr.leave_type}</p>
                                            <p className="text-[0.6rem] text-text-muted uppercase tracking-widest mt-1">UID: {lr.uid.substring(0, 8)}</p>
                                        </td>
                                        <td className="px-8 py-5">
                                            <p className="text-xs font-bold text-text">{new Date(lr.start_date).toLocaleDateString()} - {new Date(lr.end_date).toLocaleDateString()}</p>
                                            <p className="text-[0.6rem] text-text-muted font-medium mt-1 uppercase">{lr.days_count} Working Days</p>
                                        </td>
                                        <td className="px-8 py-5">
                                            <span className={`px-3 py-1 rounded-lg text-[0.6rem] font-black uppercase tracking-widest border ${
                                                lr.status === 'approved' ? 'bg-emerald-50 text-emerald-600 border-emerald-100' :
                                                lr.status === 'rejected' ? 'bg-rose-50 text-rose-600 border-rose-100' :
                                                'bg-orange-50 text-orange-600 border-orange-100'
                                            }`}>
                                                {lr.status}
                                            </span>
                                        </td>
                                        <td className="px-8 py-5 text-right">
                                            <button
                                                onClick={() => setLeaveDetail(lr)}
                                                className="text-text-muted hover:text-primary transition-all"
                                                title="View leave record details"
                                            ><Info size={18} /></button>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </div>
            )}
        </div>
      </div>

      {showLeaveModal && (
        <LeaveRequestModal
          leaveTypes={leaveTypes}
          onClose={() => setShowLeaveModal(false)}
          onSuccess={(msg) => {
            setShowLeaveModal(false);
            setLeaveResultModal({ tone: 'success', title: 'Request submitted', message: msg });
            loadStaffData();
          }}
          onError={(msg) => {
            setShowLeaveModal(false);
            setLeaveResultModal({ tone: 'error', title: 'Submission failed', message: msg });
          }}
        />
      )}

      {leaveDetail && (
        <LeaveDetailsModal
          record={leaveDetail}
          onClose={() => setLeaveDetail(null)}
        />
      )}

      {leaveResultModal && (
        <LeaveResultModal
          tone={leaveResultModal.tone}
          title={leaveResultModal.title}
          message={leaveResultModal.message}
          onClose={() => setLeaveResultModal(null)}
        />
      )}
    </div>
  );
}

function ModalShell({
  onClose,
  title,
  subtitle,
  children,
  footer,
  size = 'md',
}: {
  onClose: () => void;
  title: string;
  subtitle?: string;
  children: React.ReactNode;
  footer?: React.ReactNode;
  size?: 'sm' | 'md' | 'lg';
}) {
  const maxW = size === 'sm' ? 'max-w-md' : size === 'lg' ? 'max-w-3xl' : 'max-w-2xl';
  return createPortal(
    <div className="fixed inset-0 bg-[#002147]/80 backdrop-blur-md z-[150] flex items-center justify-center p-4" onClick={onClose}>
      <div className={`bg-card rounded-[2.5rem] w-full ${maxW} border border-border shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200`} onClick={(e) => e.stopPropagation()}>
        <div className="p-8 border-b border-border bg-muted/50 flex justify-between items-center relative overflow-hidden">
          <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12 pointer-events-none">
            <Sparkles size={180} />
          </div>
          <div className="relative z-10">
            <h2 className="text-2xl font-black text-text uppercase tracking-tight">{title}</h2>
            {subtitle && (
              <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">{subtitle}</p>
            )}
          </div>
          <button
            onClick={onClose}
            className="relative z-10 w-10 h-10 flex items-center justify-center rounded-xl bg-card border border-border text-text-muted hover:text-rose-500 transition-all"
            title="Close"
          >
            <X size={20} />
          </button>
        </div>
        <div className="p-8 space-y-6 max-h-[70vh] overflow-y-auto custom-scrollbar">{children}</div>
        {footer && (
          <div className="px-8 py-5 border-t border-border bg-muted/30 flex justify-end gap-3">
            {footer}
          </div>
        )}
      </div>
    </div>
  ,
    document.body
  );
}

function LeaveRequestModal({
  leaveTypes,
  onClose,
  onSuccess,
  onError,
}: {
  leaveTypes: any[];
  onClose: () => void;
  onSuccess: (msg: string) => void;
  onError: (msg: string) => void;
}) {
  const today = new Date().toISOString().slice(0, 10);
  const [start, setStart] = useState(today);
  const [end, setEnd] = useState(today);
  const [leaveTypeId, setLeaveTypeId] = useState<number | ''>(leaveTypes[0]?.id ?? '');
  const [reason, setReason] = useState('');
  const [submitting, setSubmitting] = useState(false);

  const workingDays = (() => {
    if (!start || !end || new Date(end) < new Date(start)) return 0;
    const s = new Date(start);
    const e = new Date(end);
    let count = 0;
    for (let d = new Date(s); d <= e; d.setDate(d.getDate() + 1)) {
      const day = d.getDay();
      if (day !== 0 && day !== 6) count += 1;
    }
    return count;
  })();

  const submit = async () => {
    if (!start || !end) {
      onError('Start and end dates are required.');
      return;
    }
    if (new Date(end) < new Date(start)) {
      onError('End date must be on or after start date.');
      return;
    }
    if (!leaveTypeId) {
      onError('Leave type is required.');
      return;
    }
    setSubmitting(true);
    try {
      await api.post('/hr/leave-requests', {
        start_date: start,
        end_date: end,
        leave_type_id: leaveTypeId,
        days_count: workingDays,
        reason: reason || null,
      });
      onSuccess('Leave request submitted for review.');
    } catch (err: any) {
      onError(err.response?.data?.error || 'Failed to submit leave request.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <ModalShell
      onClose={onClose}
      title="Request Leave"
      subtitle="Absence Management Protocol"
      footer={
        <>
          <button
            type="button"
            onClick={onClose}
            className="px-6 py-3 rounded-xl border border-border text-text-muted font-black text-xs uppercase tracking-widest hover:text-text transition-all"
          >
            Cancel
          </button>
          <button
            type="button"
            onClick={submit}
            disabled={submitting}
            className="flex-1 py-3 bg-primary text-white rounded-xl font-black uppercase text-[0.65rem] tracking-widest shadow-lg shadow-blue-900/10 active:scale-95 transition-all disabled:opacity-50 flex items-center justify-center gap-2"
          >
            {submitting ? (
              <div className="w-3.5 h-3.5 border-2 border-white border-t-transparent rounded-full animate-spin" />
            ) : (
              <FileSignature size={14} />
            )}
            {submitting ? 'Submitting…' : 'Submit Request'}
          </button>
        </>
      }
    >
      <div className="space-y-4">
        <h3 className="text-[0.65rem] font-black uppercase tracking-[3px] text-primary border-b border-border pb-2">Leave Window</h3>
        <div className="grid grid-cols-2 gap-4">
          <div className="space-y-1.5">
            <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Start Date</label>
            <input
              type="date"
              value={start}
              onChange={e => setStart(e.target.value)}
              className="w-full bg-muted/50 border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text"
            />
          </div>
          <div className="space-y-1.5">
            <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">End Date</label>
            <input
              type="date"
              value={end}
              min={start}
              onChange={e => setEnd(e.target.value)}
              className="w-full bg-muted/50 border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text"
            />
          </div>
        </div>
        <div className="space-y-1.5">
          <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Leave Type</label>
          <select
            value={leaveTypeId}
            onChange={e => setLeaveTypeId(e.target.value ? Number(e.target.value) : '')}
            className="w-full bg-muted/50 border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text"
          >
            {leaveTypes.length === 0 ? (
              <option value="">No leave types configured</option>
            ) : (
              leaveTypes.map(lt => (
                <option key={lt.id} value={lt.id}>{lt.name}</option>
              ))
            )}
          </select>
        </div>
        <div className="flex items-center justify-between px-4 py-2 rounded-xl bg-primary/5 border border-primary/10">
          <span className="text-[0.6rem] font-black uppercase tracking-widest text-primary">Working Days</span>
          <span className="text-xs font-black text-primary">{workingDays}</span>
        </div>
        <div className="space-y-1.5">
          <label className="text-[0.6rem] font-black uppercase text-text-muted px-1">Reason (optional)</label>
          <textarea
            value={reason}
            onChange={e => setReason(e.target.value)}
            rows={3}
            placeholder="Brief context for the absence"
            className="w-full bg-muted/50 border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text resize-none"
          />
        </div>
      </div>
    </ModalShell>
  );
}

function LeaveDetailsModal({ record, onClose }: { record: any; onClose: () => void }) {
  const fields = [
    { label: 'UID', value: record.uid },
    { label: 'Type', value: record.leave_type },
    { label: 'Start', value: record.start_date },
    { label: 'End', value: record.end_date },
    { label: 'Working Days', value: String(record.days_count ?? '—') },
    { label: 'Status', value: record.status },
  ];
  return (
    <ModalShell onClose={onClose} title="Leave Record" subtitle={`UID ${record.uid.substring(0, 8)}`}>
      <dl className="divide-y divide-border border border-border rounded-2xl overflow-hidden">
        {fields.map(f => (
          <div key={f.label} className="flex items-center justify-between gap-4 px-5 py-4 bg-card">
            <dt className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted">{f.label}</dt>
            <dd className="text-sm font-bold text-text text-right break-all">{f.value}</dd>
          </div>
        ))}
      </dl>
    </ModalShell>
  );
}

function LeaveResultModal({
  tone,
  title,
  message,
  onClose,
}: {
  tone: 'success' | 'error';
  title: string;
  message: string;
  onClose: () => void;
}) {
  const Icon = tone === 'success' ? CheckCircle2 : AlertCircle;
  const toneClasses = tone === 'success'
    ? 'text-emerald-500 bg-emerald-500/10'
    : 'text-rose-500 bg-rose-500/10';
  return (
    <ModalShell
      onClose={onClose}
      title={title}
      footer={
        <button
          type="button"
          onClick={onClose}
          className="px-8 py-3 bg-primary text-white rounded-xl font-black uppercase text-[0.65rem] tracking-widest shadow-lg shadow-blue-900/10 active:scale-95 transition-all"
        >
          Acknowledge
        </button>
      }
    >
      <div className="flex items-start gap-4">
        <div className={`w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 ${toneClasses}`}>
          <Icon size={22} />
        </div>
        <p className="text-sm font-semibold text-text leading-relaxed pt-1">{message}</p>
      </div>
    </ModalShell>
  );
}
