'use client';
import { useEffect, useState } from 'react';
import { useAuth } from '../../lib/authContext';
import InternLayout from '../../components/InternLayout';
import Link from 'next/link';
import { useRouter } from 'next/navigation';

export default function InternDashboard() {
  const { user, isLoading } = useAuth();
  const router = useRouter();
  const [myLeaves, setMyLeaves] = useState<any[]>([]);
  const [myAppraisals, setMyAppraisals] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [isAuthorized, setIsAuthorized] = useState(false);

  useEffect(() => {
    if (!isLoading) {
      if (!user) {
        router.replace('/login');
        return;
      }
      if (user.role !== 'intern') {
        router.replace('/login');
        return;
      }
      setIsAuthorized(true);
      
      // Fetch real data from API
      fetchInternData();
    }
  }, [user, isLoading, router]);

  const fetchInternData = async () => {
    if (!user?.employeeId) return;
    
    setLoading(true);
    try {
      // Fetch leave requests for this intern only
      const leaveResponse = await fetch(`/api/leave?employeeId=${user.employeeId}`);
      if (leaveResponse.ok) {
        const leaveData = await leaveResponse.json();
        setMyLeaves(leaveData);
      } else {
        console.error('Failed to fetch leave requests');
        setMyLeaves([]);
      }

      // Fetch appraisals for this intern only
      try {
        const appraisalResponse = await fetch(`/api/performance/appraisals?employeeId=${user.employeeId}`);
        if (appraisalResponse.ok) {
          const appraisalData = await appraisalResponse.json();
          setMyAppraisals(appraisalData);
        } else {
          setMyAppraisals([]);
        }
      } catch (err) {
        console.error('Error fetching appraisals:', err);
        setMyAppraisals([]);
      }
    } catch (error) {
      console.error('Error fetching intern data:', error);
    } finally {
      setLoading(false);
    }
  };

  if (isLoading || !isAuthorized || loading) {
    return (
      <InternLayout title="Dashboard">
        <div className="flex justify-center items-center h-64">
          <div className="w-8 h-8 border-2 border-pink-300 border-t-pink-600 rounded-full animate-spin"></div>
        </div>
      </InternLayout>
    );
  }

  if (!user) return null;

  const pendingLeaves = myLeaves.filter(l => l.status === 'Pending').length;
  const approvedLeaves = myLeaves.filter(l => l.status === 'Approved' || l.status === 'HOS Approved').length;
  const rejectedLeaves = myLeaves.filter(l => l.status === 'Rejected').length;
  const currentAppraisal = myAppraisals.find(a => a.status === 'Completed') || myAppraisals[0];

  // Calculate total leave days taken (only approved leaves count)
  const totalLeaveDays = myLeaves
    .filter(l => l.status === 'Approved' || l.status === 'HOS Approved')
    .reduce((sum, l) => sum + (l.days || 0), 0);

  // Intern leave entitlement (15 days for interns)
  const totalEntitlement = 15;
  const remainingLeave = Math.max(0, totalEntitlement - totalLeaveDays);

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

      <div className="grid grid-cols-1 md:grid-cols-3 gap-5 mb-8">
        {/* Leave Requests Card - Links to leave page */}
        <Link href="/intern/leave">
          <div className="bg-white rounded-xl p-5 shadow-sm border border-gray-100 hover:shadow-md transition-all cursor-pointer group">
            <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
              {rejectedLeaves > 0 && ` · ${rejectedLeaves} rejected`}
            </p>
          </div>
        </Link>

        {/* Leave Balance Card - Links to leave page (where balance is shown) */}
        <Link href="/intern/leave">
          <div className="bg-white rounded-xl p-5 shadow-sm border border-gray-100 hover:shadow-md transition-all cursor-pointer group">
            <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-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">{remainingLeave}</p>
            <p className="text-sm text-gray-500 mt-0.5">Leave Balance</p>
            <p className="text-xs text-gray-400 mt-1">
              {totalLeaveDays} days taken of {totalEntitlement}
            </p>
            {remainingLeave <= 3 && remainingLeave > 0 && (
              <p className="text-xs text-amber-600 mt-1 font-semibold">⚠️ Low balance!</p>
            )}
          </div>
        </Link>

        {/* Appraisals Card - Links to performance page */}
        <Link href="/intern/performance">
          <div className="bg-white rounded-xl p-5 shadow-sm border border-gray-100 hover:shadow-md transition-all cursor-pointer group">
            <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-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">{myAppraisals.length}</p>
            <p className="text-sm text-gray-500 mt-0.5">Appraisals</p>
            <p className="text-xs text-gray-400 mt-1">
              {currentAppraisal?.period || 'No appraisals yet'}
            </p>
          </div>
        </Link>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* Recent Leave Requests */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
          <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="/intern/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>
        </div>

        {/* Performance Appraisals */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
          <div className="p-5">
            <div className="flex items-center justify-between mb-4">
              <h3 className="font-semibold text-gray-800">Performance Appraisals</h3>
              <Link href="/intern/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="space-y-3">
                {myAppraisals.slice(0, 3).map(a => (
                  <div key={a.id} className="p-4 bg-gray-50 rounded-xl">
                    <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 ${
                        a.status === 'Completed' ? 'bg-green-100 text-green-700' : 
                        a.status === 'In Progress' ? 'bg-blue-100 text-blue-700' : 
                        'bg-gray-100 text-gray-600'
                      }`}>
                        {a.status}
                      </span>
                    </div>
                    <p className="text-2xl font-bold" style={{ color: '#b828a0' }}>
                      {a.overallScore > 0 ? `${a.overallScore}%` : '-'}
                    </p>
                    <p className="text-xs text-gray-400 mt-1">
                      Grade: <span className="font-semibold text-gray-600">{a.grade || 'Pending'}</span>
                    </p>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>

      <div className="mt-6 bg-blue-50 border border-blue-200 rounded-xl px-4 py-3 flex items-start gap-3">
        <i className="ri-information-line text-blue-600 mt-0.5 text-lg"></i>
        <div className="text-xs text-blue-800">
          <strong>Intern Leave Policy:</strong> Interns are entitled to {totalEntitlement} days annual leave. 
          You have used {totalLeaveDays} days and have {remainingLeave} days remaining.
          Leave workflow: Intern → HOD → HOS (final approval).
        </div>
      </div>
    </InternLayout>
  );
}