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

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 TAHOMA_STYLE = `
  * { margin: 0; padding: 0; box-sizing: border-box; }
  body { font-family: 'Tahoma', Arial, sans-serif; font-size: 12pt; color: #111; background: #fff; line-height: 1.6; }
  .page { max-width: 760px; margin: 0 auto; padding: 28px; }
  .logo-row { display: flex; align-items: center; justify-content: center; margin-bottom: 10px; }
  .logo-img { height: 80px; width: auto; object-fit: contain; }
  .doc-ref { font-size: 10pt; color: #666; text-align: right; line-height: 1.7; }
  .divider { border: none; border-top: 3px solid #b22698; margin: 8px 0 16px; }
  .doc-title { text-align: center; font-size: 14pt; font-weight: bold; color: #b22698; letter-spacing: 2px; text-transform: uppercase; margin-bottom: 4px; }
  .doc-subtitle { text-align: center; font-size: 11pt; color: #777; margin-bottom: 20px; }
  .section { margin-bottom: 16px; }
  .section-header { background: #b22698; color: #fff; font-size: 12pt; font-weight: bold; padding: 6px 12px; border-radius: 4px 4px 0 0; text-transform: uppercase; letter-spacing: 0.5px; }
  .section-body { border: 1px solid #e0d0e8; border-top: none; border-radius: 0 0 4px 4px; overflow: hidden; }
  table.info { width: 100%; border-collapse: collapse; }
  table.info tr:nth-child(even) td { background: #fdf4ff; }
  table.info td { padding: 7px 12px; border-bottom: 1px solid #ece8f0; font-size: 12pt; vertical-align: top; font-family: 'Tahoma', Arial, sans-serif; }
  table.info td:first-child { font-weight: 600; color: #555; width: 38%; background: #f8f0fc; border-right: 1px solid #ece8f0; }
  table.info tr:last-child td { border-bottom: none; }
  .status-badge { display: inline-block; background: #b22698; color: #fff; font-weight: bold; padding: 4px 16px; border-radius: 20px; font-size: 12pt; letter-spacing: 0.5px; }
  .sig-section { margin-top: 28px; border-top: 2px dashed #e0d0e8; padding-top: 18px; }
  .sig-grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px; margin-top: 10px; }
  .sig-box { padding: 10px; }
  .sig-line { border-top: 1.5px solid #333; margin-top: 42px; padding-top: 6px; }
  .sig-name { font-weight: bold; font-size: 12pt; color: #222; font-family: 'Tahoma', Arial, sans-serif; }
  .sig-role { font-size: 12pt; color: #888; margin-top: 2px; font-family: 'Tahoma', Arial, sans-serif; }
  .sig-date { font-size: 12pt; color: #aaa; margin-top: 2px; font-family: 'Tahoma', Arial, sans-serif; }
  .digital-sig { margin-top: 20px; border: 2px solid #16a34a; border-radius: 8px; padding: 12px 16px; background: #f0fdf4; }
  .digital-sig-header { font-size: 12pt; font-weight: bold; color: #16a34a; text-transform: uppercase; margin-bottom: 6px; font-family: 'Tahoma', Arial, sans-serif; }
  .digital-sig-name { font-size: 13pt; font-weight: bold; color: #111; font-family: 'Tahoma', Arial, sans-serif; }
  .digital-sig-meta { font-size: 11pt; color: #555; margin-top: 3px; font-family: 'Tahoma', Arial, sans-serif; }
  .footer { margin-top: 28px; border-top: 1px solid #eee; padding-top: 10px; text-align: center; font-size: 9pt; color: #bbb; font-family: 'Tahoma', Arial, sans-serif; }
`;

