'use client';
import { useState, useEffect } from 'react';
import HOSLayout from '../../components/HOSLayout';
import { useAuth } from '../../lib/authContext';
import Link from 'next/link';
import AnimatedCard, { AnimatedStatCard } from '../../components/AnimatedCard';

interface LeaveRequest {
  id: string;
  employeeId: string;
  employeeName: string;
  dept: string;
  type: string;
  days: number;
  status: string;
  hodApprovedOn: string;
  startDate: string;
  endDate: string;
  reason: string;
}

interface TrainingRequest {
  id: string;
  employeeId: string;
  employeeName: string;
  dept: string;
  courseRequested: string;
  estimatedCost: number;
  status: string;
  currentStage: string;
}

interface DepartmentSummary {
  dept: string;
  pending: number;
  hodApproved: number;
  approved: number;
}

export default function HOSDashboard() {
  const { user, isLoading } = useAuth();
  const [pendingHOS, setPendingHOS] = useState<LeaveRequest[]>([]);
  const [hosApproved, setHosApproved] = useState<LeaveRequest[]>([]);
  const [fullyApproved, setFullyApproved] = useState<LeaveRequest[]>([]);
  const [pendingTrainingHOS, setPendingTrainingHOS] = useState<TrainingRequest[]>([]);
  const [deptSummary, setDeptSummary] = useState<DepartmentSummary[]>([]);
  const [loading, setLoading] = useState(true);

  const departments = ['ICT', 'Monitoring & Evaluation', 'Transport', 'Procurement', 'Corporate Communication'];

  useEffect(() => {
    if (user) {
      fetchData();
    }
  }, [user]);

  const fetchData = async () => {
    try {
      setLoading(true);
      
      // Fetch leave requests
      const leaveRes = await fetch('/api/leave');
      const leaveData = await leaveRes.json();
      const leaveRequests = Array.isArray(leaveData) ? leaveData : [];
      
      // Filter by status
      setPendingHOS(leaveRequests.filter((r: LeaveRequest) => r.status === 'HOD Approved'));
      setHosApproved(leaveRequests.filter((r: LeaveRequest) => r.status === 'HOS Approved'));
      setFullyApproved(leaveRequests.filter((r: LeaveRequest) => r.status === 'Approved'));
      
      // Department summary
      const summary = departments.map(dept => ({
        dept,
        pending: leaveRequests.filter((r: LeaveRequest) => r.dept === dept && r.status === 'Pending').length,
        hodApproved: leaveRequests.filter((r: LeaveRequest) => r.dept === dept && r.status === 'HOD Approved').length,
        approved: leaveRequests.filter((r: LeaveRequest) => r.dept === dept && r.status === 'Approved').length,
      }));
      setDeptSummary(summary);
      
      // Fetch training requests
      const trainingRes = await fetch('/api/training/requests');
      const trainingData = await trainingRes.json();
      const trainingRequests = Array.isArray(trainingData) ? trainingData : [];
      setPendingTrainingHOS(trainingRequests.filter((r: TrainingRequest) => r.currentStage === 'HOS'));
      
    } catch (error) {
      console.error('Error fetching dashboard data:', error);
    } finally {
      setLoading(false);
    }
  };

  if (isLoading || loading) {
    return (
      <HOSLayout title="HOS Dashboard">
        <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 dashboard...</p>
          </div>
        </div>
      </HOSLayout>
    );
  }

  if (!user) return null;

  const statCards = [
    { label: 'Leave Requests Awaiting Review', value: pendingHOS.length, icon: 'ri-time-line', color: '#d97706', bg: '#fef3c7', link: '/hos/requests' },
    { label: 'Training Requests Awaiting Review', value: pendingTrainingHOS.length, icon: 'ri-graduation-cap-line', color: '#7c3aed', bg: '#ede9fe', link: '/hos/training' },
    { label: 'Forwarded to HR', value: hosApproved.length, icon: 'ri-send-plane-line', color: '#059669', bg: '#d1fae5', link: '/hos/requests' },
    { label: 'Fully Approved', value: fullyApproved.length, icon: 'ri-checkbox-circle-line', color: '#2563eb', bg: '#dbeafe', link: '/hos/audit' },
  ];

  return (
    <HOSLayout title="HOS Dashboard">
      <div className="space-y-6">
        <div>
          <h2 className="text-xl font-bold text-gray-800">Welcome, {user.name}</h2>
          <p className="text-gray-500 text-sm mt-1">Head of Secretariat — Oversee all 5 departments: ICT, M&E, Transport, Procurement, Corporate Communication</p>
        </div>

        {/* Stats Cards */}
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          {statCards.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">
          {/* Pending Leave Requests */}
          <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">Leave Requests Awaiting Your Review</h3>
                <p className="text-xs text-gray-400 mt-0.5">HOD-approved requests pending HOS review</p>
              </div>
              <Link href="/hos/requests">
                <span className="text-xs font-semibold cursor-pointer" style={{ color: '#b828a0' }}>View all →</span>
              </Link>
            </div>
            {pendingHOS.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 reviews — all clear!
              </div>
            ) : (
              <div className="divide-y divide-gray-50">
                {pendingHOS.slice(0, 5).map((r) => (
                  <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: '#b828a0' }}>
                      {r.employeeName?.split(' ').map((n: string) => n[0]).join('').slice(0, 2) || 'EM'}
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="font-medium text-gray-800 text-sm truncate">{r.employeeName}</p>
                      <p className="text-xs text-gray-400">{r.dept} · {r.type} · {r.days} day(s)</p>
                      <p className="text-xs text-blue-500">HOD approved on {r.hodApprovedOn ? new Date(r.hodApprovedOn).toLocaleDateString() : 'N/A'}</p>
                    </div>
                    <Link href={`/hos/requests/${r.id}`}>
                      <span className="text-xs px-3 py-1.5 rounded-full bg-amber-100 text-amber-700 font-semibold cursor-pointer whitespace-nowrap">Review</span>
                    </Link>
                  </div>
                ))}
              </div>
            )}
          </AnimatedCard>

          {/* Department Overview */}
          <AnimatedCard delay={0.2}>
            <div className="px-5 py-4 border-b border-gray-100">
              <h3 className="font-bold text-gray-800">Department Overview</h3>
              <p className="text-xs text-gray-400 mt-0.5">Leave status across all 5 departments</p>
            </div>
            <div className="divide-y divide-gray-50">
              {deptSummary.map(d => (
                <div key={d.dept} className="px-5 py-3 flex items-center gap-3">
                  <div className="flex-1 min-w-0">
                    <p className="font-medium text-gray-800 text-sm">{d.dept}</p>
                  </div>
                  <div className="flex items-center gap-2 text-xs flex-wrap">
                    {d.pending > 0 && <span className="px-2 py-0.5 rounded-full bg-amber-100 text-amber-700 font-semibold">{d.pending} pending</span>}
                    {d.hodApproved > 0 && <span className="px-2 py-0.5 rounded-full bg-blue-100 text-blue-700 font-semibold">{d.hodApproved} HOD ✓</span>}
                    {d.approved > 0 && <span className="px-2 py-0.5 rounded-full bg-green-100 text-green-700 font-semibold">{d.approved} approved</span>}
                    {d.pending === 0 && d.hodApproved === 0 && d.approved === 0 && <span className="text-gray-400">No requests</span>}
                  </div>
                </div>
              ))}
            </div>
          </AnimatedCard>
        </div>

        {/* Pending Training Requests */}
        {pendingTrainingHOS.length > 0 && (
          <AnimatedCard delay={0.25}>
            <div className="px-5 py-4 border-b border-gray-100 flex items-center justify-between">
              <div>
                <h3 className="font-bold text-gray-800">Training Requests Awaiting Your Review</h3>
                <p className="text-xs text-gray-400 mt-0.5">HR-approved training requests pending HOS review</p>
              </div>
              <Link href="/hos/training">
                <span className="text-xs font-semibold cursor-pointer" style={{ color: '#b828a0' }}>View all →</span>
              </Link>
            </div>
            <div className="divide-y divide-gray-50">
              {pendingTrainingHOS.slice(0, 4).map(r => (
                <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: '#7c3aed' }}>
                    {r.employeeName?.split(' ').map((n: string) => n[0]).join('').slice(0, 2) || 'EM'}
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="font-medium text-gray-800 text-sm truncate">{r.courseRequested}</p>
                    <p className="text-xs text-gray-400">{r.employeeName} · {r.dept} · KES {r.estimatedCost?.toLocaleString() || '0'}</p>
                  </div>
                  <span className="text-xs px-2 py-1 rounded-full bg-purple-100 text-purple-700 font-semibold whitespace-nowrap">Pending HOS</span>
                </div>
              ))}
            </div>
          </AnimatedCard>
        )}

        {/* Role Info Card */}
        <div className="rounded-2xl px-5 py-4" style={{ background: '#fce7f3', border: '1px solid #B22698' }}>
          <div className="flex items-start gap-3">
            <i className="ri-information-line text-lg mt-0.5" style={{ color: '#B22698' }}></i>
            <div>
              <p className="font-semibold text-sm" style={{ color: '#B22698' }}>Your Role — Head of Secretariat</p>
              <p className="text-xs mt-1" style={{ color: '#B22698' }}>
                You oversee all 5 departments. You review HOD-approved requests before forwarding to HR for final approval.
              </p>
              <div className="flex items-center gap-1 mt-2 text-xs flex-wrap" style={{ color: '#B22698' }}>
                <span className="px-2 py-0.5 rounded-full font-semibold" style={{ background: '#fce7f3' }}>Employee → HOD</span>
                <i className="ri-arrow-right-line"></i>
                <span className="px-2 py-0.5 rounded-full font-semibold text-white" style={{ background: '#B22698' }}>You (HOS)</span>
                <i className="ri-arrow-right-line"></i>
                <span className="px-2 py-0.5 rounded-full font-semibold" style={{ background: '#fce7f3', color: '#B22698' }}>HR Final</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </HOSLayout>
  );
}