'use client';
import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
  fetchDepartments, fetchAllEmployees, fetchUsers,
  createHODWithUser, createDepartment, updateDepartment,
  assignHODToDepartment, resetUserPassword, promoteEmployee,
  hashPassword, generateTempPassword, sendWelcomeEmail,
  createEmployeeWithUser, updateUser,
} from '../../../lib/admin-api';
import { useAuth } from '../../../lib/authContext';

const BRAND = '#b828a0';

interface Dept {
  id: string;
  name: string;
  code: string;
  hod_id: string | null;
  description?: string;
  is_active: boolean;
}

interface StaffRow {
  id: string;
  employee_number: string;
  full_name: string;
  email: string;
  dept: string;
  position: string;
  employment_type: string;
  is_intern: boolean;
  is_active: boolean;
}

interface UserRow {
  id: string;
  username: string;
  name: string;
  email: string;
  role: string;
  dept: string | null;
  is_active: boolean;
}

function initials(name: string) {
  return name.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2);
}

export default function AdminEmployeesTab() {
  const { user } = useAuth();
  const [activeSection, setActiveSection] = useState<
    'overview' | 'add-employee' | 'add-hod' | 'add-dept' | 'promote-demote' | 'reset-password' | 'change-hod'
  >('overview');

  const [departments, setDepartments] = useState<Dept[]>([]);
  const [staff, setStaff] = useState<StaffRow[]>([]);
  const [users, setUsers] = useState<UserRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [toast, setToast] = useState('');
  const [toastType, setToastType] = useState<'success' | 'error'>('success');
  const [saving, setSaving] = useState(false);

  const [empForm, setEmpForm] = useState({ name: '', email: '', phone: '', dept: '', position: '', employmentType: 'Permanent', gender: 'Male', joinDate: '', salary: '' });
  const [hodForm, setHodForm] = useState({ name: '', email: '', phone: '', dept: '', username: '', password: '', confirmPassword: '' });
  const [deptForm, setDeptForm] = useState({ name: '', code: '', description: '' });
  const [promoteForm, setPromoteForm] = useState({ userId: '', newRole: 'employee', newDept: '' });
  const [resetForm, setResetForm] = useState({ userId: '', newPassword: '' });
  const [changeHodForm, setChangeHodForm] = useState({ deptId: '', newHodUserId: '' });
  const [successData, setSuccessData] = useState<{ username: string; password: string; empNumber: string; emailSent: boolean } | null>(null);

  useEffect(() => {
    Promise.all([fetchDepartments(), fetchAllEmployees(), fetchUsers()])
      .then(([depts, emps, us]) => {
        setDepartments(depts as Dept[]);
        setStaff(emps as StaffRow[]);
        setUsers(us as UserRow[]);
        const firstDept = (depts[0] as Dept)?.name || '';
        setEmpForm(f => ({ ...f, dept: firstDept }));
        setHodForm(f => ({ ...f, dept: firstDept }));
        setPromoteForm(f => ({ ...f, newDept: firstDept }));
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const showToast = (msg: string, type: 'success' | 'error' = 'success') => {
    setToast(msg);
    setToastType(type);
    setTimeout(() => setToast(''), 4000);
  };

  const reload = async () => {
    const [depts, emps, us] = await Promise.all([fetchDepartments(), fetchAllEmployees(), fetchUsers()]);
    setDepartments(depts as Dept[]);
    setStaff(emps as StaffRow[]);
    setUsers(us as UserRow[]);
  };

  const getDeptHOD = (dept: Dept) => {
    if (!dept.hod_id) return null;
    return users.find(u => u.id === dept.hod_id) || null;
  };

  const handleAddEmployee = async () => {
    if (!empForm.name || !empForm.email || !empForm.position || !empForm.joinDate) {
      showToast('Please fill all required fields', 'error');
      return;
    }
    setSaving(true);
    try {
      const result = await createEmployeeWithUser({
        fullName: empForm.name,
        email: empForm.email,
        phone: empForm.phone,
        gender: empForm.gender,
        dept: empForm.dept,
        position: empForm.position,
        joinDate: empForm.joinDate,
        salary: empForm.salary,
        employmentType: empForm.employmentType,
        createdByName: user?.name || 'Admin',
      });
      await reload();
      setSuccessData({ username: result.username, password: result.tempPassword, empNumber: result.empNumber, emailSent: true });
      setEmpForm({ name: '', email: '', phone: '', dept: departments[0]?.name || '', position: '', employmentType: 'Permanent', gender: 'Male', joinDate: '', salary: '' });
      setActiveSection('overview');
    } catch (err: unknown) {
      showToast((err instanceof Error ? err.message : 'Failed to add employee'), 'error');
    } finally {
      setSaving(false);
    }
  };

  const handleAddHOD = async () => {
    if (!hodForm.name || !hodForm.email || !hodForm.username || !hodForm.password || !hodForm.dept) {
      showToast('Please fill all required fields', 'error');
      return;
    }
    if (hodForm.password !== hodForm.confirmPassword) {
      showToast('Passwords do not match', 'error');
      return;
    }
    setSaving(true);
    try {
      const result = await createHODWithUser({
        fullName: hodForm.name,
        email: hodForm.email,
        phone: hodForm.phone,
        dept: hodForm.dept,
        username: hodForm.username,
        initialPassword: hodForm.password,
        assignedByName: user?.name || 'Admin',
      });
      await reload();
      setSuccessData({ username: result.username, password: hodForm.password, empNumber: result.empNumber, emailSent: true });
      setHodForm({ name: '', email: '', phone: '', dept: departments[0]?.name || '', username: '', password: '', confirmPassword: '' });
      setActiveSection('overview');
    } catch (err: unknown) {
      showToast((err instanceof Error ? err.message : 'Failed to create HOD'), 'error');
    } finally {
      setSaving(false);
    }
  };

  const handleAddDept = async () => {
    if (!deptForm.name || !deptForm.code) {
      showToast('Department name and code are required', 'error');
      return;
    }
    setSaving(true);
    try {
      await createDepartment({ name: deptForm.name, code: deptForm.code.toUpperCase(), description: deptForm.description });
      await reload();
      showToast(`Department "${deptForm.name}" created successfully`);
      setDeptForm({ name: '', code: '', description: '' });
      setActiveSection('overview');
    } catch (err: unknown) {
      showToast((err instanceof Error ? err.message : 'Failed to create department'), 'error');
    } finally {
      setSaving(false);
    }
  };

  const handleChangeHOD = async () => {
    if (!changeHodForm.deptId || !changeHodForm.newHodUserId) {
      showToast('Please select a department and HOD', 'error');
      return;
    }
    setSaving(true);
    try {
      const dept = departments.find(d => d.id === changeHodForm.deptId);
      await assignHODToDepartment(dept?.name || '', changeHodForm.newHodUserId, user?.name || 'Admin');
      await reload();
      showToast('HOD assigned successfully');
      setChangeHodForm({ deptId: '', newHodUserId: '' });
      setActiveSection('overview');
    } catch (err: unknown) {
      showToast((err instanceof Error ? err.message : 'Failed to assign HOD'), 'error');
    } finally {
      setSaving(false);
    }
  };

  const handlePromote = async () => {
    if (!promoteForm.userId || !promoteForm.newRole) return;
    setSaving(true);
    try {
      const target = users.find(u => u.id === promoteForm.userId);
      if (!target) throw new Error('User not found');
      await promoteEmployee({
        employeeId: target.id,
        employeeName: target.name,
        fromRole: target.role,
        toRole: promoteForm.newRole,
        fromDept: target.dept || undefined,
        toDept: promoteForm.newDept || undefined,
        authorizedByName: user?.name || 'Admin',
      });
      const updates: Record<string, unknown> = { role: promoteForm.newRole };
      if (promoteForm.newDept) updates.dept = promoteForm.newDept;
      await updateUser(promoteForm.userId, updates);
      await reload();
      showToast(`${target.name} role updated to ${promoteForm.newRole}`);
      setPromoteForm({ userId: '', newRole: 'employee', newDept: '' });
      setActiveSection('overview');
    } catch (err: unknown) {
      showToast((err instanceof Error ? err.message : 'Failed to update role'), 'error');
    } finally {
      setSaving(false);
    }
  };

  const handleResetPassword = async () => {
    if (!resetForm.userId || resetForm.newPassword.length < 6) return;
    setSaving(true);
    try {
      const target = users.find(u => u.id === resetForm.userId);
      if (!target) throw new Error('User not found');
      const newHash = await hashPassword(resetForm.newPassword);
      await resetUserPassword(resetForm.userId, newHash, user?.name || 'Admin');
      await sendWelcomeEmail({ to: target.email, name: target.name, username: target.username, password: resetForm.newPassword, role: target.role, dept: target.dept || undefined });
      await reload();
      showToast(`Password reset for ${target.name}. They will be prompted to change it on next login.`);
      setResetForm({ userId: '', newPassword: '' });
      setActiveSection('overview');
    } catch (err: unknown) {
      showToast((err instanceof Error ? err.message : 'Failed to reset password'), 'error');
    } finally {
      setSaving(false);
    }
  };

  const hodUsers = users.filter(u => u.role === 'hod' && u.is_active);
  const roleOptions = [
    { key: 'employee', label: 'Employee' },
    { key: 'intern', label: 'Intern' },
    { key: 'hod', label: 'HOD' },
    { key: 'hr', label: 'HR Manager' },
    { key: 'finance', label: 'Finance Officer' },
    { key: 'hos', label: 'HOS' },
    { key: 'admin', label: 'Admin' },
  ];

  const sections = [
    { id: 'overview', label: 'Overview', icon: 'ri-dashboard-line' },
    { id: 'add-employee', label: 'Add Employee / Intern', icon: 'ri-user-add-line' },
    { id: 'add-hod', label: 'Add HOD Account', icon: 'ri-user-star-line' },
    { id: 'add-dept', label: 'Add Department', icon: 'ri-building-line' },
    { id: 'change-hod', label: 'Assign HOD to Dept', icon: 'ri-swap-line' },
    { id: 'promote-demote', label: 'Promote / Demote', icon: 'ri-arrow-up-down-line' },
    { id: 'reset-password', label: 'Reset Password', icon: 'ri-lock-password-line' },
  ];

  return (
    <div className="space-y-5">
      {toast && (
        <div className={`fixed top-20 right-6 z-[100] px-5 py-3 rounded-xl shadow-lg text-sm font-medium flex items-center gap-2 text-white ${toastType === 'success' ? 'bg-green-600' : 'bg-red-600'}`}>
          <i className={`text-lg ${toastType === 'success' ? 'ri-checkbox-circle-line' : 'ri-error-warning-line'}`}></i>
          {toast}
        </div>
      )}

      {successData && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-2xl p-8 w-[480px] shadow-2xl text-center">
            <div className="w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4" style={{ background: '#fdf4fc' }}>
              <i className="ri-checkbox-circle-fill text-4xl" style={{ color: BRAND }}></i>
            </div>
            <h3 className="text-xl font-bold text-gray-800 mb-2">Account Created!</h3>
            <p className="text-sm text-gray-500 mb-5">Credentials have been generated and a welcome email dispatched.</p>
            <div className="rounded-xl p-4 mb-4 border text-left" style={{ background: '#fdf4fc', borderColor: '#f0c0ec' }}>
              <p className="text-xs font-semibold uppercase tracking-wide mb-3" style={{ color: BRAND }}>Login Credentials</p>
              <div className="space-y-2 text-sm">
                <div className="flex justify-between py-1.5 border-b border-pink-100">
                  <span className="text-gray-500">Employee ID / Username</span>
                  <span className="font-mono font-bold">{successData.username}</span>
                </div>
                <div className="flex justify-between py-1.5">
                  <span className="text-gray-500">Initial Password</span>
                  <span className="font-mono font-bold">{successData.password}</span>
                </div>
              </div>
            </div>
            <div className={`rounded-xl p-3 mb-4 flex items-start gap-2 text-left ${successData.emailSent ? 'bg-green-50 border border-green-200' : 'bg-amber-50 border border-amber-200'}`}>
              <i className={`mt-0.5 ${successData.emailSent ? 'ri-mail-check-line text-green-600' : 'ri-mail-line text-amber-600'}`}></i>
              <p className={`text-xs ${successData.emailSent ? 'text-green-800' : 'text-amber-800'}`}>
                {successData.emailSent ? 'Welcome email with credentials sent to the user.' : 'Please share credentials manually with the user.'}
              </p>
            </div>
            <button onClick={() => setSuccessData(null)}
              className="w-full py-3 rounded-xl text-white font-semibold cursor-pointer whitespace-nowrap"
              style={{ background: BRAND }}>
              Done
            </button>
          </div>
        </div>
      )}

      <div className="flex gap-2 flex-wrap">
        {sections.map(s => (
          <button key={s.id} onClick={() => setActiveSection(s.id as typeof activeSection)}
            className="flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-semibold cursor-pointer whitespace-nowrap transition-all"
            style={activeSection === s.id ? { background: BRAND, color: '#fff' } : { background: '#f3f4f6', color: '#4b5563' }}>
            <i className={s.icon}></i>
            {s.label}
          </button>
        ))}
      </div>

      {loading && (
        <div className="flex justify-center py-12">
          <div className="w-8 h-8 border-2 border-pink-300 border-t-pink-600 rounded-full animate-spin"></div>
        </div>
      )}

      {!loading && activeSection === 'overview' && (
        <div className="space-y-5">
          <div className="grid grid-cols-4 gap-4">
            {[
              { label: 'Total Staff', value: staff.length, icon: 'ri-team-line', color: BRAND },
              { label: 'Departments', value: departments.length, icon: 'ri-building-line', color: '#2563eb' },
              { label: 'Active HODs', value: departments.filter(d => d.hod_id).length, icon: 'ri-user-star-line', color: '#059669' },
              { label: 'System Users', value: users.filter(u => u.is_active).length, icon: 'ri-shield-user-line', color: '#f59e0b' },
            ].map((s, i) => (
              <motion.div key={s.label} initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: i * 0.08 }}
                className="bg-white rounded-xl p-4 border border-gray-100 shadow-sm">
                <div className="w-9 h-9 rounded-xl flex items-center justify-center mb-3" style={{ background: s.color + '18' }}>
                  <i className={`${s.icon} text-lg`} style={{ color: s.color }}></i>
                </div>
                <p className="text-2xl font-bold text-gray-800">{s.value}</p>
                <p className="text-xs text-gray-500">{s.label}</p>
              </motion.div>
            ))}
          </div>

          <div className="bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden">
            <div className="px-5 py-3 border-b border-gray-100 flex items-center justify-between">
              <h3 className="font-semibold text-gray-700">Departments & HODs</h3>
              <button onClick={() => setActiveSection('add-dept')}
                className="text-xs px-3 py-1.5 rounded-lg text-white cursor-pointer whitespace-nowrap"
                style={{ background: BRAND }}>
                + Add Department
              </button>
            </div>
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="bg-gray-50 border-b border-gray-100">
                    {['Department', 'Code', 'Current HOD', 'HOD Email', 'Actions'].map(h => (
                      <th key={h} className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {departments.map(d => {
                    const hodUser = getDeptHOD(d);
                    return (
                      <tr key={d.id} className="border-b border-gray-50 hover:bg-gray-50/50">
                        <td className="px-4 py-3 font-medium text-gray-800">{d.name}</td>
                        <td className="px-4 py-3"><span className="text-xs font-mono bg-gray-100 px-2 py-0.5 rounded">{d.code}</span></td>
                        <td className="px-4 py-3 text-gray-600">{hodUser?.name || <span className="text-amber-500 text-xs">Not assigned</span>}</td>
                        <td className="px-4 py-3 text-xs text-gray-500">{hodUser?.email || '—'}</td>
                        <td className="px-4 py-3">
                          <button onClick={() => { setChangeHodForm({ deptId: d.id, newHodUserId: '' }); setActiveSection('change-hod'); }}
                            className="text-xs px-3 py-1.5 rounded-lg border cursor-pointer whitespace-nowrap"
                            style={{ borderColor: BRAND, color: BRAND }}>
                            Change HOD
                          </button>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>

          <div className="bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden">
            <div className="px-5 py-3 border-b border-gray-100 flex items-center justify-between">
              <h3 className="font-semibold text-gray-700">All Staff ({staff.length})</h3>
              <button onClick={() => setActiveSection('add-employee')}
                className="text-xs px-3 py-1.5 rounded-lg text-white cursor-pointer whitespace-nowrap"
                style={{ background: BRAND }}>
                + Add Employee
              </button>
            </div>
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="bg-gray-50 border-b border-gray-100">
                    {['Name', 'Dept', 'Position', 'Type', 'Status'].map(h => (
                      <th key={h} className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {staff.map(s => (
                    <tr key={s.id} className="border-b border-gray-50 hover:bg-gray-50/50">
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-2">
                          <div className="w-7 h-7 rounded-full flex items-center justify-center text-white text-xs font-bold flex-shrink-0" style={{ background: BRAND }}>
                            {initials(s.full_name)}
                          </div>
                          <div>
                            <p className="font-medium text-gray-800 text-sm">{s.full_name}</p>
                            <p className="text-xs text-gray-400">{s.email}</p>
                          </div>
                        </div>
                      </td>
                      <td className="px-4 py-3 text-gray-600 text-sm">{s.dept}</td>
                      <td className="px-4 py-3 text-gray-600 text-sm">{s.position}</td>
                      <td className="px-4 py-3">
                        <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${s.is_intern ? 'bg-orange-100 text-orange-700' : s.employment_type === 'Contract' ? 'bg-blue-100 text-blue-700' : 'bg-green-100 text-green-700'}`}>
                          {s.is_intern ? 'Intern' : s.employment_type}
                        </span>
                      </td>
                      <td className="px-4 py-3">
                        <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${s.is_active ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'}`}>
                          {s.is_active ? 'Active' : 'Inactive'}
                        </span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

      {!loading && activeSection === 'add-employee' && (
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-6">
          <div className="mb-5">
            <h3 className="font-bold text-gray-800">Add New Employee or Intern</h3>
            <p className="text-xs text-gray-400 mt-0.5">System will auto-generate employee ID, password, and send a welcome email</p>
          </div>
          <div className="grid grid-cols-2 gap-4">
            {[
              { label: 'Full Name *', key: 'name', placeholder: 'e.g. Jane Wanjiru' },
              { label: 'Email Address *', key: 'email', type: 'email', placeholder: 'jane@uwezo.go.ke' },
              { label: 'Phone', key: 'phone', placeholder: '+254 7XX XXX XXX' },
              { label: 'Date Joined *', key: 'joinDate', type: 'date', placeholder: '' },
              { label: 'Job Title / Position *', key: 'position', placeholder: 'e.g. M&E Officer' },
              { label: 'Salary (KES)', key: 'salary', placeholder: 'e.g. 145000' },
            ].map(f => (
              <div key={f.key}>
                <label className="block text-xs font-semibold text-gray-600 mb-1">{f.label}</label>
                <input
                  type={f.type || 'text'}
                  placeholder={f.placeholder}
                  value={(empForm as Record<string, string>)[f.key]}
                  onChange={e => setEmpForm(prev => ({ ...prev, [f.key]: e.target.value }))}
                  className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none focus:border-pink-400" />
              </div>
            ))}
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">Department</label>
              <select value={empForm.dept} onChange={e => setEmpForm(f => ({ ...f, dept: e.target.value }))}
                className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none pr-8 cursor-pointer">
                {departments.map(d => <option key={d.id} value={d.name}>{d.name}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">Employment Type</label>
              <select value={empForm.employmentType} onChange={e => setEmpForm(f => ({ ...f, employmentType: e.target.value }))}
                className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none pr-8 cursor-pointer">
                {['Permanent', 'Contract', 'Intern', 'Casual'].map(t => <option key={t}>{t}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">Gender</label>
              <div className="flex gap-2">
                {['Male', 'Female'].map(g => (
                  <button key={g} onClick={() => setEmpForm(f => ({ ...f, gender: g }))}
                    className="flex-1 py-2.5 rounded-xl text-sm font-semibold cursor-pointer border transition-all"
                    style={empForm.gender === g ? { background: BRAND, color: '#fff', borderColor: BRAND } : { background: '#f9f9f9', color: '#4b5563', borderColor: '#e5e7eb' }}>
                    {g}
                  </button>
                ))}
              </div>
            </div>
          </div>
          <div className="mt-4 bg-amber-50 border border-amber-200 rounded-xl px-4 py-3 flex items-start gap-2">
            <i className="ri-information-line text-amber-600 mt-0.5"></i>
            <p className="text-xs text-amber-800">A unique employee ID and temporary password are auto-generated. A welcome email is sent to the employee with their login credentials. They must change their password on first login.</p>
          </div>
          <div className="flex gap-3 mt-5">
            <button onClick={() => setActiveSection('overview')} className="px-5 py-2.5 border border-gray-200 rounded-xl text-sm text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
            <button onClick={handleAddEmployee} disabled={saving || !empForm.name || !empForm.email || !empForm.position || !empForm.joinDate}
              className="flex items-center gap-2 px-5 py-2.5 text-white rounded-xl text-sm font-semibold cursor-pointer disabled:opacity-50 whitespace-nowrap"
              style={{ background: BRAND }}>
              {saving ? <><div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"></div> Saving...</> : 'Add Employee & Send Credentials'}
            </button>
          </div>
        </div>
      )}

      {!loading && activeSection === 'add-hod' && (
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-6">
          <div className="mb-5">
            <h3 className="font-bold text-gray-800">Create HOD Account</h3>
            <p className="text-xs text-gray-400 mt-0.5">Assign a Head of Department to a specific department with their own login</p>
          </div>
          <div className="grid grid-cols-2 gap-4">
            {[
              { label: 'Full Name *', key: 'name', placeholder: 'e.g. Evans Oyaro' },
              { label: 'Email Address *', key: 'email', type: 'email', placeholder: 'hod@uwezo.go.ke' },
              { label: 'Username *', key: 'username', placeholder: 'e.g. evans.oyaro' },
              { label: 'Phone (optional)', key: 'phone', placeholder: '+254 7XX XXX XXX' },
              { label: 'Initial Password *', key: 'password', type: 'password', placeholder: 'Set a strong initial password' },
              { label: 'Confirm Password *', key: 'confirmPassword', type: 'password', placeholder: 'Re-enter password' },
            ].map(f => (
              <div key={f.key}>
                <label className="block text-xs font-semibold text-gray-600 mb-1">{f.label}</label>
                <input
                  type={f.type || 'text'}
                  placeholder={f.placeholder}
                  value={(hodForm as Record<string, string>)[f.key]}
                  onChange={e => setHodForm(prev => ({ ...prev, [f.key]: e.target.value }))}
                  className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none focus:border-pink-400" />
              </div>
            ))}
            <div className="col-span-2">
              <label className="block text-xs font-semibold text-gray-600 mb-1">Assign to Department *</label>
              <select value={hodForm.dept} onChange={e => setHodForm(f => ({ ...f, dept: e.target.value }))}
                className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none pr-8 cursor-pointer">
                <option value="">Select department...</option>
                {departments.map(d => {
                  const currentHOD = getDeptHOD(d);
                  return <option key={d.id} value={d.name}>{d.name} {currentHOD ? `— Current HOD: ${currentHOD.name}` : '— (No HOD assigned)'}</option>;
                })}
              </select>
            </div>
          </div>
          <div className="mt-4 bg-blue-50 border border-blue-200 rounded-xl px-4 py-3 flex items-start gap-2">
            <i className="ri-information-line text-blue-600 mt-0.5"></i>
            <p className="text-xs text-blue-800">The HOD will log in using their username and initial password. They will be required to change it on first login. Their account will be assigned to the selected department immediately. A welcome email with credentials will be sent.</p>
          </div>
          <div className="flex gap-3 mt-5">
            <button onClick={() => setActiveSection('overview')} className="px-5 py-2.5 border border-gray-200 rounded-xl text-sm text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
            <button onClick={handleAddHOD} disabled={saving || !hodForm.name || !hodForm.email || !hodForm.username || !hodForm.password || !hodForm.dept}
              className="flex items-center gap-2 px-5 py-2.5 text-white rounded-xl text-sm font-semibold cursor-pointer disabled:opacity-50 whitespace-nowrap"
              style={{ background: BRAND }}>
              {saving ? <><div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"></div> Creating...</> : 'Create HOD Account'}
            </button>
          </div>
        </div>
      )}

      {!loading && activeSection === 'add-dept' && (
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-6">
          <div className="mb-5">
            <h3 className="font-bold text-gray-800">Create New Department</h3>
            <p className="text-xs text-gray-400 mt-0.5">Add a department to the organizational structure</p>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">Department Name *</label>
              <input value={deptForm.name} onChange={e => setDeptForm(f => ({ ...f, name: e.target.value }))}
                placeholder="e.g. Legal Affairs"
                className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none focus:border-pink-400" />
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">Department Code * (3-5 chars)</label>
              <input value={deptForm.code} onChange={e => setDeptForm(f => ({ ...f, code: e.target.value.toUpperCase() }))}
                placeholder="e.g. LEG"
                className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none focus:border-pink-400 uppercase" />
            </div>
            <div className="col-span-2">
              <label className="block text-xs font-semibold text-gray-600 mb-1">Description (optional)</label>
              <textarea value={deptForm.description} onChange={e => setDeptForm(f => ({ ...f, description: e.target.value }))}
                rows={2} maxLength={500}
                placeholder="Brief description of the department's mandate..."
                className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none focus:border-pink-400 resize-none" />
            </div>
          </div>
          <div className="mt-4 bg-green-50 border border-green-200 rounded-xl px-4 py-3 flex items-start gap-2">
            <i className="ri-information-line text-green-600 mt-0.5"></i>
            <p className="text-xs text-green-800">After creating the department, you can assign a HOD to it from the <strong>Assign HOD to Dept</strong> section.</p>
          </div>
          <div className="flex gap-3 mt-5">
            <button onClick={() => setActiveSection('overview')} className="px-5 py-2.5 border border-gray-200 rounded-xl text-sm text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
            <button onClick={handleAddDept} disabled={saving || !deptForm.name || !deptForm.code}
              className="flex items-center gap-2 px-5 py-2.5 text-white rounded-xl text-sm font-semibold cursor-pointer disabled:opacity-50 whitespace-nowrap"
              style={{ background: BRAND }}>
              {saving ? <><div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"></div> Creating...</> : 'Create Department'}
            </button>
          </div>
        </div>
      )}

      {!loading && activeSection === 'change-hod' && (
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-6">
          <div className="mb-5">
            <h3 className="font-bold text-gray-800">Assign HOD to Department</h3>
            <p className="text-xs text-gray-400 mt-0.5">Replace or assign a Head of Department. Previous assignment will be closed.</p>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">Select Department *</label>
              <select value={changeHodForm.deptId} onChange={e => setChangeHodForm(f => ({ ...f, deptId: e.target.value }))}
                className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none pr-8 cursor-pointer">
                <option value="">Select department...</option>
                {departments.map(d => {
                  const currentHOD = getDeptHOD(d);
                  return <option key={d.id} value={d.id}>{d.name} {currentHOD ? `(Current: ${currentHOD.name})` : '(No HOD)'}</option>;
                })}
              </select>
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">Select New HOD *</label>
              <select value={changeHodForm.newHodUserId} onChange={e => setChangeHodForm(f => ({ ...f, newHodUserId: e.target.value }))}
                className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none pr-8 cursor-pointer">
                <option value="">Select user...</option>
                {hodUsers.map(u => <option key={u.id} value={u.id}>{u.name} — {u.dept || 'Unassigned'}</option>)}
                {users.filter(u => ['employee', 'hr', 'finance', 'admin'].includes(u.role) && u.is_active).map(u => (
                  <option key={u.id} value={u.id}>{u.name} ({u.role})</option>
                ))}
              </select>
            </div>
          </div>
          <div className="flex gap-3 mt-5">
            <button onClick={() => setActiveSection('overview')} className="px-5 py-2.5 border border-gray-200 rounded-xl text-sm text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
            <button onClick={handleChangeHOD} disabled={saving || !changeHodForm.deptId || !changeHodForm.newHodUserId}
              className="flex items-center gap-2 px-5 py-2.5 text-white rounded-xl text-sm font-semibold cursor-pointer disabled:opacity-50 whitespace-nowrap"
              style={{ background: BRAND }}>
              {saving ? <><div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"></div> Assigning...</> : 'Assign HOD'}
            </button>
          </div>
        </div>
      )}

      {!loading && activeSection === 'promote-demote' && (
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-6">
          <div className="mb-5">
            <h3 className="font-bold text-gray-800">Promote / Demote Employee</h3>
            <p className="text-xs text-gray-400 mt-0.5">Change a staff member's role or department. All changes are logged for audit.</p>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div className="col-span-2">
              <label className="block text-xs font-semibold text-gray-600 mb-1">Select Staff Member *</label>
              <select value={promoteForm.userId} onChange={e => setPromoteForm(f => ({ ...f, userId: e.target.value }))}
                className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none pr-8 cursor-pointer">
                <option value="">Select staff member...</option>
                {users.filter(u => u.is_active).map(u => <option key={u.id} value={u.id}>{u.name} — {u.role} ({u.dept || 'No dept'})</option>)}
              </select>
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">New System Role *</label>
              <select value={promoteForm.newRole} onChange={e => setPromoteForm(f => ({ ...f, newRole: e.target.value }))}
                className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none pr-8 cursor-pointer">
                {roleOptions.map(r => <option key={r.key} value={r.key}>{r.label}</option>)}
              </select>
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">New Department (optional)</label>
              <select value={promoteForm.newDept} onChange={e => setPromoteForm(f => ({ ...f, newDept: e.target.value }))}
                className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none pr-8 cursor-pointer">
                <option value="">Keep current department</option>
                {departments.map(d => <option key={d.id} value={d.name}>{d.name}</option>)}
              </select>
            </div>
          </div>
          {promoteForm.userId && (() => {
            const target = users.find(u => u.id === promoteForm.userId);
            if (!target) return null;
            return (
              <div className="mt-4 bg-amber-50 border border-amber-200 rounded-xl px-4 py-3">
                <p className="text-xs font-semibold text-amber-700">Change Preview: {target.name}</p>
                <p className="text-xs text-amber-600 mt-1">
                  Role: <strong>{target.role}</strong> → <strong>{promoteForm.newRole}</strong>
                  {promoteForm.newDept && <span> | Dept: <strong>{target.dept || 'none'}</strong> → <strong>{promoteForm.newDept}</strong></span>}
                </p>
              </div>
            );
          })()}
          <div className="flex gap-3 mt-5">
            <button onClick={() => setActiveSection('overview')} className="px-5 py-2.5 border border-gray-200 rounded-xl text-sm text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
            <button onClick={handlePromote} disabled={saving || !promoteForm.userId}
              className="flex items-center gap-2 px-5 py-2.5 text-white rounded-xl text-sm font-semibold cursor-pointer disabled:opacity-50 whitespace-nowrap"
              style={{ background: BRAND }}>
              {saving ? <><div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"></div> Applying...</> : 'Apply Role Change'}
            </button>
          </div>
        </div>
      )}

      {!loading && activeSection === 'reset-password' && (
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-6">
          <div className="mb-5">
            <h3 className="font-bold text-gray-800">Reset Employee Password</h3>
            <p className="text-xs text-gray-400 mt-0.5">Set a new password. Employee will be required to change it on next login and will receive an email.</p>
          </div>
          <div className="space-y-4 max-w-lg">
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">Select Staff Member *</label>
              <select value={resetForm.userId} onChange={e => setResetForm(f => ({ ...f, userId: e.target.value }))}
                className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none pr-8 cursor-pointer">
                <option value="">Select staff member...</option>
                {users.filter(u => u.is_active).map(u => <option key={u.id} value={u.id}>{u.name} ({u.email})</option>)}
              </select>
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-600 mb-1">New Password *</label>
              <input type="password" value={resetForm.newPassword} onChange={e => setResetForm(f => ({ ...f, newPassword: e.target.value }))}
                placeholder="Enter new password (min. 6 characters)"
                className="w-full border border-gray-200 rounded-xl px-3 py-2.5 text-sm outline-none focus:border-pink-400" />
            </div>
          </div>
          <div className="mt-4 bg-amber-50 border border-amber-200 rounded-xl px-4 py-3 flex items-start gap-2">
            <i className="ri-alert-line text-amber-600 mt-0.5"></i>
            <p className="text-xs text-amber-800">The reset is logged in the audit trail. The employee will receive an email notification and must change their password on next login.</p>
          </div>
          <div className="flex gap-3 mt-5">
            <button onClick={() => setActiveSection('overview')} className="px-5 py-2.5 border border-gray-200 rounded-xl text-sm text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
            <button onClick={handleResetPassword} disabled={saving || !resetForm.userId || resetForm.newPassword.length < 6}
              className="flex items-center gap-2 px-5 py-2.5 text-white rounded-xl text-sm font-semibold cursor-pointer disabled:opacity-50 whitespace-nowrap"
              style={{ background: BRAND }}>
              {saving ? <><div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"></div> Resetting...</> : 'Reset Password & Notify Employee'}
            </button>
          </div>
        </div>
      )}
    </div>
  );
}