import { LeaveRequest, LEAVE_POLICIES } from '../app/hr/leave/leaveData';
import { triggerFileDownload } from './autoDownloadPdf';

const UWEZO_LOGO = 'https://storage.readdy-site.link/project_files/8353c6c3-4df0-48e3-b13e-2f6c24e6f89d/6d094512-dcbf-4464-ad6a-2cd0e9a78386_uwezo-fund-logo.png?v=507c066dfae2633b1a8385356d2c557b';

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',
};

const HOD_ADDRESSES: Record<string, string> = {
  '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 };
}

const COMMON_STYLE = '.page{max-width:700px;margin:0 auto;padding:15px;border:1px solid #ccc;}' +
  '.logo-row{display:flex;justify-content:center;margin-bottom:8px;}' +
  '.logo-img{height:65px;width:auto;object-fit:contain;}' +
  '.org-name{text-align:center;font-size:12pt;font-weight:bold;color:#111;letter-spacing:2px;margin-bottom:1px;}' +
  '.org-sub{text-align:center;font-size:8pt;color:#555;margin-bottom:1px;}' +
  '.org-addr{text-align:center;font-size:7.5pt;color:#666;line-height:1.5;margin-bottom:6px;}' +
  '.thick-line{border:none;border-top:2px solid #111;margin:6px 0;}' +
  '.form-title{text-align:center;font-size:10pt;font-weight:bold;color:#111;text-transform:uppercase;margin:8px 0 4px;letter-spacing:1px;}' +
  '.part-label{font-size:9pt;font-weight:bold;margin:6px 0 2px;text-decoration:underline;}' +
  '.part-sub{font-size:8pt;color:#555;margin-bottom:6px;font-style:italic;}' +
  '.field-row{font-size:9pt;color:#333;margin-bottom:3px;line-height:1.6;}' +
  '.field-row .fill{border-bottom:1px solid #333;display:inline-block;min-width:80px;padding:0 4px;font-weight:bold;color:#000;}' +
  '.footer-bar{background:#b22698;color:#fff;text-align:center;padding:8px 12px;font-size:8pt;font-weight:bold;margin-top:15px;}' +
  '.footer-bar span{margin:0 8px;}' +
  '.sig-block{margin-top:15px;font-size:9pt;}' +
  '.sig-block .line{border-bottom:1px solid #333;display:inline-block;min-width:120px;}' +
  '.check-box{display:inline-block;width:12px;height:12px;border:1px solid #333;margin-right:4px;vertical-align:middle;}' +
  '.checked-box{display:inline-block;width:12px;height:12px;border:1px solid #333;background:#333;margin-right:4px;vertical-align:middle;}';

function buildFormHtml(content: string): string {
  return '<!DOCTYPE html><html><head><meta charset="utf-8"><style>' + COMMON_STYLE + '</style></head><body>' + content + '</body></html>';
}

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

  let html = '<div class="page">';

  html += '<div class="logo-row"><img src="' + UWEZO_LOGO + '" class="logo-img" alt="Uwezo Fund" /></div>';
  html += '<div class="org-name">UWEZO FUND OVERSIGHT BOARD</div>';
  html += '<div class="org-sub">SECRETARIAT</div>';
  html += '<div class="org-addr">Lenrho House, 16<sup>th</sup> Floor, Standard Street, Nairobi &nbsp;|&nbsp; P.O. Box 42009-00100, NAIROBI<br>Website: https://www.uwezo.go.ke &nbsp;|&nbsp; E-MAIL: info@uwezo.go.ke</div>';
  html += '<hr class="thick-line">';

  html += '<div class="form-title">APPLICATION FOR ' + (policy?.label || request.type).toUpperCase() + '</div>';
  html += '<div style="text-align:center;font-size:8pt;color:#555;margin-bottom:8px;">(To be submitted at least 14 days before the leave is due)</div>';

  html += '<div class="part-label">PART I</div>';
  html += '<div class="field-row">1. I wish to apply for <span class="fill">' + request.days + '</span> days ' + (policy?.label || request.type).toLowerCase() + ' beginning on <span class="fill">' + request.startDate + '</span></div>';
  html += '<div class="field-row">The last leave was taken by me was from <span class="fill">' + prevStart + '</span> to <span class="fill">' + prevEnd + '</span></div>';

  html += '<div class="field-row" style="margin-top:8px;">2. My leave address will be <span class="fill" style="min-width:300px;">' + address + '</span></div>';

  html += '<div class="field-row" style="margin-top:8px;">3. During the period of leave my salary should:</div>';
  html += '<div class="field-row">&nbsp;&nbsp;&nbsp;(a) continue to be paid into my bank account <span class="fill" style="min-width:200px;">Nil</span></div>';
  html += '<div class="field-row">&nbsp;&nbsp;&nbsp;(b) be paid at the following address: <span class="fill" style="min-width:250px;">Nil</span></div>';

  html += '<div style="margin-top:10px;font-size:9pt;">' +
    '<p class="field-row">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 class="field-row" style="margin-top:5px;">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>';

  html += '<div class="sig-block">' +
    '<p class="field-row">Date <span class="fill" style="min-width:120px;">' + today + '</span></p>' +
    '<p class="field-row" style="margin-top:6px;">Signature of Applicant <span class="line" style="min-width:150px;">&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>';

  html += '<div class="footer-bar">' +
    '<span>10th Anniversary</span>' +
    '<span>AHADI YETU KAZI KWAKO</span>' +
    '<span>Kenya Vision 2030</span>' +
    '</div>';

  html += '</div>';

  triggerFileDownload(buildFormHtml(html), 'Leave_Application_Part_I_' + request.id + '.pdf');
}

