'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;
  status?: string;
}

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 [resending, setResending] = useState<string | null>(null);
  const [deleting, setDeleting] = useState<string | null>(null);

  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;
  };

  // Delete Employee Function
  const handleDeleteEmployee = async (employeeId: string, employeeName: string, employeeEmail: string) => {
    if (confirm(`⚠️ Are you sure you want to delete ${employeeName}?\n\nThis will permanently delete:\n• User account\n• Leave requests\n• Training records\n• Appraisals\n• Work plans\n• KPIs\n• All related data\n\n⚠️ This action cannot be undone!`)) {
      setDeleting(employeeId);
      try {
        const response = await fetch(`/api/admin/employees/${employeeId}`, {
          method: 'DELETE',
        });
        
        if (response.ok) {
          showToast(`✅ ${employeeName} deleted successfully`, 'success');
          await reload();
        } else {
          const error = await response.json();
          showToast(error.error || 'Failed to delete employee', 'error');
        }
      } catch (error) {
        showToast('Network error. Please try again.', 'error');
      } finally {
        setDeleting(null);
      }
    }
  };

  // Resend activation email function
  const handleResendActivation = async (email: string, userId: string) => {
    setResending(userId);
    try {
      const response = await fetch('/api/auth/resend-activation', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      
      const data = await response.json();
      
      if (response.ok) {
        showToast(`✅ Activation link sent to ${email}`, 'success');
      } else {
        showToast(data.error || 'Failed to resend activation', 'error');
      }
    } catch (error) {
      showToast('Network error. Please try again.', 'error');
    } finally {
      setResending(null);
    }
  };

  const handleAddEmployee = async () => {
    if (!empForm.name || !empForm.email || !empForm.position || !empForm.joinDate) {
      showToast('Please fill all required fields', 'error');
      return;
    }
    setSaving(true);
    try {
      // First create employee record
      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',
      });
      
      // Then create user with activation (using the admin API that sends activation email)
      const userResponse = await fetch('/api/admin/users', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: empForm.email,
          name: empForm.name,
          role: empForm.employmentType === 'Intern' ? 'INTERN' : 'EMPLOYEE',
          dept: empForm.dept,
          employeeId: result.empNumber,
          username: empForm.email.split('@')[0],
          phone: empForm.phone,
          position: empForm.position,
          gender: empForm.gender,
        }),
      });
      
      const userData = await userResponse.json();
      
      await reload();
      setSuccessData({ 
        username: result.username || empForm.email.split('@')[0], 
        password: result.tempPassword || 'Will be set during activation', 
        empNumber: result.empNumber, 
        emailSent: userData.emailSent || false 
      });
      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 {
      // Create HOD with activation (using admin API)
      const userResponse = await fetch('/api/admin/users', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          email: hodForm.email,
          name: hodForm.name,
          role: 'HOD',
          dept: hodForm.dept,
          username: hodForm.username,
          phone: hodForm.phone,
        }),
      });
      
      const userData = await userResponse.json();
      
      // Also create HOD record in the legacy system
      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: hodForm.username, 
        password: hodForm.password, 
        empNumber: userData.user?.employeeId || 'N/A', 
        emailSent: userData.emailSent || false 
      });
      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, updated_at: new Date().toISOString() };
      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 ? 'Activation email sent to the user. They will need to set their password via the activation link.' : 'Please share the activation link 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">
          {/* Stats Cards */}
          <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>

          {/* Departments Table */}
          <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>

          {/* Staff Table with Delete and Activation Buttons */}
          <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', '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>
                  {staff.map(s => {
                    const userAccount = users.find(u => u.email === s.email);
                    const needsActivation = userAccount?.status === 'PENDING_ACTIVATION';
                    return (
                      <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 ? (needsActivation ? 'bg-yellow-100 text-yellow-700' : 'bg-green-100 text-green-700') : 'bg-gray-100 text-gray-500'}`}>
                            {s.is_active ? (needsActivation ? 'Pending Activation' : 'Active') : 'Inactive'}
                          </span>
                        </td>
                        <td className="px-4 py-3">
                          <div className="flex items-center gap-2">
                            {needsActivation && userAccount && (
                              <button
                                onClick={() => handleResendActivation(s.email, userAccount.id)}
                                disabled={resending === userAccount.id}
                                className="text-xs px-2 py-1 rounded-lg border cursor-pointer whitespace-nowrap flex items-center gap-1"
                                style={{ borderColor: BRAND, color: BRAND }}
                              >
                                {resending === userAccount.id ? (
                                  <div className="w-3 h-3 border-2 border-purple-600 border-t-transparent rounded-full animate-spin"></div>
                                ) : (
                                  <i className="ri-mail-send-line text-xs"></i>
                                )}
                                Resend
                              </button>
                            )}
                            <button
                              onClick={() => handleDeleteEmployee(s.id, s.full_name, s.email)}
                              disabled={deleting === s.id}
                              className="text-red-600 hover:text-red-800 text-xs px-2 py-1 rounded-lg border border-red-200 hover:border-red-400 flex items-center gap-1 transition"
                            >
                              {deleting === s.id ? (
                                <div className="w-3 h-3 border-2 border-red-600 border-t-transparent rounded-full animate-spin"></div>
                              ) : (
                                <i className="ri-delete-bin-line text-xs"></i>
                              )}
                              Delete
                            </button>
                          </div>
                        </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">An activation email will be sent to the employee's email address. They will set their own password.</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">An activation email will be sent to the employee. They will click the link to set their own password.</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> Creating...</> : 'Add Employee & Send Activation'}
            </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">An activation email will be sent to the HOD's email address.</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">An activation email will be sent to the HOD. They will click the link to set their own password.</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 & Send Activation'}
            </button>
          </div>
        </div>
      )}

      {/* Keep all other sections (add-dept, change-hod, promote-demote, reset-password) as they were - unchanged */}
    </div>
  );
}