import { LeaveRequest, LEAVE_POLICIES } from '../app/hr/leave/leaveData';
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';

function getLeaveCarriedForward(_employeeId: string): number { return 15; }
function getAnnualLeaveDue(_employeeId: string): number { return 21; }
function getLeaveAlreadyTaken(_employeeId: string): number { return 10; }

function buildHtmlContent(request: LeaveRequest, hrName?: string): string {
  const today = new Date().toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' });
  const refNo = request.id;
  const policy = LEAVE_POLICIES.find(p => p.type === request.type);

  const carriedForward = getLeaveCarriedForward(request.employeeId);
  const annualDue = getAnnualLeaveDue(request.employeeId);
  const totalDue = carriedForward + annualDue;
  const alreadyTaken = getLeaveAlreadyTaken(request.employeeId);
  const nowApplied = request.days;
  const balanceDue = totalDue - alreadyTaken - nowApplied;

  const startObj = new Date(request.startDate);
  const endObj = new Date(request.endDate);
  const resumeDate = new Date(endObj);
  resumeDate.setDate(resumeDate.getDate() + 1);
  const resumeStr = resumeDate.toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' });
  const appDateStr = new Date(request.submittedOn).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' });
  const startStr = startObj.toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' });
  const endStr = endObj.toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' });
  const currentYear = new Date().getFullYear();
  const hrSignatureName = hrName || 'CHRP ELIZABETH MUTUNGI';

  const hrStamp = getHRStamp();

  const style = `
    @page { size: A4 portrait; margin: 8mm; }
    * { 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.5; }
    .page { width: 100%; max-width: 190mm; margin: 0 auto; padding: 0; }
    .logo-row { display: flex; align-items: center; justify-content: center; margin-bottom: 4px; }
    .logo-img { height: 65px; width: auto; object-fit: contain; }
    .org-title { text-align: center; font-size: 14pt; font-weight: bold; color: #111; letter-spacing: 1.5px; text-transform: uppercase; font-family: 'Tahoma', Arial, sans-serif; }
    .divider { border: none; border-top: 2.5px solid #b22698; margin: 4px 0 6px; }
    .ref-row { display: flex; justify-content: space-between; font-size: 11pt; color: #333; margin-bottom: 5px; font-family: 'Tahoma', Arial, sans-serif; }
    .emp-name { font-size: 12pt; font-weight: bold; font-family: 'Tahoma', Arial, sans-serif; margin-bottom: 2px; }
    .emp-pos { font-size: 11pt; color: #555; font-family: 'Tahoma', Arial, sans-serif; margin-bottom: 5px; }
    .page-title { text-align: center; font-size: 13pt; font-weight: bold; text-transform: uppercase; letter-spacing: 1px; color: #111; margin: 8px 0; font-family: 'Tahoma', Arial, sans-serif; border-bottom: 1px solid #ddd; padding-bottom: 5px; }
    .content-text { font-size: 12pt; line-height: 1.6; text-align: justify; margin: 8px 0 10px; color: #222; font-family: 'Tahoma', Arial, sans-serif; }
    .comp-label { font-size: 12pt; font-weight: bold; margin-bottom: 5px; font-family: 'Tahoma', Arial, sans-serif; }
    .leave-table { width: 100%; border-collapse: collapse; margin: 8px 0; font-size: 12pt; font-family: 'Tahoma', Arial, sans-serif; }
    .leave-table th, .leave-table td { border: 1.2px solid #333; padding: 5px 8px; vertical-align: middle; }
    .leave-table th { text-align: left; font-weight: bold; background: #f5f5f5; }
    .leave-table td.right { text-align: right; font-weight: bold; }
    .note-text { font-size: 12pt; line-height: 1.5; text-align: justify; border-top: 1px solid #ddd; padding-top: 8px; margin-top: 8px; color: #222; font-family: 'Tahoma', Arial, sans-serif; }
    .sig-section { margin-top: 12px; padding-top: 10px; }
    .sig-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; }
    .sig-box { padding: 5px; }
    .sig-line { border-top: 1.2px solid #333; padding-top: 5px; margin-top: 5px; }
    .sig-name { font-weight: bold; font-size: 12pt; font-family: 'Tahoma', Arial, sans-serif; }
    .sig-role { font-size: 11pt; color: #555; font-family: 'Tahoma', Arial, sans-serif; margin-top: 2px; }
    .sig-date { font-size: 11pt; color: #888; font-family: 'Tahoma', Arial, sans-serif; margin-top: 2px; }
    .stamp-box { height: 75px; display: flex; align-items: center; justify-content: center; border: 1px dashed #ccc; border-radius: 4px; background: #fafafa; }
    .stamp-img { height: 70px; width: auto; object-fit: contain; }
    .stamp-placeholder { font-size: 11pt; color: #bbb; text-align: center; font-family: 'Tahoma', Arial, sans-serif; }
    .hr-address { margin-top: 5px; font-size: 11pt; color: #666; font-family: 'Tahoma', Arial, sans-serif; text-align: center; }
  `;

  return `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Leave_Computation_${request.id}</title>
  <style>${style}</style>
</head>
<body>
<div class="page">

  <div class="logo-row">
    <img src="${UWEZO_LOGO}" class="logo-img" alt="Uwezo Fund Logo" />
  </div>
  <div class="org-title">UWEZO FUND OVERSIGHT BOARD</div>
  <hr class="divider" />

  <div class="ref-row">
    <span><strong>Ref:</strong> ${refNo}</span>
    <span><strong>Date:</strong> ${today}</span>
  </div>

  <div class="emp-name">${request.employee}</div>
  <div class="emp-pos">${request.position} &mdash; ${request.dept}</div>

  <div class="page-title">ANNUAL LEAVE COMPUTATION &amp; APPROVAL</div>

  <div class="content-text">
    Reference is made to your application dated <strong>${appDateStr}</strong>. This is to inform you that your 
    request for <strong>${nowApplied} days</strong> of <strong>${policy?.label || request.type}</strong> has been 
    approved to commence from <strong>${startStr}</strong> to <strong>${endStr}</strong>. 
    You are expected to resume duty on <strong>${resumeStr}</strong>.
  </div>

  <div class="comp-label">Leave Computation:</div>
  <table class="leave-table">
    <thead>
      <tr>
        <th style="width:70%;">DETAILS</th>
        <th style="width:30%;text-align:center;">NO. OF DAYS</th>
      </tr>
    </thead>
    <tbody>
      <tr><td style="border:1.2px solid #333; padding:5px 8px;">Leave carried forward 2024/2025</td><td class="right">${carriedForward}</td></tr>
      <tr><td style="border:1.2px solid #333; padding:5px 8px;">Annual leave due &mdash; 2025/2026</td><td class="right">${annualDue}</td></tr>
      <tr><td style="border:1.2px solid #333; padding:5px 8px;"><strong>Total leave due</strong></td><td class="right"><strong>${totalDue}</strong></td></tr>
      <tr><td style="border:1.2px solid #333; padding:5px 8px;">Less leave already taken</td><td class="right">${alreadyTaken}</td></tr>
      <tr><td style="border:1.2px solid #333; padding:5px 8px;">Less leave now applied for</td><td class="right">${nowApplied}</td></tr>
      <tr style="background:#fdf4ff;"><td style="border:1.2px solid #333; padding:5px 8px;"><strong>Balance due &mdash; 2025/2026</strong></td><td class="right"><strong>${balanceDue}</strong></td></tr>
    </tbody>
  </table>

  <div class="note-text">
    Please note that annual leave commences from <strong>1<sup>st</sup> July to 30<sup>th</sup> June</strong> of every 
    financial year. Any balance in excess of <strong>15 days</strong> as at <strong>30<sup>th</sup> June, ${currentYear}</strong> 
    will be forfeited automatically in accordance with the HUMAN RESOURCE POLICIES AND PROCEDURES MANUAL FOR THE PUBLIC 
    SERVICE (MAY 2016) SECTION E.3 (2)(IV).
  </div>

  <div class="sig-section">
    <div class="sig-grid">
      <div class="sig-box">
        <div class="sig-name">${hrSignatureName}</div>
        <div class="sig-role">FOR: HEAD OF SECRETARIAT</div>
        <div class="sig-date">Date: ${request.approvedOn || today}</div>
      </div>
      <div class="sig-box">
        ${hrStamp
          ? `<div class="stamp-box"><img src="${hrStamp}" class="stamp-img" alt="Office Stamp" /></div>`
          : `<div class="stamp-box"><div class="stamp-placeholder">OFFICIAL STAMP<br>HR Department</div></div>`
        }
        <div class="hr-address">HR Department — Uwezo Fund</div>
      </div>
    </div>
  </div>

</div>
</body>
</html>`;
}