export function downloadLeaveApplicationFormPart2(request: LeaveRequest, allRequests: LeaveRequest[] = [], hodName?: string, hosName?: string, stage: 'hod' | 'hos' = 'hod'): void {
  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);

  let html = '<div class="page">';

  html += '<div class="logo-row"><img src="' + UWEZO_LOGO + '" class="logo-img" alt="Uwezo Fund" /></div>';
  html += '<div class="org-name">UWEZO FUND OVERSIGHT BOARD</div>';
  html += '<div class="org-sub">SECRETARIAT</div>';
  html += '<div class="org-addr">Lenrho House, 16<sup>th</sup> Floor, Standard Street, Nairobi &nbsp;|&nbsp; P.O. Box 42009-00100, NAIROBI<br>Website: https://www.uwezo.go.ke &nbsp;|&nbsp; E-MAIL: info@uwezo.go.ke</div>';
  html += '<hr class="thick-line">';

  html += '<div class="form-title">APPLICATION FOR ' + (policy?.label || request.type).toUpperCase() + '</div>';
  html += '<div style="text-align:center;font-size:8pt;color:#555;margin-bottom:8px;">(To be submitted at least 14 days before the leave is due)</div>';

  html += '<div class="part-label">PART I</div>';
  html += '<div class="field-row">1. I wish to apply for <span class="fill">' + request.days + '</span> days ' + (policy?.label || request.type).toLowerCase() + ' beginning on <span class="fill">' + request.startDate + '</span></div>';
  html += '<div class="field-row">The last leave was taken by me was from <span class="fill">' + prevStart + '</span> to <span class="fill">' + prevEnd + '</span></div>';

  html += '<div class="field-row" style="margin-top:8px;">2. My leave address will be <span class="fill" style="min-width:300px;">' + address + '</span></div>';

  html += '<div class="field-row" style="margin-top:8px;">3. During the period of leave my salary should:</div>';
  html += '<div class="field-row">&nbsp;&nbsp;&nbsp;(a) continue to be paid into my bank account <span class="fill" style="min-width:200px;">Nil</span></div>';
  html += '<div class="field-row">&nbsp;&nbsp;&nbsp;(b) be paid at the following address: <span class="fill" style="min-width:250px;">Nil</span></div>';

  html += '<div style="margin-top:10px;font-size:9pt;">' +
    '<p class="field-row">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 class="field-row" style="margin-top:5px;">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>';

  html += '<div class="sig-block">' +
    '<p class="field-row">Date <span class="fill" style="min-width:120px;">' + request.submittedOn + '</span></p>' +
    '<p class="field-row" style="margin-top:6px;">Signature of Applicant <span class="line" style="min-width:150px;">&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>';

  html += '<div class="part-label" style="margin-top:20px;">PART II</div>';
  html += '<div class="part-sub">(To be Completed by Head of Department)</div>';

  html += '<div class="field-row" style="margin-top:8px;">6. (a) Recommended. Arrangements will be made for the performance of the duties of the officer during his/her absence. <span class="checked-box"></span></div>';
  html += '<div class="field-row">&nbsp;&nbsp;&nbsp;&nbsp;(b) Not Recommended for the following reasons: <span class="fill" style="min-width:300px;">Nil</span></div>';

  html += '<div class="sig-block">' +
    '<p class="field-row">Date <span class="fill" style="min-width:120px;">' + (request.hodApprovedOn || 'Nil') + '</span></p>' +
    '<p class="field-row" style="margin-top:4px;">Signed <span class="line" style="min-width:150px;">&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 class="field-row" style="margin-top:4px;">Division/Section/Unit <span class="fill" style="min-width:150px;">' + request.dept + '</span></p>' +
    '<p class="field-row" style="margin-top:4px;">Designation <span class="fill" style="min-width:120px;">Head of ' + request.dept + '</span></p>' +
    '<p class="field-row" style="margin-top:4px;">Name <span class="fill" style="min-width:200px;">' + (hodName || 'Nil') + '</span></p>' +
    '</div>';

  if (stage === 'hos') {
    html += '<div class="part-label" style="margin-top:20px;">PART III</div>';
    html += '<div class="part-sub">(To be Completed by the Head of Secretariat where applicable)</div>';

    html += '<div class="field-row" style="margin-top:8px;">7. Leave allowance will be paid in accordance with prevailing regulations.</div>';
    html += '<div class="field-row">This application is approved: <span class="checked-box"></span></div>';

    html += '<div class="sig-block">' +
      '<p class="field-row">Date <span class="fill" style="min-width:120px;">' + (request.hosApprovedOn || 'Nil') + '</span></p>' +
      '<p class="field-row" style="margin-top:4px;">Signed <span class="line" style="min-width:150px;">&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 class="field-row" style="margin-top:4px;">Head of Secretariat <span class="fill" style="min-width:200px;">' + (hosName || 'Nil') + '</span></p>' +
      '</div>';
  }

  html += '<div class="footer-bar">' +
    '<span>10th Anniversary</span>' +
    '<span>AHADI YETU KAZI KWAKO</span>' +
    '<span>Kenya Vision 2030</span>' +
    '</div>';

  html += '</div>';

  const filename = stage === 'hos' ? 'Leave_Application_Part_III_' + request.id + '.pdf' : 'Leave_Application_Part_II_' + request.id + '.pdf';
  triggerFileDownload(buildFormHtml(html), filename);
}

export function downloadFullApplicationForm(request: LeaveRequest, allRequests: LeaveRequest[] = [], hodName?: string, hosName?: string): void {
  downloadLeaveApplicationFormPart2(request, allRequests, hodName, hosName, 'hos');
}