'use client';
import HODLayout from '../../components/HODLayout';
import { useAuth } from '../../lib/authContext';
import { useLeaveStore } from '../../lib/leaveStore';
import { useTrainingStore } from '../../lib/trainingStore';
import Link from 'next/link';
import { LEAVE_POLICIES } from '../hr/leave/leaveData';
import AnimatedCard, { AnimatedStatCard } from '../../components/AnimatedCard';

const BRAND = '#B22698';

const DEPT_STAFF: Record<string, { name: string; position: string; id: string }[]> = {
  'ICT': [
    { name: 'Peter Otieno', position: 'Systems Developer', id: 'UF002' },
    { name: 'Alice Odhiambo', position: 'Software Developer', id: 'UF009' },
    { name: 'Brian Omondi', position: 'Network Engineer', id: 'UF012' },
  ],
  'Monitoring & Evaluation': [
    { name: 'Jane Mwangi', position: 'M&E Officer', id: 'UF001' },
    { name: 'Fatuma Hassan', position: 'Data Analyst', id: 'UF007' },
    { name: 'Esther Njeri', position: 'M&E Coordinator', id: 'UF011' },
  ],
  'Transport': [
    { name: 'David Wangui', position: 'Driver', id: 'UF004' },
    { name: 'Samuel Kipchoge', position: 'Transport Officer', id: 'UF006' },
  ],
  'Procurement': [
    { name: 'Grace Wanjiku', position: 'Procurement Officer', id: 'UF005' },
    { name: 'John Mutua', position: 'Senior Procurement Manager', id: 'UF008' },
  ],
  'Corporate Communication': [
    { name: 'Mary Kamau', position: 'Communications Officer', id: 'UF003' },
    { name: 'Robert Kariuki', position: 'PR Specialist', id: 'UF010' },
  ],
};

