'use client';
import { useState } from 'react';
import { useAuth } from '../../../lib/authContext';
import EmployeeLayout from '../../../components/EmployeeLayout';
import { useLeaveStore } from '../../../lib/leaveStore';
import {
  LEAVE_POLICIES, LeaveRequest,
  isCurrentlyOnLeave, getUpcomingLeave, computeEmployeeBalance, getAvailableLeaveTypes
} from '../../hr/leave/leaveData';
import NewLeaveRequestModal from '../../hr/leave/NewLeaveRequestModal';
import LeavePolicyTab from '../../hr/leave/LeavePolicyTab';
import LeaveCalendarTab from '../../hr/leave/LeaveCalendarTab';
import LeaveDetailModal from '../../hr/leave/LeaveDetailModal';
import { downloadApprovalLetterPdf } from '../../../lib/leaveComputationPdf';
import { downloadLeaveComputationForm } from '../../../lib/leaveComputationForm';
import { calculateDays, getMinStartDate } from '../../hr/leave/leaveData';

function EditResubmitModal({ request, allRequests, onClose, onResubmit }: { request: LeaveRequest; allRequests: LeaveRequest[]; onClose: () => void; onResubmit: (u: LeaveRequest) => void }) {
  const today = new Date().toISOString().split('T')[0];
  const minStart = getMinStartDate(request.type);
  const [form, setForm] = useState({ startDate: request.reviewNewStart || request.startDate, endDate: request.reviewNewEnd || request.endDate, reason: request.reason });
  const [errors, setErrors] = useState<string[]>([]);
  const days = calculateDays(form.startDate, form.endDate);
  const policy = LEAVE_POLICIES.find(p => p.type === request.type);
  const handleSubmit = () => {
    const errs: string[] = [];
    if (!form.startDate || !form.endDate) errs.push('Please select both dates.');
    if (form.endDate < form.startDate) errs.push('End date must be after start date.');
    if (days <= 0) errs.push('Invalid date range.');
    if (errs.length > 0) { setErrors(errs); return; }
    onResubmit({ ...request, startDate: form.startDate, endDate: form.endDate, days, reason: form.reason, status: 'Pending', reviewComment: undefined, reviewRequested: false, reviewBy: undefined, reviewDate: undefined, reviewNewStart: undefined, reviewNewEnd: undefined, hodApprovedBy: undefined, hodApprovedOn: undefined, submittedOn: today });
  };
  return (
    <div className="fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg">
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-100" style={{ background: '#7c3aed' }}>
          <div><h3 className="font-bold text-white">Edit & Resubmit Leave Request</h3><p className="text-violet-200 text-xs mt-0.5">{request.id} — {policy?.label}</p></div>
          <button onClick={onClose} className="w-8 h-8 flex items-center justify-center cursor-pointer"><i className="ri-close-line text-white text-xl"></i></button>
        </div>
        <div className="p-6 space-y-4">
          {request.reviewComment && (<div className="bg-violet-50 border border-violet-200 rounded-xl px-4 py-3"><p className="text-xs font-semibold text-violet-700 mb-1">Review Comment from {request.reviewBy || 'HOD/HOS'}:</p><p className="text-sm text-violet-800">{request.reviewComment}</p>{request.reviewNewStart && request.reviewNewEnd && (<p className="text-xs text-violet-600 mt-1">Suggested: {request.reviewNewStart} → {request.reviewNewEnd}</p>)}</div>)}
          {errors.length > 0 && (<div className="bg-red-50 border border-red-200 rounded-xl px-4 py-3">{errors.map((e, i) => <p key={i} className="text-xs text-red-700">{e}</p>)}</div>)}
          <div className="grid grid-cols-2 gap-3">
            <div><label className="block text-xs font-semibold text-gray-600 mb-1.5">Start Date *</label><input type="date" value={form.startDate} min={minStart} onChange={e => setForm(f => ({ ...f, startDate: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm outline-none" /></div>
            <div><label className="block text-xs font-semibold text-gray-600 mb-1.5">End Date *</label><input type="date" value={form.endDate} min={form.startDate} onChange={e => setForm(f => ({ ...f, endDate: e.target.value }))} className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm outline-none" /></div>
          </div>
          {days > 0 && <div className="bg-blue-50 text-blue-700 text-sm px-4 py-2.5 rounded-lg">{days} day(s) selected</div>}
          {request.type !== 'Annual' && (<div><label className="block text-xs font-semibold text-gray-600 mb-1.5">Reason</label><textarea value={form.reason} onChange={e => setForm(f => ({ ...f, reason: e.target.value }))} rows={3} className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm outline-none resize-none" /></div>)}
        </div>
        <div className="px-6 py-4 border-t border-gray-100 flex gap-3 justify-end">
          <button onClick={onClose} className="px-4 py-2.5 border border-gray-200 rounded-xl text-sm text-gray-600 cursor-pointer whitespace-nowrap">Cancel</button>
          <button onClick={handleSubmit} className="px-6 py-2.5 text-white rounded-xl text-sm font-semibold cursor-pointer whitespace-nowrap" style={{ background: '#7c3aed' }}><i className="ri-send-plane-line mr-1"></i> Resubmit</button>
        </div>
      </div>
    </div>
  );
}

type TabKey = 'overview' | 'history' | 'calendar' | 'policy';

const STATUS_CONFIG: Record<string, { color: string; bg: string }> = {
  Pending: { color: '#d97706', bg: '#fef3c7' },
  'Pending Review': { color: '#7c3aed', bg: '#ede9fe' },
  'HOD Approved': { color: '#2563eb', bg: '#dbeafe' },
  'HOS Approved': { color: '#059669', bg: '#d1fae5' },
  Approved: { color: '#16a34a', bg: '#dcfce7' },
  Rejected: { color: '#dc2626', bg: '#fee2e2' },
  Cancelled: { color: '#6b7280', bg: '#f3f4f6' },
};

function ApprovalLetterModal({ request, onClose }: { request: LeaveRequest; onClose: () => void }) {
  const policy = LEAVE_POLICIES.find(p => p.type === request.type);

  const handleDownload = () => {
    downloadApprovalLetterPdf(request);
  };

  return (
    <div className="fixed inset-0 bg-black/50 z-[60] flex items-center justify-center p-4">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-100" style={{ background: '#b828a0' }}>
          <div>
            <h3 className="font-bold text-white text-lg">Leave Approval Letter</h3>
            <p className="text-pink-200 text-sm">Official document — {request.id}</p>
          </div>
          <button onClick={onClose} className="w-8 h-8 flex items-center justify-center rounded-lg bg-white/20 cursor-pointer">
            <i className="ri-close-line text-white"></i>
          </button>
        </div>

        <div className="p-8">
          <div className="border-2 border-gray-200 rounded-xl p-6 font-mono text-sm text-gray-700 space-y-4 bg-gray-50">
            <div className="text-center border-b border-gray-300 pb-4">
              <p className="text-lg font-bold text-gray-900">UWEZO FUND OVERSIGHT BOARD</p>
              <p className="text-sm text-gray-600">LEAVE APPROVAL LETTER</p>
            </div>
            <div className="flex justify-between text-xs">
              <span>Date: {request.approvedOn || new Date().toLocaleDateString('en-KE', { day: 'numeric', month: 'long', year: 'numeric' })}</span>
              <span>Ref: {request.id}</span>
            </div>
            <div className="space-y-1 text-xs">
              <p><strong>To:</strong> {request.employee}</p>
              <p><strong>Department:</strong> {request.dept}</p>
              <p><strong>Position:</strong> {request.position}</p>
            </div>
            <p className="text-xs">Dear {request.employee?.split(' ')[0] || 'Employee'},</p>
            <p className="text-xs font-bold underline">RE: APPROVAL OF {(policy?.label || request.type).toUpperCase()} APPLICATION</p>
            <p className="text-xs">This is to confirm that your application for <strong>{policy?.label || request.type}</strong> has been reviewed and <strong className="text-green-700">APPROVED</strong>.</p>
            <div className="bg-white border border-gray-200 rounded-lg p-3 space-y-1 text-xs">
              <p className="font-bold mb-2">LEAVE DETAILS:</p>
              <p>• Leave Type: {policy?.label || request.type}</p>
              <p>• Start Date: {request.startDate}</p>
              <p>• End Date: {request.endDate}</p>
              <p>• Duration: {request.days} day(s)</p>
              <p>• Reason: {request.reason}</p>
            </div>
            <p className="text-xs">You are required to report back to duty on the next working day after <strong>{request.endDate}</strong>.</p>
            <p className="text-xs">Please ensure that your duties are properly handed over before proceeding on leave.</p>
            <div className="grid grid-cols-2 gap-4 pt-4 border-t border-gray-200 text-xs">
              <div>
                <p className="font-bold">Approved by: {request.approvedBy || 'HR Manager'}</p>
                <p>Date: {request.approvedOn || new Date().toLocaleDateString('en-KE', { day: 'numeric', month: 'long', year: 'numeric' })}</p>
                <div className="mt-4 border-t border-gray-400 pt-1">
                  <p>HR MANAGER, UWEZO FUND</p>
                </div>
              </div>
              <div>
                <div className="mt-8 border-t border-gray-400 pt-1">
                  <p>HEAD OF DEPARTMENT</p>
                </div>
              </div>
            </div>
            <p className="text-xs text-gray-400 text-center border-t border-gray-200 pt-3">Uwezo Fund HRMS Version 2.0.1 © 2026</p>
          </div>
        </div>

        <div className="px-6 py-4 border-t border-gray-100 flex gap-3 justify-end">
          <button onClick={onClose}
            className="px-4 py-2.5 border border-gray-200 rounded-xl text-sm text-gray-600 cursor-pointer whitespace-nowrap">
            Close
          </button>
          <button onClick={handleDownload}
            className="flex items-center gap-2 px-5 py-2.5 text-white rounded-xl text-sm font-semibold cursor-pointer whitespace-nowrap"
            style={{ background: '#b828a0' }}>
            <i className="ri-download-line"></i> Download Letter
          </button>
        </div>
      </div>
    </div>
  );
}

export default function EmployeeLeavePage() {
  const { user } = useAuth();
  const { requests, updateRequests } = useLeaveStore();
  const [showNew, setShowNew] = useState(false);
  const [activeTab, setActiveTab] = useState<TabKey>('overview');
  const [toast, setToast] = useState('');
  const [viewRequest, setViewRequest] = useState<LeaveRequest | null>(null);
  const [showLetter, setShowLetter] = useState<LeaveRequest | null>(null);
  const [editRequest, setEditRequest] = useState<LeaveRequest | null>(null);

  if (!user) return null;

  const empId = user.employeeId || 'E001';
  const empName = user.name || '';
  const empDept = user.dept || 'HR';
  const empType: 'Employee' | 'Intern' = (user as any).isIntern ? 'Intern' : 'Employee';
  const empGender: 'Male' | 'Female' = (user as any).gender || 'Female';

  const myRequests = requests.filter(r => r.employeeId === empId);
  const currentLeave = isCurrentlyOnLeave(empId, requests);
  const upcomingLeave = getUpcomingLeave(empId, requests);

  const showToast = (msg: string) => { setToast(msg); setTimeout(() => setToast(''), 3500); };

  const handleSubmit = (req: LeaveRequest) => {
    updateRequests(prev => [req, ...prev]);
    setShowNew(false);
    showToast('Leave request submitted! HR has been notified at hr@uwezo.go.ke');
  };

  const handleResubmit = (updated: LeaveRequest) => {
    updateRequests(prev => prev.map(r => r.id === updated.id ? updated : r));
    setEditRequest(null);
    showToast('Leave request resubmitted! Forwarded to HOD for review.');
  };

  const myBalances = getAvailableLeaveTypes(empGender, empType === 'Intern')
    .map(type => computeEmployeeBalance(empId, type, empType === 'Intern', requests));

  const TABS = [
    { key: 'overview' as TabKey, label: 'Overview', icon: 'ri-dashboard-line' },
    { key: 'history' as TabKey, label: 'My Requests', icon: 'ri-file-list-3-line' },
    { key: 'calendar' as TabKey, label: 'My Calendar', icon: 'ri-calendar-2-line' },
    { key: 'policy' as TabKey, label: 'Leave Policy', icon: 'ri-book-open-line' },
  ];

  return (
    <EmployeeLayout title="My Leave">
      {toast && (
        <div className="fixed top-20 right-6 z-[100] bg-green-600 text-white px-5 py-3 rounded-xl shadow-lg flex items-center gap-2">
          <i className="ri-checkbox-circle-line text-lg"></i>
          <span className="text-sm font-medium">{toast}</span>
        </div>
      )}

      <div className="flex items-center justify-between mb-5">
        <div>
          <h2 className="text-lg font-bold text-gray-800">Leave Management</h2>
          <p className="text-sm text-gray-500">Manage your leave requests and view balances</p>
        </div>
        <button onClick={() => setShowNew(true)}
          className="flex items-center gap-2 text-white px-4 py-2.5 rounded-xl text-sm font-semibold cursor-pointer whitespace-nowrap"
          style={{ background: '#b828a0' }}>
          <i className="ri-add-line"></i> New Request
        </button>
      </div>

      {/* Review notifications */}
      {myRequests.filter(r => r.status === 'Pending Review').length > 0 && (
        <div className="space-y-3 mb-5">
          {myRequests.filter(r => r.status === 'Pending Review').map(r => (
            <div key={r.id} className="bg-violet-50 border border-violet-200 rounded-xl px-4 py-3 flex items-start gap-3">
              <div className="w-8 h-8 flex items-center justify-center rounded-full bg-violet-100 flex-shrink-0">
                <i className="ri-refresh-line text-violet-600"></i>
              </div>
              <div className="flex-1">
                <p className="text-sm font-semibold text-violet-800">Review Required — {r.id}</p>
                <p className="text-xs text-violet-600 mt-0.5">
                  {r.reviewBy || 'HOD/HOS'} requested a review on {r.reviewDate}:
                </p>
                <p className="text-xs text-violet-700 mt-1 bg-white/60 rounded-lg px-3 py-2">{r.reviewComment}</p>
                {r.reviewNewStart && r.reviewNewEnd && (
                  <p className="text-xs text-violet-500 mt-1">
                    Suggested dates: {r.reviewNewStart} → {r.reviewNewEnd}
                  </p>
                )}
                <button onClick={() => setEditRequest(r)}
                  className="mt-2 flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-white text-xs font-semibold cursor-pointer whitespace-nowrap"
                  style={{ background: '#7c3aed' }}>
                  <i className="ri-edit-line"></i> Edit & Resubmit
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Low balance alert */}
      {myBalances.some(b => b.remaining <= 3 && b.entitlement > 0) && (
        <div className="bg-amber-50 border border-amber-200 rounded-xl px-4 py-3 flex items-start gap-3 mb-5">
          <i className="ri-alarm-warning-line text-amber-600 mt-0.5"></i>
          <div>
            <p className="text-sm font-semibold text-amber-800">Low Leave Balance</p>
            {myBalances.filter(b => b.remaining <= 3 && b.entitlement > 0).map(b => {
              const p = LEAVE_POLICIES.find(pp => pp.type === b.type);
              return (
                <p key={b.type} className="text-xs text-amber-700 mt-0.5">
                  {p?.label}: only {b.remaining} day{b.remaining !== 1 ? 's' : ''} remaining
                </p>
              );
            })}
          </div>
        </div>
      )}

      <div className="flex items-center gap-1 flex-wrap mb-5 bg-white border border-gray-100 rounded-2xl px-2 py-2 shadow-sm">
        {TABS.map(tab => (
          <button key={tab.key} onClick={() => setActiveTab(tab.key)}
            className="flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-medium cursor-pointer whitespace-nowrap transition-all"
            style={activeTab === tab.key ? { background: '#b828a0', color: '#fff' } : { color: '#6b7280' }}>
            <i className={tab.icon}></i>
            {tab.label}
          </button>
        ))}
      </div>

      {activeTab === 'overview' && (
        <div className="space-y-5">
          <div className="grid grid-cols-3 gap-4">
            <div className={`rounded-2xl p-5 border-2 ${currentLeave ? 'border-green-300 bg-green-50' : 'border-gray-200 bg-white'}`}>
              <div className="flex items-center gap-3 mb-3">
                <div className={`w-10 h-10 rounded-xl flex items-center justify-center ${currentLeave ? 'bg-green-500' : 'bg-gray-200'}`}>
                  <i className={`${currentLeave ? 'ri-user-follow-line' : 'ri-user-line'} text-white text-lg`}></i>
                </div>
                <div>
                  <p className="text-xs text-gray-500 font-medium">Current Status</p>
                  <p className={`text-sm font-bold ${currentLeave ? 'text-green-700' : 'text-gray-700'}`}>
                    {currentLeave ? 'ON LEAVE' : 'NOT ON LEAVE'}
                  </p>
                </div>
              </div>
              {currentLeave ? (
                <div className="bg-green-100 rounded-xl px-3 py-2">
                  <p className="text-xs font-semibold text-green-700">{LEAVE_POLICIES.find(p => p.type === currentLeave.type)?.label}</p>
                  <p className="text-xs text-green-600">Until {currentLeave.endDate}</p>
                </div>
              ) : (
                <p className="text-xs text-gray-400">You are currently at work</p>
              )}
            </div>

            <div className="rounded-2xl p-5 border border-gray-200 bg-white">
              <div className="flex items-center gap-3 mb-3">
                <div className="w-10 h-10 rounded-xl flex items-center justify-center" style={{ background: '#b828a0' }}>
                  <i className="ri-calendar-event-line text-white text-lg"></i>
                </div>
                <div>
                  <p className="text-xs text-gray-500 font-medium">Upcoming Leave</p>
                  <p className="text-sm font-bold text-gray-700">
                    {upcomingLeave ? LEAVE_POLICIES.find(p => p.type === upcomingLeave.type)?.label : 'None scheduled'}
                  </p>
                </div>
              </div>
              {upcomingLeave ? (
                <div className="rounded-xl px-3 py-2" style={{ background: '#fdf4ff' }}>
                  <p className="text-xs font-semibold" style={{ color: '#b828a0' }}>{upcomingLeave.startDate} → {upcomingLeave.endDate}</p>
                  <p className="text-xs text-gray-500">{upcomingLeave.days} day(s)</p>
                </div>
              ) : (
                <p className="text-xs text-gray-400">No upcoming approved leave</p>
              )}
            </div>

            <div className="rounded-2xl p-5 border border-gray-200 bg-white">
              <div className="flex items-center gap-3 mb-3">
                <div className="w-10 h-10 rounded-xl flex items-center justify-center bg-amber-500">
                  <i className="ri-time-line text-white text-lg"></i>
                </div>
                <div>
                  <p className="text-xs text-gray-500 font-medium">Pending Requests</p>
                  <p className="text-sm font-bold text-gray-700">{myRequests.filter(r => r.status === 'Pending' || r.status === 'HOD Approved').length} awaiting approval</p>
                </div>
              </div>
              <p className="text-xs text-gray-400">{empType === 'Intern' ? 'Interns: HOD → HR' : 'Employees: HOD → HOS → HR'}</p>
            </div>
          </div>

          <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
            <div className="px-5 py-3 border-b border-gray-100">
              <h3 className="font-semibold text-gray-700">My Leave Balance</h3>
              <p className="text-xs text-gray-400 mt-0.5">Remaining = Entitlement − Days Taken (approved leaves only)</p>
            </div>
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="bg-gray-50 border-b border-gray-100">
                    <th className="text-left px-5 py-3 text-xs font-semibold text-gray-500 uppercase">Leave Type</th>
                    <th className="text-center px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Entitlement</th>
                    <th className="text-center px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Taken</th>
                    <th className="text-center px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Remaining</th>
                    <th className="text-center px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Carryover</th>
                  </tr>
                </thead>
                <tbody>
                  {myBalances.map(bal => {
                    const policy = LEAVE_POLICIES.find(p => p.type === bal.type);
                    const pct = bal.entitlement > 0 ? Math.min(100, (bal.taken / bal.entitlement) * 100) : 0;
                    const isLow = bal.remaining <= 3 && bal.entitlement > 0;
                    return (
                      <tr key={bal.type} className="border-b border-gray-50 hover:bg-gray-50/50">
                        <td className="px-5 py-3">
                          <div className="flex items-center gap-2.5">
                            <div className="w-7 h-7 rounded-lg flex items-center justify-center flex-shrink-0" style={{ background: (policy?.color || '#9ca3af') + '20' }}>
                              <i className={`${policy?.icon || 'ri-calendar-line'} text-xs`} style={{ color: policy?.color || '#9ca3af' }}></i>
                            </div>
                            <span className="font-medium text-gray-700">{policy?.label || bal.type}</span>
                          </div>
                        </td>
                        <td className="px-4 py-3 text-center text-gray-600">
                          {bal.entitlement === 0 ? 'Unlimited' : `${bal.entitlement} days`}
                        </td>
                        <td className="px-4 py-3 text-center">
                          <div>
                            <span className="font-semibold text-gray-700">{bal.taken} days</span>
                            {bal.entitlement > 0 && (
                              <div className="w-16 bg-gray-100 rounded-full h-1 mx-auto mt-1">
                                <div className="h-1 rounded-full" style={{ width: `${pct}%`, background: policy?.color || '#9ca3af' }}></div>
                              </div>
                            )}
                          </div>
                        </td>
                        <td className="px-4 py-3 text-center">
                          <span className={`inline-flex items-center justify-center px-2.5 py-1 rounded-full text-sm font-bold ${isLow ? 'bg-red-100 text-red-700' : 'bg-green-100 text-green-700'}`}>
                            {bal.entitlement === 0 ? '∞' : `${bal.remaining} days`}
                          </span>
                        </td>
                        <td className="px-4 py-3 text-center text-sm text-amber-600 font-medium">
                          {bal.carryover > 0 ? `${bal.carryover} days` : <span className="text-gray-300">—</span>}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>

          <div className="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>Important Rules:</strong> Leave must be applied at least 14 days before the start date. End date must be after start date. You cannot request leave for today or past dates. Requests cannot exceed your remaining balance. Once submitted, you cannot edit or delete your request. <strong>Employees:</strong> HOD → HOS → HR. <strong>Interns:</strong> HOD → HR (no HOS step). An email notification will be sent to HR at hr@uwezo.go.ke upon submission.
            </div>
          </div>
        </div>
      )}

      {activeTab === 'history' && (
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
          <div className="px-5 py-3 border-b border-gray-100 flex items-center justify-between">
            <h3 className="font-semibold text-gray-700">My Leave Requests</h3>
            <span className="text-xs text-gray-400">{myRequests.length} total requests</span>
          </div>
          {myRequests.length === 0 ? (
            <div className="text-center py-12 text-gray-400">
              <div className="w-12 h-12 flex items-center justify-center mx-auto mb-3">
                <i className="ri-calendar-line text-4xl"></i>
              </div>
              <p>No leave requests yet</p>
              <button onClick={() => setShowNew(true)}
                className="mt-3 px-4 py-2 rounded-lg text-sm font-semibold text-white cursor-pointer whitespace-nowrap"
                style={{ background: '#b828a0' }}>
                Submit First Request
              </button>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="bg-gray-50 border-b border-gray-100">
                    <th className="text-left px-5 py-3 text-xs font-semibold text-gray-500 uppercase">Request ID</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Leave Type</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Start Date</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">End Date</th>
                    <th className="text-center px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Days</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Reason</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Status</th>
                    <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Submitted</th>
                    <th className="text-right px-4 py-3 text-xs font-semibold text-gray-500 uppercase">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {myRequests.map(req => {
                    const st = STATUS_CONFIG[req.status] || STATUS_CONFIG['Pending'];
                    const policy = LEAVE_POLICIES.find(p => p.type === req.type);
                    return (
                      <tr key={req.id} className="border-b border-gray-50 hover:bg-gray-50/50">
                        <td className="px-5 py-3 font-mono text-xs text-gray-500">{req.id}</td>
                        <td className="px-4 py-3">
                          <div className="flex items-center gap-1.5">
                            <div className="w-2 h-2 rounded-full" style={{ background: policy?.color }}></div>
                            <span className="text-sm text-gray-700">{policy?.label}</span>
                          </div>
                        </td>
                        <td className="px-4 py-3 text-gray-600">{req.startDate}</td>
                        <td className="px-4 py-3 text-gray-600">{req.endDate}</td>
                        <td className="px-4 py-3 text-center font-semibold text-gray-800">{req.days}</td>
                        <td className="px-4 py-3 text-xs text-gray-500 max-w-[160px] truncate">{req.reason}</td>
                        <td className="px-4 py-3">
                          <span className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-semibold"
                            style={{ color: st.color, background: st.bg }}>
                            {req.status}
                          </span>
                          {req.status === 'Rejected' && req.rejectionReason && (
                            <p className="text-xs text-red-500 mt-0.5 max-w-[160px] truncate">{req.rejectionReason}</p>
                          )}
                        </td>
                        <td className="px-4 py-3 text-xs text-gray-400">{req.submittedOn}</td>
                        <td className="px-4 py-3 text-right">
                          <div className="flex items-center justify-end gap-1">
                            {req.status === 'Pending Review' && (
                              <button onClick={() => setEditRequest(req)}
                                className="flex items-center gap-1 px-2 py-1.5 rounded-lg text-white cursor-pointer text-xs font-medium whitespace-nowrap"
                                style={{ background: '#7c3aed' }}>
                                <i className="ri-edit-line"></i> Edit & Resubmit
                              </button>
                            )}
                            {(req.status === 'Approved' || req.status === 'HOS Approved') && (
                              <button onClick={() => downloadLeaveComputationForm(req)}
                                className="flex items-center gap-1 px-2 py-1.5 rounded-lg bg-blue-50 text-blue-600 hover:bg-blue-100 cursor-pointer text-xs font-medium whitespace-nowrap">
                                <i className="ri-file-pdf-line"></i> Computation
                              </button>
                            )}
                            {req.status === 'Approved' && (
                              <button onClick={() => setShowLetter(req)} title="Download Approval Letter"
                                className="flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs font-semibold text-white cursor-pointer whitespace-nowrap"
                                style={{ background: '#b828a0' }}>
                                <i className="ri-download-line"></i> Letter
                              </button>
                            )}
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
          <div className="px-5 py-3 bg-amber-50 border-t border-amber-100">
            <p className="text-xs text-amber-700">
              <i className="ri-lock-line mr-1"></i>
              <strong>Read-only:</strong> Submitted requests cannot be edited or deleted. Contact HR for any changes.
            </p>
          </div>
        </div>
      )}

      {activeTab === 'calendar' && (
        <div className="space-y-4">
          <div className="bg-blue-50 border border-blue-200 rounded-xl px-4 py-3 flex items-start gap-2">
            <i className="ri-information-line text-blue-600 mt-0.5"></i>
            <p className="text-xs text-blue-800">This calendar shows your approved leave dates (highlighted in green).</p>
          </div>
          <LeaveCalendarTab requests={myRequests} highlightApproved={true} singleUserView={true} />
        </div>
      )}

      {activeTab === 'policy' && <LeavePolicyTab canEdit={false} />}

      {showNew && (
        <NewLeaveRequestModal
          employeeId={empId}
          employeeName={empName || ''}
          employeeDept={empDept}
          employeePosition="HR Officer"
          employeeType={empType}
          employeeGender={empGender}
          existingRequests={requests}
          onClose={() => setShowNew(false)}
          onSubmit={handleSubmit}
        />
      )}

      {viewRequest && (
        <LeaveDetailModal
          request={viewRequest}
          isEmployee={true}
          onClose={() => setViewRequest(null)}
        />
      )}

      {showLetter && (
        <ApprovalLetterModal
          request={showLetter}
          onClose={() => setShowLetter(null)}
        />
      )}


      {editRequest && (
        <EditResubmitModal
          request={editRequest}
          allRequests={requests}
          onClose={() => setEditRequest(null)}
          onResubmit={handleResubmit}
        />
      )}
    </EmployeeLayout>
  );
}