'use client';
import { LeaveRequest, LEAVE_POLICIES } from './leaveData';
import { downloadLeaveApplicationFormPart1, downloadLeaveApplicationFormPart2, downloadFullApplicationForm } from '../../../lib/leaveApplicationForm';

interface Props {
  request: LeaveRequest;
  onClose: () => void;
  allRequests?: LeaveRequest[];
  hodName?: string;
  hosName?: string;
  stage?: 'part1' | 'part2' | 'full';
}

const EMPLOYEE_ADDRESSES: Record<string, string> = {
  'E001': 'P.O. Box 899, MACHAKOS',
  'E002': 'P.O. Box 10234, NAIROBI',
  'E003': 'P.O. Box 5500, KISUMU',
  'E004': 'P.O. Box 3400, NAKURU',
  'E005': 'P.O. Box 899, MACHAKOS',
  'E006': 'P.O. Box 1500, EMBU',
  'E007': 'P.O. Box 7800, MOMBASA',
  'E008': 'P.O. Box 2300, KERICHO',
  'E009': 'P.O. Box 10234, NAIROBI',
  'E010': 'P.O. Box 5500, KISUMU',
  'I001': 'P.O. Box 1200, KIAMBU',
  'I002': 'P.O. Box 899, MACHAKOS',
  'I003': 'P.O. Box 7800, MOMBASA',
  'I004': 'P.O. Box 3400, NAKURU',
  'I005': 'P.O. Box 10234, NAIROBI',
  'UF001': 'P.O. Box 899, MACHAKOS',
  'UF002': 'P.O. Box 10234, NAIROBI',
  'UF003': 'P.O. Box 5500, KISUMU',
  'UF004': 'P.O. Box 3400, NAKURU',
  'UF005': 'P.O. Box 899, MACHAKOS',
  'UF006': 'P.O. Box 1200, KIAMBU',
  'UF007': 'P.O. Box 10234, NAIROBI',
};

const HOD_ADDRESSES: Record<string, string> = {
  'Evans Oyaro': 'P.O. Box 2100, KAREN, NAIROBI',
  'Margaret Muriithi': 'P.O. Box 10234, NAIROBI',
  'Margaret Murithi': 'P.O. Box 10234, NAIROBI',
  'Laban Mwangi': 'P.O. Box 5500, KISUMU',
  'Benadette Owade': 'P.O. Box 3400, NAKURU',
  'Gedion Njoroge': 'P.O. Box 2100, KAREN, NAIROBI',
  'Susan Kariuki': 'P.O. Box 2100, KAREN, NAIROBI',
  'David Njoroge': 'P.O. Box 10234, NAIROBI',
  'James Omondi': 'P.O. Box 5500, KISUMU',
  'Mary Ndungu': 'P.O. Box 3400, NAKURU',
};

function getAddress(request: LeaveRequest): string {
  if (HOD_ADDRESSES[request.employee]) return HOD_ADDRESSES[request.employee];
  return EMPLOYEE_ADDRESSES[request.employeeId] || EMPLOYEE_ADDRESSES[request.employee] || 'P.O. Box 00100, NAIROBI';
}

function getPreviousLeave(request: LeaveRequest, allRequests: LeaveRequest[] = []): { start: string; end: string } | null {
  const prev = allRequests.filter(r =>
    r.employeeId === request.employeeId &&
    r.id !== request.id &&
    r.status === 'Approved' &&
    r.endDate < request.startDate
  ).sort((a, b) => b.endDate.localeCompare(a.endDate))[0];
  if (!prev) return null;
  return { start: prev.startDate, end: prev.endDate };
}