// Load libraries dynamically and generate PDF
let librariesLoaded = false;
let pendingPromise: Promise<any> | null = null;

// @ts-ignore - Promise type workaround for TypeScript error
async function loadLibraries(): Promise<void> {
  if (librariesLoaded) return;
  
  if (pendingPromise) return pendingPromise;
  
  pendingPromise = new Promise((resolve, reject) => {
    let loadedCount = 0;
    const totalLibraries = 2;
    
    function checkComplete() {
      loadedCount++;
      if (loadedCount === totalLibraries) {
        librariesLoaded = true;
        pendingPromise = null;
        resolve(true);
      }
    }
    
    // Load html2canvas
    const canvasScript = document.createElement('script');
    canvasScript.src = 'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js';
    canvasScript.onload = checkComplete;
    canvasScript.onerror = () => reject(new Error('Failed to load html2canvas'));
    document.head.appendChild(canvasScript);
    
    // Load jspdf
    const pdfScript = document.createElement('script');
    pdfScript.src = 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js';
    pdfScript.onload = checkComplete;
    pdfScript.onerror = () => reject(new Error('Failed to load jspdf'));
    document.head.appendChild(pdfScript);
  });
  
  return pendingPromise;
}

// Generate and download PDF directly
export async function downloadLeaveComputationForm(request: LeaveRequest, hrName?: string): Promise<void> {
  const html = buildHtmlContent(request, hrName);
  const filename = `Leave_Computation_${request.id}.pdf`;
  
  // Create a temporary container with the HTML content
  const container = document.createElement('div');
  container.innerHTML = html;
  container.style.position = 'fixed';
  container.style.left = '-9999px';
  container.style.top = '-9999px';
  container.style.width = '800px';
  container.style.background = '#fff';
  container.style.padding = '20px';
  document.body.appendChild(container);
  
  try {
    // Wait for libraries to load
    await loadLibraries();
    
    // Wait for all images to load
    const images = container.querySelectorAll('img');
    await Promise.all(Array.from(images).map(img => {
      if (img.complete && img.naturalHeight !== 0) return Promise.resolve();
      return new Promise((resolve) => {
        img.onload = resolve;
        img.onerror = resolve;
        if (img.complete) resolve();
      });
    }));
    
    // Extra delay to ensure rendering
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // @ts-ignore - html2canvas is loaded globally
    const canvas = await html2canvas(container, {
      scale: 2,
      useCORS: true,
      logging: false,
      backgroundColor: '#ffffff'
    });
    
    // @ts-ignore - jspdf is loaded globally
    const { jsPDF } = window.jspdf;
    const pdf = new jsPDF('p', 'mm', 'a4');
    const imgData = canvas.toDataURL('image/png');
    const imgWidth = 210;
    const pageHeight = 297;
    const imgHeight = (canvas.height * imgWidth) / canvas.width;
    let heightLeft = imgHeight;
    let position = 0;
    
    pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
    heightLeft -= pageHeight;
    
    while (heightLeft > 0) {
      position = heightLeft - imgHeight;
      pdf.addPage();
      pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
      heightLeft -= pageHeight;
    }
    
    pdf.save(filename);
  } catch (error) {
    console.error('PDF generation failed:', error);
    // Fallback: open in new window
    const blob = new Blob([html], { type: 'text/html' });
    const url = URL.createObjectURL(blob);
    const newWindow = window.open(url, '_blank');
    if (newWindow) {
      setTimeout(() => URL.revokeObjectURL(url), 60000);
    }
  } finally {
    document.body.removeChild(container);
  }
}

export function downloadLeaveComputationFormWord(request: LeaveRequest, hrName?: string): void {
  const html = buildHtmlContent(request, hrName);
  const blob = new Blob([html], { type: 'application/msword' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `Leave_Computation_${request.id}.doc`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}