﻿'use client';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '../../lib/authContext';
import EmployeeLayout from '../../components/EmployeeLayout';
import Link from 'next/link';
import { useLeaveStore } from '../../lib/leaveStore';
import { useTrainingStore } from '../../lib/trainingStore';
import AnimatedCard, { AnimatedStatCard } from '../../components/AnimatedCard';

export default function EmployeeDashboard() {
  // ========== ALL HOOKS FIRST ==========
  const { user, isLoading } = useAuth();
  const router = useRouter();
  const { requests, refreshRequests } = useLeaveStore();
  const { trainingReqs, refreshTrainingReqs } = useTrainingStore();
  
  // ========== STATE FOR API DATA ==========
  const [myAppraisals, setMyAppraisals] = useState<any[]>([]);
  const [myTrainings, setMyTrainings] = useState<any[]>([]);
  const [loadingAppraisals, setLoadingAppraisals] = useState(true);
  const [loadingTrainings, setLoadingTrainings] = useState(true);

  // ========== REDIRECT IF NOT AUTHENTICATED ==========
  useEffect(() => {
    if (!isLoading) {
      if (!user) {
        console.log('No user found, redirecting to login');
        router.replace('/login');
      } else {
        const userRole = user.role?.toLowerCase();
        const validRoles = ['employee', 'intern', 'admin', 'hr'];
        
        if (!validRoles.includes(userRole) && !user.isIntern) {
          console.log('Invalid role for employee page:', userRole);
          router.replace('/login');
        } else {
          console.log('User authenticated:', user.email, 'Role:', userRole);
          // Fetch data from APIs
          fetchEmployeeData();
        }
      }
    }
  }, [user, isLoading, router]);

  // ========== FETCH REAL DATA FROM API ==========
  const fetchEmployeeData = async () => {
    if (!user?.employeeId) return;
    
    // Fetch appraisals
    setLoadingAppraisals(true);
    try {
      const appraisalResponse = await fetch(`/api/performance/appraisals?employeeId=${user.employeeId}`);
      if (appraisalResponse.ok) {
        const data = await appraisalResponse.json();
        setMyAppraisals(data);
      } else {
        console.error('Failed to fetch appraisals');
        setMyAppraisals([]);
      }
    } catch (error) {
      console.error('Error fetching appraisals:', error);
      setMyAppraisals([]);
    } finally {
      setLoadingAppraisals(false);
    }
    
    // Fetch enrolled trainings
    setLoadingTrainings(true);
    try {
      const trainingResponse = await fetch(`/api/training/enrolled?employeeId=${user.employeeId}`);
      if (trainingResponse.ok) {
        const data = await trainingResponse.json();
        setMyTrainings(data);
      } else {
        setMyTrainings([]);
      }
    } catch (error) {
      console.error('Error fetching trainings:', error);
      setMyTrainings([]);
    } finally {
      setLoadingTrainings(false);
    }
    
    // Refresh leave requests and training requests from stores
    await refreshRequests();
    await refreshTrainingReqs();
  };

  // Helper function to get status display
  const getAppraisalStatusClass = (status: string) => {
    switch (status) {
      case 'Completed':
        return 'bg-green-100 text-green-700';
      case 'Approved by HOD':
        return 'bg-purple-100 text-purple-700';
      case 'Submitted':
        return 'bg-blue-100 text-blue-700';
      case 'Pending HOD Approval':
        return 'bg-yellow-100 text-yellow-700';
      default:
        return 'bg-gray-100 text-gray-600';
    }
  };

  // ========== SHOW LOADING STATE ==========
  if (isLoading || loadingAppraisals || loadingTrainings) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <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>
    );
  }

  // ========== CONDITIONAL RETURN ==========
  if (!user) return null;

  // ========== DERIVED VALUES FROM REAL DATA ==========
  const myLeaves = requests.filter(l => l.employeeId === user.employeeId || l.employee === user.name);
  const myTrainingReqs = trainingReqs.filter(r => r.employeeId === user.employeeId);
  
  // Only show enrolled trainings (status = Enrolled or Completed)
  const enrolledTrainings = myTrainings.filter(t => t.status === 'Enrolled' || t.status === 'Completed');
  const upcomingTrainings = myTrainings.filter(t => t.status === 'Enrolled' && t.startDate && new Date(t.startDate) > new Date()).length;
  
  const pendingLeaves = myLeaves.filter(l => l.status === 'Pending' || l.status === 'HOD Approved').length;
  const latestAppraisal = myAppraisals[0];
  const approvedLeaves = myLeaves.filter(l => l.status === 'Approved' || l.status === 'HOS Approved').length;
  const pendingReviews = myLeaves.filter(l => l.status === 'Pending Review').length;
  
  // Calculate average performance score
  const completedAppraisals = myAppraisals.filter(a => a.status === 'Completed' && a.overallRating > 0);
  const avgScore = completedAppraisals.length > 0 
    ? (completedAppraisals.reduce((sum, a) => sum + a.overallRating, 0) / completedAppraisals.length).toFixed(1)
    : 'N/A';

  return (
    <EmployeeLayout title="My Dashboard">
      <div className="mb-6">
        <h2 className="text-xl font-bold text-gray-800">Welcome back, {user.name?.split(' ')[0] || 'Employee'}!</h2>
        <p className="text-gray-500 text-sm mt-1">
          {user.role === 'intern' ? 'Intern' : 'Employee'} · {user.dept || 'ICT'} Department
          <span className="ml-2 text-xs text-gray-400">ID: {user.employeeId}</span>
        </p>
      </div>

      <div className="grid grid-cols-4 gap-5 mb-8">
        <Link href="/employee/leave">
          <AnimatedStatCard delay={0}>
            <div className="flex items-center justify-between mb-3">
              <div className="w-10 h-10 rounded-xl flex items-center justify-center text-white" style={{ background: '#b828a0' }}>
                <i className="ri-calendar-check-line text-lg"></i>
              </div>
              <i className="ri-arrow-right-line text-gray-300 group-hover:text-gray-500 transition-colors"></i>
            </div>
            <p className="text-2xl font-bold text-gray-800">{myLeaves.length}</p>
            <p className="text-sm text-gray-500 mt-0.5">Leave Requests</p>
            <p className="text-xs text-gray-400 mt-1">
              {pendingLeaves} pending · {approvedLeaves} approved
              {pendingReviews > 0 && ` · ${pendingReviews} need review`}
            </p>
          </AnimatedStatCard>
        </Link>

        <Link href="/employee/training">
          <AnimatedStatCard delay={0.1}>
            <div className="flex items-center justify-between mb-3">
              <div className="w-10 h-10 rounded-xl flex items-center justify-center text-white" style={{ background: '#059669' }}>
                <i className="ri-graduation-cap-line text-lg"></i>
              </div>
              <i className="ri-arrow-right-line text-gray-300 group-hover:text-gray-500 transition-colors"></i>
            </div>
            <p className="text-2xl font-bold text-gray-800">{enrolledTrainings.length}</p>
            <p className="text-sm text-gray-500 mt-0.5">My Trainings</p>
            <p className="text-xs text-gray-400 mt-1">
              {upcomingTrainings} upcoming · {myTrainingReqs.length} requested
            </p>
          </AnimatedStatCard>
        </Link>

        <Link href="/employee/performance">
          <AnimatedStatCard delay={0.2}>
            <div className="flex items-center justify-between mb-3">
              <div className="w-10 h-10 rounded-xl flex items-center justify-center text-white" style={{ background: '#d97706' }}>
                <i className="ri-bar-chart-line text-lg"></i>
              </div>
              <i className="ri-arrow-right-line text-gray-300 group-hover:text-gray-500 transition-colors"></i>
            </div>
            <p className="text-2xl font-bold text-gray-800">{myAppraisals.length}</p>
            <p className="text-sm text-gray-500 mt-0.5">Appraisals</p>
            <p className="text-xs text-gray-400 mt-1">
              {latestAppraisal ? latestAppraisal.period : 'No appraisals yet'}
            </p>
          </AnimatedStatCard>
        </Link>

        <Link href="/employee/performance">
          <AnimatedStatCard delay={0.3}>
            <div className="flex items-center justify-between mb-3">
              <div className="w-10 h-10 rounded-xl flex items-center justify-center text-white" style={{ background: '#7c3aed' }}>
                <i className="ri-star-line text-lg"></i>
              </div>
              <i className="ri-arrow-right-line text-gray-300 group-hover:text-gray-500 transition-colors"></i>
            </div>
            <p className="text-2xl font-bold text-gray-800">{avgScore === 'N/A' ? 'N/A' : `${avgScore}/5`}</p>
            <p className="text-sm text-gray-500 mt-0.5">Performance Score</p>
            <p className="text-xs text-gray-400 mt-1">
              {completedAppraisals.length} completed appraisals
            </p>
          </AnimatedStatCard>
        </Link>
      </div>

      <div className="grid grid-cols-2 gap-6">
        {/* Recent Leave Requests */}
        <AnimatedCard delay={0.15}>
          <div className="p-5">
            <div className="flex items-center justify-between mb-4">
              <h3 className="font-semibold text-gray-800">Recent Leave Requests</h3>
              <Link href="/employee/leave" className="text-xs font-medium cursor-pointer" style={{ color: '#b828a0' }}>View all</Link>
            </div>
            {myLeaves.length === 0 ? (
              <p className="text-sm text-gray-400 text-center py-6">No leave requests yet</p>
            ) : (
              <div className="space-y-3">
                {myLeaves.slice(0, 4).map(l => (
                  <div key={l.id} className="flex items-center justify-between py-2 border-b border-gray-50 last:border-0">
                    <div>
                      <p className="text-sm font-medium text-gray-700">{l.type}</p>
                      <p className="text-xs text-gray-400">
                        {new Date(l.startDate).toLocaleDateString()} → {new Date(l.endDate).toLocaleDateString()} ({l.days} days)
                      </p>
                    </div>
                    <span className={`text-xs px-2.5 py-1 rounded-full font-medium ${
                      l.status === 'Approved' || l.status === 'HOS Approved' ? 'bg-green-100 text-green-700' : 
                      l.status === 'Rejected' ? 'bg-red-100 text-red-700' : 
                      'bg-yellow-100 text-yellow-700'
                    }`}>
                      {l.status === 'HOS Approved' ? 'Approved' : l.status}
                    </span>
                  </div>
                ))}
              </div>
            )}
          </div>
        </AnimatedCard>

        {/* My Trainings */}
        <AnimatedCard delay={0.2}>
          <div className="p-5">
            <div className="flex items-center justify-between mb-4">
              <h3 className="font-semibold text-gray-800">My Trainings</h3>
              <Link href="/employee/training" className="text-xs font-medium cursor-pointer" style={{ color: '#b828a0' }}>View all</Link>
            </div>
            {myTrainings.length === 0 ? (
              <p className="text-sm text-gray-400 text-center py-6">Not enrolled in any training</p>
            ) : (
              <div className="space-y-3">
                {myTrainings.slice(0, 4).map(t => (
                  <div key={t.id} className="flex items-center justify-between py-2 border-b border-gray-50 last:border-0">
                    <div>
                      <p className="text-sm font-medium text-gray-700">{t.title}</p>
                      <p className="text-xs text-gray-400">
                        {t.startDate ? new Date(t.startDate).toLocaleDateString() : 'TBD'} · {t.mode || 'Virtual'}
                      </p>
                    </div>
                    <span className={`text-xs px-2.5 py-1 rounded-full font-medium ${
                      t.status === 'Completed' ? 'bg-green-100 text-green-700' : 
                      t.status === 'Ongoing' ? 'bg-blue-100 text-blue-700' : 
                      'bg-yellow-100 text-yellow-700'
                    }`}>
                      {t.status}
                    </span>
                  </div>
                ))}
              </div>
            )}
          </div>
        </AnimatedCard>

        {/* Performance Appraisals - Full width */}
        <AnimatedCard className="col-span-2" delay={0.25}>
          <div className="p-5">
            <div className="flex items-center justify-between mb-4">
              <h3 className="font-semibold text-gray-800">My Performance Appraisals</h3>
              <Link href="/employee/performance" className="text-xs font-medium cursor-pointer" style={{ color: '#b828a0' }}>View all</Link>
            </div>
            {myAppraisals.length === 0 ? (
              <p className="text-sm text-gray-400 text-center py-6">No appraisals found</p>
            ) : (
              <div className="grid grid-cols-3 gap-4">
                {myAppraisals.slice(0, 3).map(a => (
                  <AnimatedCard key={a.id} delay={0.3} hoverScale={1.03}>
                    <div className="p-4">
                      <div className="flex items-center justify-between mb-2">
                        <span className="text-sm font-semibold text-gray-700">{a.period}</span>
                        <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${getAppraisalStatusClass(a.status)}`}>
                          {a.status}
                        </span>
                      </div>
                      <p className="text-2xl font-bold" style={{ color: '#b828a0' }}>
                        {a.overallRating > 0 ? `${a.overallRating.toFixed(1)}/5` : '-'}
                      </p>
                      <p className="text-xs text-gray-400 mt-1">HOD: {a.hodName || 'Not assigned'}</p>
                    </div>
                  </AnimatedCard>
                ))}
              </div>
            )}
          </div>
        </AnimatedCard>
      </div>
    </EmployeeLayout>
  );
}