export function downloadLeaveComputationPdf(request: LeaveRequest, hrName?: string): void {
  const policy = LEAVE_POLICIES.find(p => p.type === request.type);
  const today = new Date().toLocaleDateString('en-KE', { year: 'numeric', month: 'long', day: 'numeric' });
  const ref = request.id;
  const entitlement = request.employeeType === 'Intern' ? '15' : '30';
  const isHOSApproved = request.status === 'HOS Approved' || request.status === 'Approved';

  let html = `<!DOCTYPE html><html><head><meta charset="utf-8"><title>Leave Computation Form - ${ref}</title><style>${TAHOMA_STYLE}</style></head><body>`;
  html += '<div class="page">';

  html += `<div class="logo-row"><img src="${UWEZO_LOGO}" class="logo-img" alt="Uwezo Fund Logo" /></div>`;
  html += '<div class="doc-title">UWEZO FUND OVERSIGHT BOARD</div>';
  html += '<hr class="divider">';
  html += '<div class="doc-title" style="font-size:13pt;margin-top:4px;">Leave Computation Form</div>';
  html += '<div class="doc-subtitle">Official Staff Leave Record &amp; Approval Document</div>';
  html += `<div style="text-align:right;font-size:10pt;color:#666;margin-bottom:14px;font-family:Tahoma,Arial,sans-serif;"><strong>Ref No:</strong> ${ref} &nbsp;|&nbsp; <strong>Date Generated:</strong> ${today}</div>`;

  html += `<div class="section"><div class="section-header">1. Employee Information</div>
    <div class="section-body"><table class="info">
    <tr><td>Full Name</td><td>${request.employee}</td></tr>
    <tr><td>Department</td><td>${request.dept}</td></tr>
    <tr><td>Position / Designation</td><td>${request.position}</td></tr>
    <tr><td>Employee Type</td><td>${request.employeeType}</td></tr>
    </table></div></div>`;

  html += `<div class="section"><div class="section-header">2. Leave Details</div>
    <div class="section-body"><table class="info">
    <tr><td>Leave Type</td><td>${policy?.label || request.type}</td></tr>
    <tr><td>Leave Start Date</td><td>${request.startDate}</td></tr>
    <tr><td>Leave End Date</td><td>${request.endDate}</td></tr>
    <tr><td>Total Leave Days Applied</td><td><strong>${request.days} working day(s)</strong></td></tr>
    <tr><td>Reason for Leave</td><td>${request.reason || '—'}</td></tr>
    </table></div></div>`;

  html += `<div class="section"><div class="section-header">3. Leave Balance Computation</div>
    <div class="section-body"><table class="info">
    <tr><td>Annual Entitlement</td><td>${entitlement} days</td></tr>
    <tr><td>Days Taken This Request</td><td>${request.days} days</td></tr>
    <tr><td>Leave Commencement Date</td><td>${request.startDate}</td></tr>
    <tr><td>Expected Return to Duty</td><td>${request.endDate}</td></tr>
    </table></div></div>`;

  html += `<div class="section"><div class="section-header">4. Approval Trail</div>
    <div class="section-body"><table class="info">
    <tr><td>Date Submitted</td><td>${request.submittedOn}</td></tr>
    <tr><td>HOD Review / Approval</td><td>${request.hodApprovedOn ? `Approved on ${request.hodApprovedOn} by ${request.hodApprovedBy || 'HOD'}` : 'Pending'}</td></tr>
    <tr><td>Head of Secretariat Review</td><td>${request.hosApprovedOn ? `Approved on ${request.hosApprovedOn} by ${request.hosApprovedBy || 'HOS/CEO'}` : 'Pending / N/A'}</td></tr>
    <tr><td>HR Final Record</td><td>${request.approvedOn ? `Recorded on ${request.approvedOn} by ${request.approvedBy || 'HR Manager'}` : 'Pending'}</td></tr>
    </table></div></div>`;

  html += `<div class="section"><div class="section-header">5. Leave Status</div>
    <div class="section-body" style="padding:12px 14px;">
    <span class="status-badge">${request.status.toUpperCase()}</span>
    ${request.hosComment ? `<p style="margin-top:8px;font-size:12pt;color:#555;font-family:Tahoma,Arial,sans-serif;"><strong>Note:</strong> ${request.hosComment}</p>` : ''}
    </div></div>`;

  html += `<div class="sig-section">
    <div style="text-align:left;font-weight:bold;color:#555;font-size:12pt;margin-bottom:0;font-family:Tahoma,Arial,sans-serif;">AUTHORIZED SIGNATURES</div>
    <div class="sig-grid">
      <div class="sig-box"><div class="sig-line">
        <div class="sig-name">Employee</div>
        <div class="sig-role">${request.employee}</div>
        <div class="sig-date">Date: ____________</div>
      </div></div>
      <div class="sig-box"><div class="sig-line">
        <div class="sig-name">Head of Department</div>
        <div class="sig-role">${request.dept}</div>
        <div class="sig-date">Date: ${request.hodApprovedOn || '____________'}</div>
      </div></div>
      <div class="sig-box"><div class="sig-line">
        <div class="sig-name">HR Manager</div>
        <div class="sig-role">Human Resources, Uwezo Fund</div>
        <div class="sig-date">Date: ${request.approvedOn || '____________'}</div>
      </div></div>
    </div></div>`;

  if (isHOSApproved) {
    html += `<div class="digital-sig">
      <div class="digital-sig-header">&#10003; Digitally Authorized by Head of Secretariat</div>
      <div class="digital-sig-name">${request.hosApprovedBy || 'HEAD OF SECRETARIAT / CEO'}</div>
      <div class="digital-sig-meta">Head of Secretariat — Uwezo Fund Oversight Board</div>
      <div class="digital-sig-meta">Digitally Signed on: ${request.hosApprovedOn || today}</div>
      <div class="digital-sig-meta" style="font-size:10pt;color:#888;margin-top:4px;">This document has been electronically authorized. Ref: ${ref}</div>
    </div>`;
  }

  html += `<div class="footer">This document is an official record generated by Uwezo Fund HRMS &bull; Printed on: ${today}<br>Uwezo Fund &bull; P.O. Box 00100, Nairobi, Kenya &bull; info@uwezo.go.ke</div>`;
  html += '</div></body></html>';

  triggerFileDownload(html, `Leave_Computation_${request.id}.pdf`);
}

