'use client';
import { useState, useEffect } from 'react';
import HODLayout from '../../../components/HODLayout';
import { useAuth } from '../../../lib/authContext';
import { useLeaveStore } from '../../../lib/leaveStore';
import { LEAVE_POLICIES } from '../../hr/leave/leaveData';

const BRAND = '#B22698';

interface Employee {
  id: string;
  employeeNumber: string;
  fullName: string;
  email: string;
  dept: string;
  position: string;
  joinDate: string;
  gender: string;
  grade: string;
  isActive: boolean;
  phone?: string;
}

export default function HODDepartmentPage() {
  const { user } = useAuth();
  const { requests } = useLeaveStore();
  const [employees, setEmployees] = useState<Employee[]>([]);
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState({
    total: 0,
    active: 0,
    onLeave: 0,
    pendingRequests: 0,
  });

  useEffect(() => {
    const fetchDepartmentEmployees = async () => {
      if (!user?.dept) return;
      
      try {
        setLoading(true);
        const response = await fetch(`/api/admin/employees`);
        if (response.ok) {
          const data = await response.json();
          const deptEmployees = data.filter((emp: Employee) => emp.dept === user.dept);
          setEmployees(deptEmployees);
          
          const today = new Date().toISOString().split('T')[0];
          const activeEmployees = deptEmployees.filter((emp: Employee) => emp.isActive !== false);
          const onLeaveCount = deptEmployees.filter((emp: Employee) => {
            const empRequests = requests.filter(r => 
              r.employee === emp.fullName && 
              r.status === 'Approved' && 
              r.startDate <= today && 
              r.endDate >= today
            );
            return empRequests.length > 0;
          }).length;
          
          const pendingCount = requests.filter(r => 
            r.dept === user.dept && 
            r.status === 'Pending'
          ).length;
          
          setStats({
            total: deptEmployees.length,
            active: activeEmployees.length,
            onLeave: onLeaveCount,
            pendingRequests: pendingCount,
          });
        }
      } catch (error) {
        console.error('Error fetching employees:', error);
      } finally {
        setLoading(false);
      }
    };
    
    fetchDepartmentEmployees();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [user?.dept]);

  if (!user) return null;

  const dept = user.dept || 'ICT';
  const today = new Date().toISOString().split('T')[0];

  if (loading) {
    return (
      <HODLayout title="My Department">
        <div className="flex items-center justify-center h-64">
          <div className="text-center">
            <div className="w-12 h-12 border-4 border-purple-600 border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
            <p className="text-gray-500">Loading department employees...</p>
          </div>
        </div>
      </HODLayout>
    );
  }

  return (
    <HODLayout title="My Department">
      <div className="space-y-5">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-lg font-bold text-gray-800">{dept} Department</h2>
            <p className="text-sm text-gray-500">{stats.total} staff members under your supervision</p>
          </div>
        </div>

        {/* Stats Cards */}
        <div className="grid grid-cols-4 gap-4 mb-2">
          <div className="bg-white rounded-xl border border-gray-100 p-4 text-center">
            <p className="text-2xl font-bold text-gray-800">{stats.total}</p>
            <p className="text-xs text-gray-400 mt-1">Total Staff</p>
          </div>
          <div className="bg-white rounded-xl border border-gray-100 p-4 text-center">
            <p className="text-2xl font-bold text-blue-600">{stats.active}</p>
            <p className="text-xs text-gray-400 mt-1">Active Staff</p>
          </div>
          <div className="bg-white rounded-xl border border-gray-100 p-4 text-center">
            <p className="text-2xl font-bold text-green-600">{stats.onLeave}</p>
            <p className="text-xs text-gray-400 mt-1">Currently On Leave</p>
          </div>
          <div className="bg-white rounded-xl border border-gray-100 p-4 text-center">
            <p className="text-2xl font-bold text-amber-600">{stats.pendingRequests}</p>
            <p className="text-xs text-gray-400 mt-1">Pending Requests</p>
          </div>
        </div>

        {/* Employees List */}
        <div className="grid grid-cols-1 gap-4">
          {employees.length === 0 ? (
            <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-12 text-center">
              <i className="ri-team-line text-4xl text-gray-300 mb-2 block"></i>
              <p className="text-gray-400">No employees found in {dept} department</p>
            </div>
          ) : (
            employees.map((emp) => {
              const onLeave = requests.find(r =>
                r.employee === emp.fullName && 
                r.status === 'Approved' && 
                r.startDate <= today && 
                r.endDate >= today
              );
              const empRequests = requests.filter(r => r.employee === emp.fullName);
              const pendingCount = empRequests.filter(r => r.status === 'Pending').length;
              const approvedCount = empRequests.filter(r => r.status === 'Approved' || r.status === 'HOS Approved').length;

              return (
                <div key={emp.id} className="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 hover:shadow-md transition">
                  <div className="flex items-start gap-4 mb-4">
                    <div className="w-12 h-12 rounded-xl flex items-center justify-center text-white font-bold flex-shrink-0" style={{ background: BRAND }}>
                      {emp.fullName?.split(' ').map(n => n[0]).join('').slice(0, 2) || 'EM'}
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 flex-wrap">
                        <h4 className="font-bold text-gray-800">{emp.fullName}</h4>
                        <span className="text-xs px-2 py-0.5 rounded-full bg-blue-100 text-blue-700 font-semibold">{emp.grade || 'Grade 4'}</span>
                        {!emp.isActive && (
                          <span className="text-xs px-2 py-0.5 rounded-full bg-red-100 text-red-700 font-semibold">Inactive</span>
                        )}
                        {onLeave && (
                          <span className="text-xs px-2 py-0.5 rounded-full bg-green-100 text-green-700 font-semibold">On Leave</span>
                        )}
                        {pendingCount > 0 && (
                          <span className="text-xs px-2 py-0.5 rounded-full bg-amber-100 text-amber-700 font-semibold">{pendingCount} Pending</span>
                        )}
                      </div>
                      <p className="text-sm text-gray-500">{emp.position}</p>
                      <div className="flex items-center gap-4 mt-1 text-xs text-gray-400 flex-wrap">
                        <span><i className="ri-mail-line mr-1"></i>{emp.email}</span>
                        <span><i className="ri-calendar-line mr-1"></i>Joined {emp.joinDate ? new Date(emp.joinDate).toLocaleDateString() : 'N/A'}</span>
                        <span><i className="ri-user-line mr-1"></i>{emp.gender || 'Not specified'}</span>
                        {emp.phone && <span><i className="ri-phone-line mr-1"></i>{emp.phone}</span>}
                      </div>
                      {onLeave && (
                        <p className="text-xs text-green-600 mt-1">
                          <i className="ri-calendar-line mr-1"></i>
                          {LEAVE_POLICIES.find(p => p.type === onLeave.type)?.label} until {onLeave.endDate}
                        </p>
                      )}
                    </div>
                    <div className="text-right text-xs text-gray-400">
                      <p className="font-semibold text-gray-600">{approvedCount} approved leaves</p>
                      <p className="font-mono">{emp.employeeNumber}</p>
                    </div>
                  </div>

                  {empRequests.length > 0 && (
                    <div className="border-t border-gray-50 pt-3">
                      <p className="text-xs font-semibold text-gray-500 mb-2">Recent Leave Requests</p>
                      <div className="flex gap-2 flex-wrap">
                        {empRequests.slice(0, 4).map(r => {
                          const policy = LEAVE_POLICIES.find(p => p.type === r.type);
                          return (
                            <div key={r.id} className="flex items-center gap-1.5 bg-gray-50 rounded-lg px-2.5 py-1.5">
                              <div className="w-2 h-2 rounded-full" style={{ background: policy?.color }}></div>
                              <span className="text-xs text-gray-600">{policy?.label || r.type}</span>
                              <span className="text-xs text-gray-400">({r.days}d)</span>
                              <span className={`text-xs font-semibold ${r.status === 'Approved' || r.status === 'HOS Approved' ? 'text-green-600' : r.status === 'Rejected' ? 'text-red-600' : 'text-amber-600'}`}>
                                {r.status === 'HOS Approved' ? 'Approved' : r.status}
                              </span>
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  )}
                </div>
              );
            })
          )}
        </div>
      </div>
    </HODLayout>
  );
}