export default function LeaveApplicationViewModal({ request, onClose, allRequests = [], hodName, hosName, stage = 'part1' }: Props) {
  const policy = LEAVE_POLICIES.find(p => p.type === request.type);
  const prev = getPreviousLeave(request, allRequests);
  const prevStart = prev ? prev.start : 'Nil';
  const prevEnd = prev ? prev.end : 'Nil';
  const address = getAddress(request);
  const today = new Date().toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' });

  const showPartI = stage === 'part1' || stage === 'part2' || stage === 'full';
  const showPartII = stage === 'part2' || stage === 'full';
  const showPartIII = stage === 'full';

  const handleDownload = () => {
    if (stage === 'full') {
      downloadFullApplicationForm(request, allRequests, hodName, hosName);
    } else if (stage === 'part2') {
      downloadLeaveApplicationFormPart2(request, allRequests, hodName, 'hod');
    } else {
      downloadLeaveApplicationFormPart1(request, allRequests);
    }
  };

  return (
    <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-3xl max-h-[90vh] overflow-y-auto" style={{ fontFamily: '"Times New Roman", Georgia, serif', fontSize: '12pt' }}>
        <div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between" style={{ background: '#b828a0' }}>
          <div>
            <h3 className="font-bold text-white">Leave Application Form</h3>
            <p className="text-pink-200 text-xs">{request.id} — {policy?.label || request.type}</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-6">
          {/* Header */}
          <div className="text-center border-b border-gray-200 pb-4">
            <p className="text-lg font-bold text-gray-900 tracking-wider">UWEZO FUND OVERSIGHT BOARD</p>
            <p className="text-sm text-gray-600">SECRETARIAT</p>
            <p className="text-xs text-gray-500 mt-1">Lenrho House, 16th Floor, Standard Street, Nairobi | P.O. Box 42009-00100, NAIROBI</p>
            <p className="text-xs text-gray-500">Website: https://www.uwezo.go.ke | E-MAIL: info@uwezo.go.ke</p>
          </div>

          <div className="text-center">
            <p className="text-sm font-bold text-gray-800 uppercase tracking-wide">Application for {(policy?.label || request.type).toUpperCase()}</p>
            <p className="text-xs text-gray-500">(To be submitted at least 14 days before the leave is due)</p>
          </div>

          {showPartI && (
            <div className="border border-gray-200 rounded-xl p-4">
              <p className="text-xs font-bold text-gray-700 underline mb-3">PART I</p>

              <div className="space-y-2 text-sm text-gray-800">
                <p>1. I wish to apply for <span className="font-bold border-b border-gray-800 px-1">{request.days}</span> days {(policy?.label || request.type).toLowerCase()} beginning on <span className="font-bold border-b border-gray-800 px-1">{request.startDate}</span></p>
                <p>The last leave was taken by me was from <span className="font-bold border-b border-gray-800 px-1">{prevStart}</span> to <span className="font-bold border-b border-gray-800 px-1">{prevEnd}</span></p>
              </div>

              <div className="mt-3 text-sm text-gray-800">
                <p>2. My leave address will be <span className="font-bold border-b border-gray-800 px-1">{address}</span></p>
              </div>

              <div className="mt-3 text-sm text-gray-800 space-y-1">
                <p>3. During the period of leave my salary should:</p>
                <p className="ml-4">(a) continue to be paid into my bank account <span className="font-bold border-b border-gray-800 px-1">Nil</span></p>
                <p className="ml-4">(b) be paid at the following address: <span className="font-bold border-b border-gray-800 px-1">Nil</span></p>
              </div>

              <div className="mt-3 text-sm text-gray-800 space-y-2">
                <p>4. As I am taking not less than one-half of my annual leave due to me, I wish to receive/do not wish to receive my pay for the month of three days before the date of commencement of leave in terms of Regulations H (12) of the Code of Regulations.</p>
                <p>5. I understand that I will require permission from the Chief Executive Officer should I desire to spend leave outside Kenya in accordance with Civil Service Regulations.</p>
              </div>

              <div className="mt-4 text-sm text-gray-800 space-y-1">
                <p>Date <span className="font-bold border-b border-gray-800 px-1">{request.submittedOn || today}</span></p>
                <p className="mt-2">Signature of Applicant <span className="inline-block border-b border-gray-800 w-40">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span></p>
              </div>
            </div>
          )}

          {showPartII && (
            <div className="border border-gray-200 rounded-xl p-4">
              <p className="text-xs font-bold text-gray-700 underline mb-1">PART II</p>
              <p className="text-xs text-gray-500 italic mb-3">(To be Completed by Head of Department)</p>

              <div className="text-sm text-gray-800 space-y-2">
                <p>6. (a) Recommended. Arrangements will be made for the performance of the duties of the officer during his/her absence. <span className="inline-block w-3 h-3 border border-gray-800 bg-gray-800 align-middle"></span></p>
                <p className="ml-4">(b) Not Recommended for the following reasons: <span className="font-bold border-b border-gray-800 px-1">Nil</span></p>
              </div>

              <div className="mt-4 text-sm text-gray-800 space-y-1">
                <p>Date <span className="font-bold border-b border-gray-800 px-1">{request.hodApprovedOn || 'Nil'}</span></p>
                <p className="mt-1">Signed <span className="inline-block border-b border-gray-800 w-32">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span></p>
                <p className="mt-1">Division/Section/Unit <span className="font-bold border-b border-gray-800 px-1">{request.dept}</span></p>
                <p className="mt-1">Designation <span className="font-bold border-b border-gray-800 px-1">Head of {request.dept}</span></p>
                <p className="mt-1">Name <span className="font-bold border-b border-gray-800 px-1">{hodName || 'Nil'}</span></p>
              </div>
            </div>
          )}

          {showPartIII && (
            <div className="border border-gray-200 rounded-xl p-4">
              <p className="text-xs font-bold text-gray-700 underline mb-1">PART III</p>
              <p className="text-xs text-gray-500 italic mb-3">(To be Completed by the Head of Secretariat where applicable)</p>

              <div className="text-sm text-gray-800 space-y-2">
                <p>7. Leave allowance will be paid in accordance with prevailing regulations.</p>
                <p>This application is approved: <span className="inline-block w-3 h-3 border border-gray-800 bg-gray-800 align-middle"></span></p>
              </div>

              <div className="mt-4 text-sm text-gray-800 space-y-1">
                <p>Date <span className="font-bold border-b border-gray-800 px-1">{request.hosApprovedOn || 'Nil'}</span></p>
                <p className="mt-1">Signed <span className="inline-block border-b border-gray-800 w-32">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span></p>
                <p className="mt-1">Head of Secretariat <span className="font-bold border-b border-gray-800 px-1">{hosName || 'Nil'}</span></p>
              </div>
            </div>
          )}

          {/* Footer */}
          <div className="rounded-lg px-4 py-3 text-center text-white text-xs font-bold" style={{ background: '#b22698' }}>
            <span className="mx-2">10th Anniversary</span>
            <span className="mx-2">AHADI YETU KAZI KWAKO</span>
            <span className="mx-2">Kenya Vision 2030</span>
          </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 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 text-white rounded-xl text-sm font-semibold cursor-pointer whitespace-nowrap"
            style={{ background: '#b22698' }}>
            <i className="ri-download-line"></i> Download PDF
          </button>
        </div>
      </div>
    </div>
  );
}