'use client';
import { useState, useEffect, useCallback } from 'react';
import { LeaveRequest, LeaveTypeKey, LEAVE_POLICIES, calculateDays, getBalanceForType, isCurrentlyOnLeave, getMinStartDate, getAvailableLeaveTypes, computeEmployeeBalance, EMPLOYEES } from './leaveData';

interface Props {
  employeeId: string;
  employeeName: string;
  employeeDept: string;
  employeePosition: string;
  employeeType: 'Employee' | 'Intern';
  employeeGender: 'Male' | 'Female';
  existingRequests: LeaveRequest[];
  onClose: () => void;
  onSubmit: (req: LeaveRequest) => void;
}

export default function NewLeaveRequestModal({ employeeId, employeeName, employeeDept, employeePosition, employeeType, employeeGender, existingRequests, onClose, onSubmit }: Props) {
  const availableTypes = getAvailableLeaveTypes(employeeGender, employeeType === 'Intern');
  const [form, setForm] = useState({
    type: availableTypes[0] as LeaveTypeKey,
    startDate: '',
    endDate: '',
    reason: '',
    dutyDelegate: '',
    dutyDelegateOther: '',
  });
  const [days, setDays] = useState(0);
  const [errors, setErrors] = useState<string[]>([]);
  const [docFile, setDocFile] = useState<string>('');
  const [submitted, setSubmitted] = useState(false);

  const today = new Date().toISOString().split('T')[0];
  const minStartDate = getMinStartDate(form.type);
  const currentLeave = isCurrentlyOnLeave(employeeId, existingRequests);
  const availablePolicies = LEAVE_POLICIES.filter(p => availableTypes.includes(p.type));

  const myBalances = getAvailableLeaveTypes(employeeGender, employeeType === 'Intern')
    .map(type => computeEmployeeBalance(employeeId, type, employeeType === 'Intern', existingRequests));

  const balance = myBalances.find(b => b.type === form.type) || null;
  const policy = LEAVE_POLICIES.find(p => p.type === form.type);

  const hasPendingOrUnconsumedLeave = existingRequests.some(r =>
    r.employeeId === employeeId &&
    r.type === form.type &&
    (r.status === 'Pending' || r.status === 'HOD Approved' || r.status === 'HOS Approved' || (r.status === 'Approved' && r.endDate >= today))
  );

  const isDocMandatory = form.type === 'Sick' || form.type === 'Maternity';
  const showReasonField = form.type !== 'Annual';
  const showDocumentSection = form.type === 'Sick' || form.type === 'Maternity';

  // Colleagues in same department for duty delegation
  const colleagues = EMPLOYEES.filter(e => e.dept === employeeDept && e.id !== employeeId && e.employeeType === employeeType);
  const showDutyDelegation = true;

  // Auto-determine end date based on remaining days
  const computeAutoEndDate = useCallback((start: string, type: LeaveTypeKey) => {
    if (!start) return '';
    const bal = myBalances.find(b => b.type === type);
    const pol = LEAVE_POLICIES.find(p => p.type === type);
    const maxDays = Math.min(bal?.remaining || 0, pol?.entitlement || 0);
    if (maxDays <= 0) return start;
    const s = new Date(start);
    s.setDate(s.getDate() + maxDays - 1);
    return s.toISOString().split('T')[0];
  }, [myBalances]);

  useEffect(() => {
    if (form.startDate && form.endDate) {
      const d = calculateDays(form.startDate, form.endDate);
      setDays(d > 0 ? d : 0);
    } else {
      setDays(0);
    }
  }, [form.startDate, form.endDate]);

  const getDateErrors = (): string[] => {
    const errs: string[] = [];
    if (!form.startDate) return errs;
    if (form.startDate < today && form.type !== 'Sick' && form.type !== 'Bereavement') errs.push('Start date must be a future date (not today or past).');
    if (form.startDate < minStartDate && form.type !== 'Sick' && form.type !== 'Bereavement') errs.push(`Leave must be applied at least 14 days in advance. Earliest allowed start date: ${minStartDate}.`);
    if (form.endDate && form.endDate < form.startDate) errs.push('End date must be on or after the start date.');
    return errs;
  };

  const validate = (): string[] => {
    const errs: string[] = [];
    if (!form.startDate || !form.endDate) { errs.push('Please select both start and end dates.'); return errs; }
    if (form.type !== 'Sick' && form.type !== 'Bereavement' && form.startDate <= today) errs.push('Start date must be a future date (not today or past).');
    if (form.type !== 'Sick' && form.type !== 'Bereavement' && form.startDate < minStartDate) errs.push(`Leave must be applied at least 14 days in advance. Earliest allowed start date: ${minStartDate}.`);
    if (form.endDate < form.startDate) errs.push('End date must be on or after the start date. Please correct the dates.');
    if (days === 0) errs.push('The selected date range results in 0 days. Please check your dates.');
    if (currentLeave) errs.push(`You are currently on leave (${currentLeave.type}) until ${currentLeave.endDate}. You cannot request overlapping leave.`);
    if (form.type !== 'Unpaid' && policy && days > policy.entitlement) {
      errs.push(`Days requested (${days}) exceeds the annual entitlement of ${policy.entitlement} days for ${policy?.label}.`);
    }
    if (form.type !== 'Unpaid' && balance && balance.entitlement > 0 && days > balance.remaining) {
      errs.push(`Insufficient leave balance. You requested ${days} days but only have ${balance.remaining} days remaining for ${policy?.label}.`);
    }
    const overlap = existingRequests.find(r =>
      r.employeeId === employeeId && r.status === 'Approved' &&
      r.startDate <= form.endDate && r.endDate >= form.startDate
    );
    if (overlap) errs.push(`Dates overlap with an existing approved leave (${overlap.id}: ${overlap.startDate} to ${overlap.endDate}).`);
    if (showReasonField && !form.reason.trim()) errs.push('Please provide a reason for your leave request.');
    if (hasPendingOrUnconsumedLeave) errs.push(`You already have a pending or active ${form.type} leave request. You cannot apply for the same type until it is fully consumed.`);
    if (isDocMandatory && !docFile) errs.push(`Supporting document is mandatory for ${policy?.label}. Please upload a medical certificate or birth notification.`);
    if (!form.dutyDelegate) errs.push('Please select a colleague to delegate your duties to during your absence.');
    if (form.dutyDelegate === 'other' && !form.dutyDelegateOther.trim()) errs.push('Please specify who will perform your duties during your absence.');
    return errs;
  };

  const handleSubmit = () => {
    const errs = validate();
    setErrors(errs);
    if (errs.length > 0) return;

    const delegateName = form.dutyDelegate === 'other' ? form.dutyDelegateOther : form.dutyDelegate;

    const newReq: LeaveRequest = {
      id: (() => {
        const maxNum = existingRequests.reduce((max, r) => {
          const match = r.id.match(/^LV(\d+)$/);
          return match ? Math.max(max, parseInt(match[1], 10)) : max;
        }, 0);
        return `LV${String(maxNum + 1).padStart(3, '0')}`;
      })(),
      employeeId,
      employee: employeeName,
      dept: employeeDept,
      position: employeePosition,
      employeeType,
      gender: employeeGender,
      type: form.type,
      startDate: form.startDate,
      endDate: form.endDate,
      days,
      reason: form.reason,
      status: 'Pending',
      submittedOn: today,
      hasDocument: !!docFile,
      dutyDelegate: delegateName,
    };
    onSubmit(newReq);
    setSubmitted(true);
  };

  const dateErrors = getDateErrors();

  const maxDaysAllowed = Math.min(
    balance && balance.entitlement > 0 ? balance.remaining : (policy?.entitlement || 0),
    policy?.entitlement || 0
  ) || (policy?.entitlement || 0);
  const maxEndDate = (() => {
    const baseDate = form.startDate || minStartDate;
    if (!baseDate || maxDaysAllowed <= 0) return '';
    const s = new Date(baseDate);
    s.setDate(s.getDate() + maxDaysAllowed - 1);
    return s.toISOString().split('T')[0];
  })();

  const canSubmit = form.startDate && form.endDate && (!showReasonField || form.reason.trim()) && days > 0 && days <= maxDaysAllowed && !currentLeave && dateErrors.length === 0 && !hasPendingOrUnconsumedLeave && (!showDocumentSection || !isDocMandatory || !!docFile) && !!form.dutyDelegate && (form.dutyDelegate !== 'other' || !!form.dutyDelegateOther.trim());

  if (submitted) {
    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-md p-8 text-center">
          <div className="w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mx-auto mb-4">
            <i className="ri-checkbox-circle-line text-green-600 text-3xl"></i>
          </div>
          <h3 className="font-bold text-gray-800 text-xl mb-2">Request Submitted!</h3>
          <p className="text-sm text-gray-500 mb-4">Your leave request has been submitted and is pending HOD then HR approval.</p>
          <div className="bg-blue-50 rounded-xl px-4 py-3 text-left mb-5 space-y-2">
            <p className="text-xs font-semibold text-blue-700">Email Notifications Sent:</p>
            <div className="flex items-center gap-2 text-xs text-blue-600">
              <i className="ri-mail-send-line"></i>
              <span>HR notified at <strong>hr@uwezo.go.ke</strong></span>
            </div>
            <div className="flex items-center gap-2 text-xs text-blue-600">
              <i className="ri-mail-line"></i>
              <span>Confirmation sent to <strong>your email</strong></span>
            </div>
          </div>
          <div className="bg-gray-50 rounded-xl px-4 py-3 text-left mb-5">
            <p className="text-xs font-semibold text-gray-600 mb-2">Approval Workflow:</p>
            <div className="flex items-center gap-2 text-xs text-gray-600">
              <div className="w-5 h-5 rounded-full bg-amber-100 text-amber-700 flex items-center justify-center font-bold text-xs">1</div>
              <span>HOD reviews and approves</span>
            </div>
            <div className="flex items-center gap-2 text-xs text-gray-600 mt-1">
              <div className="w-5 h-5 rounded-full bg-green-100 text-green-700 flex items-center justify-center font-bold text-xs">2</div>
              <span>HR gives final approval</span>
            </div>
            <div className="flex items-center gap-2 text-xs text-gray-600 mt-1">
              <div className="w-5 h-5 rounded-full flex items-center justify-center font-bold text-xs" style={{ background: '#fdf4ff', color: '#b828a0' }}>3</div>
              <span>You receive email notification + download approval letter</span>
            </div>
          </div>
          <button onClick={onClose}
            className="w-full py-2.5 rounded-xl text-white text-sm font-semibold cursor-pointer whitespace-nowrap"
            style={{ background: '#b828a0' }}>
            Close
          </button>
        </div>
      </div>
    );
  }

  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 max-h-[90vh] overflow-y-auto">
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-100">
          <div>
            <h3 className="font-bold text-gray-800 text-lg">New Leave Request</h3>
            <p className="text-xs text-gray-400 mt-0.5">Submit a leave request for HOD then HR approval</p>
          </div>
          <button onClick={onClose} className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 cursor-pointer">
            <i className="ri-close-line text-gray-500"></i>
          </button>
        </div>

        <div className="p-6 space-y-4">
          {currentLeave && (
            <div className="flex items-start gap-2 bg-red-50 border border-red-200 rounded-xl px-4 py-3">
              <i className="ri-alarm-warning-line text-red-600 mt-0.5 flex-shrink-0"></i>
              <p className="text-xs text-red-800">
                <strong>Cannot submit:</strong> You are currently on leave ({currentLeave.type}) until {currentLeave.endDate}. You cannot request overlapping leave.
              </p>
            </div>
          )}

          {hasPendingOrUnconsumedLeave && (
            <div className="flex items-start gap-2 bg-red-50 border border-red-200 rounded-xl px-4 py-3">
              <i className="ri-alarm-warning-line text-red-600 mt-0.5 flex-shrink-0"></i>
              <p className="text-xs text-red-800">
                <strong>Cannot submit:</strong> You already have a pending or active {form.type} leave request. You must wait until it is fully consumed before applying again.
              </p>
            </div>
          )}

          <div className="bg-amber-50 border border-amber-200 rounded-xl px-4 py-3 flex items-start gap-2">
            <i className="ri-information-line text-amber-600 mt-0.5 flex-shrink-0"></i>
            <div className="text-xs text-amber-800 space-y-1">
              <p><strong>Rules:</strong></p>
              <p>• Start date must be at least 14 days from today (earliest: <strong>{minStartDate}</strong>)</p>
              <p>• End date is auto-determined by your remaining days for this leave type</p>
              <p>• Days requested cannot exceed your remaining balance (<strong>{balance?.remaining ?? 0} days</strong>) or annual entitlement (<strong>{policy?.entitlement ?? 0} days</strong>)</p>
              <p>• You cannot apply the same leave type twice until consumed</p>
              <p>• <strong>Sick Leave and Maternity Leave require supporting documents</strong></p>
            </div>
          </div>

          {errors.length > 0 && (
            <div className="bg-red-50 border border-red-200 rounded-xl px-4 py-3 space-y-1">
              {errors.map((e, i) => (
                <div key={i} className="flex items-start gap-2">
                  <i className="ri-error-warning-line text-red-500 mt-0.5 flex-shrink-0"></i>
                  <p className="text-xs text-red-700">{e}</p>
                </div>
              ))}
            </div>
          )}

          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">Leave Type *</label>
            <div className="grid grid-cols-2 gap-2">
              {availablePolicies.map(p => (
                <button key={p.type} type="button" onClick={() => {
                  setForm(f => {
                    const newType = p.type as LeaveTypeKey;
                    const autoEnd = f.startDate ? computeAutoEndDate(f.startDate, newType) : '';
                    return { ...f, type: newType, endDate: autoEnd };
                  });
                  setErrors([]);
                }}
                  className="flex items-center gap-2 px-3 py-2.5 rounded-xl text-sm font-medium border cursor-pointer transition-all"
                  style={form.type === p.type ? { background: p.color + '15', borderColor: p.color, color: p.color } : { background: '#fff', borderColor: '#e5e7eb', color: '#4b5563' }}>
                  <i className={`${p.icon} text-base`}></i>
                  <span className="text-xs">{p.label}</span>
                </button>
              ))}
            </div>
          </div>

          {balance && form.type !== 'Unpaid' && (
            <div className="flex items-center gap-3 p-3 rounded-xl" style={{ background: '#fdf4ff' }}>
              <div className="w-8 h-8 flex items-center justify-center rounded-lg" style={{ background: '#b828a0' }}>
                <i className="ri-wallet-3-line text-white text-sm"></i>
              </div>
              <div className="flex-1">
                <p className="text-xs text-gray-500">Available Balance ({policy?.label})</p>
                <p className="font-bold text-gray-800">{balance.remaining} days remaining</p>
                <p className="text-xs text-gray-400">Entitlement: {balance.entitlement} days | Taken: {balance.taken} days</p>
              </div>
              {days > 0 && (
                <div className="text-right">
                  <p className="text-xs text-gray-500">After request</p>
                  <p className={`font-bold text-sm ${balance.remaining - days < 0 ? 'text-red-600' : 'text-green-600'}`}>
                    {balance.remaining - days} days
                  </p>
                </div>
              )}
            </div>
          )}

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-1.5">Start Date *</label>
              <input type="date" value={form.startDate}
                min={minStartDate}
                onChange={e => {
                  const val = e.target.value;
                  const autoEnd = computeAutoEndDate(val, form.type);
                  setForm(f => ({ ...f, startDate: val, endDate: autoEnd }));
                  setErrors([]);
                }}
                className={`w-full border rounded-lg px-3 py-2.5 text-sm outline-none ${form.startDate && form.type !== 'Sick' && form.type !== 'Bereavement' && form.startDate < minStartDate ? 'border-red-300 bg-red-50' : 'border-gray-200'}`} />
              {form.startDate && form.type !== 'Sick' && form.type !== 'Bereavement' && form.startDate < minStartDate && (
                <p className="text-xs text-red-600 mt-1">Must be at least 14 days from today</p>
              )}
              {form.startDate && form.type !== 'Sick' && form.type !== 'Bereavement' && form.startDate <= today && (
                <p className="text-xs text-red-600 mt-1">Cannot be today or a past date</p>
              )}
            </div>
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-1.5">End Date *</label>
              <input type="date" value={form.endDate}
                min={form.startDate || minStartDate}
                max={maxEndDate}
                onChange={e => { setForm(f => ({ ...f, endDate: e.target.value })); setErrors([]); }}
                className={`w-full border rounded-lg px-3 py-2.5 text-sm outline-none ${form.endDate && form.startDate && (form.endDate < form.startDate || (maxEndDate && form.endDate > maxEndDate)) ? 'border-red-300 bg-red-50' : 'border-gray-200'}`} />
              {form.endDate && form.startDate && form.endDate < form.startDate && (
                <p className="text-xs text-red-600 mt-1">End date cannot be before start date</p>
              )}
              {form.endDate && maxEndDate && form.endDate > maxEndDate && (
                <p className="text-xs text-red-600 mt-1">End date exceeds maximum allowed ({maxDaysAllowed} days). Max end: {maxEndDate}</p>
              )}
              {form.startDate && form.endDate && (
                <p className="text-xs text-green-600 mt-1">Auto: {maxDaysAllowed} days max (remaining balance)</p>
              )}
              {!form.startDate && !form.endDate && (
                <p className="text-xs text-gray-400 mt-1">Max {maxDaysAllowed} days available. Select start date to auto-compute.</p>
              )}
            </div>
          </div>

          {days > 0 && form.endDate >= form.startDate && (
            <div className="flex items-center gap-2 bg-blue-50 text-blue-700 text-sm px-4 py-2.5 rounded-lg">
              <i className="ri-calendar-check-line"></i>
              <span>{days} calendar day{days !== 1 ? 's' : ''} ({form.startDate} to {form.endDate} inclusive)</span>
            </div>
          )}

          {showReasonField && (
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-1.5">Reason *</label>
              <textarea
                value={form.reason}
                onChange={e => { const v = e.target.value; setForm(f => ({ ...f, reason: v })); }}
                readOnly={false}
                rows={3} maxLength={500} placeholder="Briefly describe the reason for your leave..."
                className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm outline-none resize-none" />
              <p className="text-xs text-gray-400 mt-1">{form.reason.length}/500 characters</p>
            </div>
          )}

          {showDocumentSection && (
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-1.5">
                Supporting Document {isDocMandatory ? <span className="text-red-500">*</span> : ''}
                {isDocMandatory && <span className="text-xs font-normal text-gray-400 ml-1">— Required for {policy?.label}</span>}
              </label>
              <label className={`border-2 border-dashed rounded-xl p-4 text-center hover:border-purple-300 transition-colors cursor-pointer block ${isDocMandatory && !docFile ? 'border-red-200 bg-red-50' : 'border-gray-200'}`}>
                <div className="w-8 h-8 flex items-center justify-center mx-auto mb-1">
                  <i className="ri-upload-cloud-2-line text-2xl text-gray-400"></i>
                </div>
                <p className="text-xs text-gray-500">PDF, JPG, PNG up to 10MB</p>
                <input type="file" accept=".pdf,.jpg,.png" className="hidden" onChange={e => setDocFile(e.target.files?.[0]?.name || '')} />
              </label>
              {docFile && <p className="text-xs text-green-600 mt-1"><i className="ri-check-line mr-1"></i>{docFile}</p>}
              {isDocMandatory && !docFile && <p className="text-xs text-red-500 mt-1"><i className="ri-error-warning-line mr-1"></i>Please upload supporting document</p>}
            </div>
          )}

          {showDutyDelegation && (
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-1.5">Duty Delegation During Absence *</label>
              <p className="text-xs text-gray-500 mb-2">Select a colleague from your department to be responsible for your duties during your absence</p>
              <div className="space-y-2">
                {colleagues.map(c => (
                  <button
                    key={c.id}
                    onClick={() => setForm(f => ({ ...f, dutyDelegate: c.name, dutyDelegateOther: '' }))}
                    className="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl border text-sm cursor-pointer transition-all"
                    style={form.dutyDelegate === c.name ? { background: '#fdf4ff', borderColor: '#b828a0', color: '#b828a0' } : { background: '#fff', borderColor: '#e5e7eb', color: '#4b5563' }}
                  >
                    <div className="w-7 h-7 rounded-full flex items-center justify-center text-white text-xs font-bold" style={{ background: '#b828a0' }}>
                      {c.name.split(' ').map(n => n[0]).join('').slice(0, 2)}
                    </div>
                    <div className="text-left">
                      <p className="font-medium">{c.name}</p>
                      <p className="text-xs text-gray-400">{c.position}</p>
                    </div>
                    {form.dutyDelegate === c.name && <i className="ri-check-line ml-auto"></i>}
                  </button>
                ))}
                <button
                  onClick={() => setForm(f => ({ ...f, dutyDelegate: 'other' }))}
                  className="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl border text-sm cursor-pointer transition-all"
                  style={form.dutyDelegate === 'other' ? { background: '#fdf4ff', borderColor: '#b828a0', color: '#b828a0' } : { background: '#fff', borderColor: '#e5e7eb', color: '#4b5563' }}
                >
                  <div className="w-7 h-7 rounded-full flex items-center justify-center text-white text-xs font-bold bg-gray-400">
                    <i className="ri-add-line"></i>
                  </div>
                  <span className="font-medium">Other (specify)</span>
                  {form.dutyDelegate === 'other' && <i className="ri-check-line ml-auto"></i>}
                </button>
              </div>
              {form.dutyDelegate === 'other' && (
                <div className="mt-2">
                  <input
                    type="text"
                    value={form.dutyDelegateOther}
                    onChange={e => setForm(f => ({ ...f, dutyDelegateOther: e.target.value }))}
                    placeholder="Enter name of person who will perform your duties..."
                    className="w-full border border-gray-200 rounded-lg px-3 py-2.5 text-sm outline-none"
                  />
                </div>
              )}
            </div>
          )}

          <div className="bg-gray-50 rounded-xl p-3">
            <p className="text-xs font-semibold text-gray-600 mb-2">Approval Workflow:</p>
            <div className="flex items-center gap-2 flex-wrap">
              <div className="flex items-center gap-1.5">
                <div className="w-6 h-6 rounded-full flex items-center justify-center text-white text-xs" style={{ background: '#b828a0' }}>1</div>
                <span className="text-xs text-gray-600">You submit</span>
              </div>
              <i className="ri-arrow-right-line text-gray-300 text-xs"></i>
              <div className="flex items-center gap-1.5">
                <div className="w-6 h-6 rounded-full bg-amber-100 flex items-center justify-center text-amber-700 text-xs">2</div>
                <span className="text-xs text-gray-600">HOD approves</span>
              </div>
              {employeeType !== 'Intern' && (
                <>
                  <i className="ri-arrow-right-line text-gray-300 text-xs"></i>
                  <div className="flex items-center gap-1.5">
                    <div className="w-6 h-6 rounded-full bg-blue-100 flex items-center justify-center text-blue-600 text-xs">3</div>
                    <span className="text-xs text-gray-600">HOS confirms</span>
                  </div>
                </>
              )}
              <i className="ri-arrow-right-line text-gray-300 text-xs"></i>
              <div className="flex items-center gap-1.5">
                <div className="w-6 h-6 rounded-full bg-green-100 flex items-center justify-center text-green-600 text-xs">{employeeType === 'Intern' ? '3' : '4'}</div>
                <span className="text-xs text-gray-600">HR final approval</span>
              </div>
              <i className="ri-arrow-right-line text-gray-300 text-xs"></i>
              <div className="flex items-center gap-1.5">
                <div className="w-6 h-6 rounded-full bg-purple-100 flex items-center justify-center text-purple-600 text-xs">{employeeType === 'Intern' ? '4' : '5'}</div>
                <span className="text-xs text-gray-600">Notified + download</span>
              </div>
            </div>
            <p className="text-xs text-gray-400 mt-1">{employeeType === 'Intern' ? 'Intern workflow: HOD → HR' : 'Employee workflow: HOD → HOS → HR'}</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 font-medium text-gray-600 hover:bg-gray-50 cursor-pointer whitespace-nowrap">
            Cancel
          </button>
          <button onClick={handleSubmit} disabled={!canSubmit}
            className="px-6 py-2.5 text-white rounded-xl text-sm font-semibold cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed whitespace-nowrap"
            style={{ background: '#b828a0' }}>
            Submit Request
          </button>
        </div>
      </div>
    </div>
  );
}