export default function HODDashboard() {
  const { user } = useAuth();
  const { requests } = useLeaveStore();
  const { trainingReqs } = useTrainingStore();

  const dept = user?.dept || 'ICT';
  const deptStaff = DEPT_STAFF[dept] || [];
  const deptRequests = requests.filter(r => r.dept === dept);
  const pendingForMe = deptRequests.filter(r => r.status === 'Pending');
  const totalApproved = deptRequests.filter(r => r.status === 'Approved').length;
  const totalRejected = deptRequests.filter(r => r.status === 'Rejected').length;
  const today = new Date().toISOString().split('T')[0];
  const onLeaveNow = deptRequests.filter(r =>
    r.status === 'Approved' && r.startDate <= today && r.endDate >= today
  );
  const myTrainingReqs = trainingReqs.filter(r => r.dept === dept);
  const pendingTraining = myTrainingReqs.filter(r => r.currentStage !== 'Complete' && r.currentStage !== 'Rejected').length;

  return (
    <HODLayout title="HOD Dashboard">
      <div className="space-y-6">
        {!user && (
          <div className="bg-white rounded-xl border border-gray-100 shadow-sm p-8 text-center text-gray-500">
            Loading...
          </div>
        )}
        <div>
          <h2 className="text-xl font-bold text-gray-800">Welcome, {user?.name || 'User'}</h2>
          <p className="text-gray-500 text-sm mt-1">Head of Department — {dept} | {deptStaff.length} staff members</p>
        </div>

        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          {[
            { label: 'Leave Requests Pending', value: pendingForMe.length, icon: 'ri-time-line', color: '#d97706', bg: '#fef3c7', link: '/hod/requests' },
            { label: 'Currently On Leave', value: onLeaveNow.length, icon: 'ri-user-follow-line', color: '#059669', bg: '#d1fae5', link: '/hod/department' },
            { label: 'Approved This Month', value: totalApproved, icon: 'ri-checkbox-circle-line', color: '#2563eb', bg: '#dbeafe', link: '/hod/history' },
            { label: 'Training Requests', value: pendingTraining, icon: 'ri-graduation-cap-line', color: '#7c3aed', bg: '#ede9fe', link: '/hod/training' },
          ].map((stat, i) => (
            <Link key={stat.label} href={stat.link}>
              <AnimatedStatCard delay={i * 0.1}>
                <div className="flex items-center justify-between mb-3">
                  <div className="w-10 h-10 rounded-xl flex items-center justify-center" style={{ background: stat.bg }}>
                    <i className={`${stat.icon} text-lg`} style={{ color: stat.color }}></i>
                  </div>
                  <i className="ri-arrow-right-line text-gray-300"></i>
                </div>
                <p className="text-2xl font-bold text-gray-800">{stat.value}</p>
                <p className="text-xs text-gray-500 mt-0.5">{stat.label}</p>
              </AnimatedStatCard>
            </Link>
          ))}
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <AnimatedCard delay={0.15}>
            <div className="px-5 py-4 border-b border-gray-100 flex items-center justify-between">
              <div>
                <h3 className="font-bold text-gray-800">Pending Leave Approvals</h3>
                <p className="text-xs text-gray-400 mt-0.5">Requests awaiting your action</p>
              </div>
              <Link href="/hod/requests">
                <span className="text-xs font-semibold cursor-pointer" style={{ color: '#B22698' }}>View all →</span>
              </Link>
            </div>
            {pendingForMe.length === 0 ? (
              <div className="py-10 text-center text-gray-400 text-sm">
                <i className="ri-checkbox-circle-line text-4xl text-green-400 block mb-2"></i>
                No pending requests — all clear!
              </div>
            ) : (
              <div className="divide-y divide-gray-50">
                {pendingForMe.slice(0, 5).map(r => {
                  const policy = LEAVE_POLICIES.find(p => p.type === r.type);
                  return (
                    <div key={r.id} className="px-5 py-3 flex items-center gap-3">
                      <div className="w-9 h-9 rounded-full flex items-center justify-center text-white text-xs font-bold flex-shrink-0" style={{ background: BRAND }}>
                        {r.employee.split(' ').map(n => n[0]).join('').slice(0, 2)}
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="font-medium text-gray-800 text-sm truncate">{r.employee}</p>
                        <p className="text-xs text-gray-400">{policy?.label} · {r.days} day(s) · {r.startDate}</p>
                      </div>
                      <span className="text-xs px-2 py-1 rounded-full bg-amber-100 text-amber-700 font-semibold whitespace-nowrap">Pending</span>
                    </div>
                  );
                })}
              </div>
            )}
          </AnimatedCard>

          <AnimatedCard delay={0.2}>
            <div className="px-5 py-4 border-b border-gray-100 flex items-center justify-between">
              <h3 className="font-bold text-gray-800">My Department — {dept}</h3>
              <Link href="/hod/department">
                <span className="text-xs font-semibold cursor-pointer" style={{ color: '#B22698' }}>View all →</span>
              </Link>
            </div>
            <div className="divide-y divide-gray-50">
              {deptStaff.map(s => {
                const onLeave = onLeaveNow.find(r => r.employee === s.name);
                return (
                  <div key={s.id} className="px-5 py-3 flex items-center gap-3">
                    <div className="w-9 h-9 rounded-full flex items-center justify-center text-white text-xs font-bold flex-shrink-0" style={{ background: '#b828a0' }}>
                      {s.name.split(' ').map(n => n[0]).join('').slice(0, 2)}
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="font-medium text-gray-800 text-sm truncate">{s.name}</p>
                      <p className="text-xs text-gray-400">{s.position}</p>
                    </div>
                    {onLeave ? (
                      <span className="text-xs px-2 py-1 rounded-full bg-green-100 text-green-700 font-semibold whitespace-nowrap">On Leave</span>
                    ) : (
                      <span className="text-xs px-2 py-1 rounded-full bg-blue-100 text-blue-700 font-semibold whitespace-nowrap">Active</span>
                    )}
                  </div>
                );
              })}
            </div>
          </AnimatedCard>
        </div>

        <div className="bg-blue-50 border border-blue-200 rounded-2xl px-5 py-4">
          <div className="flex items-start gap-3">
            <i className="ri-information-line text-blue-600 text-lg mt-0.5"></i>
            <div>
              <p className="font-semibold text-blue-800 text-sm">Approval Workflow — {dept} Department</p>
              <p className="text-xs text-blue-700 mt-1">
                You are the <strong>first reviewer</strong> for all leave and training requests from your department. After you approve, requests move to <strong>HOS (Mr. Peter Lengapiani, MBS)</strong> for secondary review, then to <strong>HR</strong> for final approval.
              </p>
              <div className="flex items-center gap-1 mt-2 text-xs text-blue-600 flex-wrap">
                <span className="px-2 py-0.5 bg-blue-200 rounded-full font-semibold">Employee</span>
                <i className="ri-arrow-right-line"></i>
                <span className="px-2 py-0.5 bg-blue-700 text-white rounded-full font-semibold">You (HOD)</span>
                <i className="ri-arrow-right-line"></i>
                <span className="px-2 py-0.5 bg-green-200 text-green-800 rounded-full font-semibold">HOS (Mr. Peter Lengapiani, MBS)</span>
                <i className="ri-arrow-right-line"></i>
                <span className="px-2 py-0.5 bg-purple-200 text-purple-800 rounded-full font-semibold">HR Final</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </HODLayout>
  );
}