export function downloadApprovalLetterPdf(request: LeaveRequest): void {
  const policy = LEAVE_POLICIES.find(p => p.type === request.type);
  const today = request.approvedOn || new Date().toISOString().split('T')[0];
  const isHOSApproved = request.status === 'HOS Approved' || request.status === 'Approved';

  const style = `
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body { font-family: 'Tahoma', Arial, sans-serif; font-size: 12pt; color: #222; background: #fff; line-height: 1.6; }
    .page { max-width: 760px; margin: 0 auto; padding: 30px; }
    .logo-row { display: flex; align-items: center; justify-content: center; margin-bottom: 16px; }
    .logo-img { height: 80px; width: auto; object-fit: contain; }
    .doc-title { text-align: center; font-size: 14pt; font-weight: bold; color: #b22698; letter-spacing: 2px; text-transform: uppercase; margin-bottom: 4px; }
    .divider { border: none; border-top: 3px solid #b22698; margin: 8px 0 18px; }
    .sub-title { text-align: center; font-size: 13pt; font-weight: bold; color: #b22698; margin-top: 4px; margin-bottom: 20px; }
    table.info { width: 100%; border-collapse: collapse; }
    table.info td { padding: 7px 12px; border-bottom: 1px solid #ece8f0; font-size: 12pt; vertical-align: top; font-family: 'Tahoma', Arial, sans-serif; }
    table.info td:first-child { font-weight: 600; color: #555; width: 38%; background: #f8f0fc; border-right: 1px solid #ece8f0; }
    .status-green { color: #16a34a; font-weight: bold; }
    .digital-sig { margin-top: 20px; border: 2px solid #16a34a; border-radius: 8px; padding: 12px 16px; background: #f0fdf4; }
    .digital-sig-header { font-size: 12pt; font-weight: bold; color: #16a34a; text-transform: uppercase; margin-bottom: 6px; font-family: 'Tahoma', Arial, sans-serif; }
    .digital-sig-name { font-size: 13pt; font-weight: bold; color: #111; font-family: 'Tahoma', Arial, sans-serif; }
    .digital-sig-meta { font-size: 11pt; color: #555; margin-top: 3px; font-family: 'Tahoma', Arial, sans-serif; }
    .footer { margin-top: 30px; border-top: 1px solid #eee; padding-top: 12px; text-align: center; font-size: 9pt; color: #bbb; font-family: 'Tahoma', Arial, sans-serif; }
  `;

  let html = `<!DOCTYPE html><html><head><meta charset="utf-8"><title>Leave Approval Letter - ${request.id}</title><style>${style}</style></head><body>`;
  html += '<div class="page">';
  html += `<div class="logo-row"><img src="${UWEZO_LOGO}" class="logo-img" alt="Uwezo Fund Logo" /></div>`;
  html += '<div class="doc-title">UWEZO FUND OVERSIGHT BOARD</div>';
  html += '<hr class="divider">';
  html += '<div class="sub-title">LEAVE APPROVAL LETTER</div>';
  html += `<div style="text-align:right;font-size:10pt;color:#666;margin-bottom:14px;font-family:Tahoma,Arial,sans-serif;"><strong>Ref No:</strong> ${request.id} &nbsp;|&nbsp; <strong>Date:</strong> ${today}</div>`;
  html += `<p style="font-family:Tahoma,Arial,sans-serif;font-size:12pt;"><strong>To:</strong> ${request.employee}<br><strong>Department:</strong> ${request.dept}<br><strong>Position:</strong> ${request.position}</p>`;
  html += `<p style="margin-top:16px;font-family:Tahoma,Arial,sans-serif;font-size:12pt;"><strong>RE: APPROVAL OF ${(policy?.label || request.type).toUpperCase()}</strong></p>`;
  html += `<p style="margin-top:10px;font-family:Tahoma,Arial,sans-serif;font-size:12pt;">Dear ${request.employee?.split(' ')[0] || 'Employee'},</p>`;
  html += `<p style="margin-top:10px;font-family:Tahoma,Arial,sans-serif;font-size:12pt;line-height:1.7;">This letter confirms that your application for <strong>${policy?.label || request.type}</strong> has been reviewed and <strong class="status-green">APPROVED</strong>.</p>`;
  html += `<table class="info" style="margin-top:16px;">
    <tr><td>Leave Type</td><td>${policy?.label || request.type}</td></tr>
    <tr><td>Start Date</td><td>${request.startDate}</td></tr>
    <tr><td>End Date</td><td>${request.endDate}</td></tr>
    <tr><td>Duration</td><td>${request.days} day(s)</td></tr>
    <tr><td>Reason</td><td>${request.reason}</td></tr>
    <tr><td>Approved By</td><td>${request.hosApprovedBy || 'Head of Secretariat'}</td></tr>
    <tr><td>Approved On</td><td>${request.hosApprovedOn || today}</td></tr>
    </table>`;
  html += `<p style="margin-top:20px;font-family:Tahoma,Arial,sans-serif;font-size:12pt;">You are expected to resume duty on the next working day after <strong>${request.endDate}</strong>.</p>`;
  html += `<p style="margin-top:40px;font-family:Tahoma,Arial,sans-serif;font-size:12pt;">Yours sincerely,<br><br><br>_______________________<br><strong>${request.hosApprovedBy || 'HEAD OF SECRETARIAT'}</strong><br>Head of Secretariat<br>Uwezo Fund</p>`;

  if (isHOSApproved) {
    html += `<div class="digital-sig">
      <div class="digital-sig-header">&#10003; Digitally Authorized by Head of Secretariat</div>
      <div class="digital-sig-name">${request.hosApprovedBy || 'HEAD OF SECRETARIAT / CEO'}</div>
      <div class="digital-sig-meta">Head of Secretariat — Uwezo Fund Oversight Board</div>
      <div class="digital-sig-meta">Digitally Signed on: ${request.hosApprovedOn || today}</div>
      <div class="digital-sig-meta" style="font-size:10pt;color:#888;margin-top:4px;">This document has been electronically authorized. Ref: ${request.id}</div>
    </div>`;
  }

  html += `<div class="footer">Uwezo Fund HRMS v2.0.1 &copy; 2026 &bull; P.O. Box 00100, Nairobi, Kenya &bull; info@uwezo.go.ke</div>`;
  html += '</div></body></html>';

  triggerFileDownload(html, `Approval_Letter_${request.id}.pdf`);
}