'use client';

import { useState } from 'react';
import { downloadLeaveComputationForm, downloadLeaveComputationFormWord } from '../../../lib/leaveComputationForm';
import { LeaveRequest, LEAVE_POLICIES, DEPARTMENTS } from './leaveData';
import { useAuth } from '../../../lib/authContext';
import LeaveDetailModal from './LeaveDetailModal';

// ----------------------------------------------------------------------
// Status configuration
// ----------------------------------------------------------------------
const STATUS_CONFIG: Record<string, { color: string; bg: string; icon: string }> = {
  Pending: { color: '#d97706', bg: '#fef3c7', icon: 'ri-time-line' },
  'Pending Review': { color: '#7c3aed', bg: '#ede9fe', icon: 'ri-refresh-line' },
  'HOD Approved': { color: '#2563eb', bg: '#dbeafe', icon: 'ri-shield-check-line' },
  'HOS Approved': { color: '#059669', bg: '#d1fae5', icon: 'ri-check-double-line' },
  Approved: { color: '#16a34a', bg: '#dcfce7', icon: 'ri-checkbox-circle-line' },
  Rejected: { color: '#dc2626', bg: '#fee2e2', icon: 'ri-close-circle-line' },
  Cancelled: { color: '#6b7280', bg: '#f3f4f6', icon: 'ri-forbid-line' },
  'Under Review': { color: '#7c3aed', bg: '#ede9fe', icon: 'ri-refresh-line' },
  Withdrawn: { color: '#64748b', bg: '#f1f5f9', icon: 'ri-arrow-go-back-line' },
};

interface Props {
  requests: LeaveRequest[];
  onUpdate: (requests: LeaveRequest[]) => void;
  showToast: (msg: string, type?: 'success' | 'error') => void;
  isAdmin?: boolean;
}

// ----------------------------------------------------------------------
// Dummy calculation helpers (replace with real data)
// ----------------------------------------------------------------------
function getLeaveCarriedForward(_employeeId: string): number {
  return 15;
}
function getAnnualLeaveDue(_employeeId: string): number {
  return 21;
}
function getLeaveAlreadyTaken(_employeeId: string): number {
  return 10;
}

// ----------------------------------------------------------------------
// Build the PDF HTML content (NO header / NO footer, fixed "NonNull" bug)
// ----------------------------------------------------------------------
function buildComputationHtml(request: LeaveRequest, hrName?: string): string {
  const today = new Date().toLocaleDateString('en-GB', {
    day: 'numeric',
    month: 'long',
    year: 'numeric',
  });
  const refNo = request.id;

  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 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.5; }
    .container { max-width: 720px; margin: 0 auto; padding: 24px; background: #fff; }
    .ref-row { display: flex; justify-content: space-between; font-size: 10pt; color: #333; margin-bottom: 6px; }
    .employee-details { margin-bottom: 8px; }
    .employee-name { font-size: 12pt; font-weight: bold; margin: 0; }
    .employee-position { font-size: 10pt; color: #555; margin: 2px 0 0; }
    .page-title { text-align: center; font-size: 13pt; font-weight: bold; text-transform: uppercase; margin: 8px 0 12px; letter-spacing: 1px; color: #111; }
    .content-text { font-size: 12pt; line-height: 1.7; text-align: justify; margin-bottom: 10px; color: #222; }
    .computation-header { font-size: 12pt; font-weight: bold; margin: 8px 0 4px; }
    .leave-table { width: 100%; border-collapse: collapse; margin: 10px 0; font-size: 12pt; }
    .leave-table th, .leave-table td { border: 1.5px solid #333; padding: 5px 8px; vertical-align: top; }
    .leave-table th { text-align: left; font-weight: bold; background: #f5f5f5; }
    .leave-table td.right { text-align: right; font-weight: bold; }
    .note-text { font-family: 'Tahoma', Arial, sans-serif; font-size: 12pt; line-height: 1.6; text-align: justify; border-top: 1px solid #ddd; padding-top: 10px; margin-top: 10px; color: #222; }
    .signature-block { margin-top: 20px; display: flex; justify-content: flex-start; }
    .signature { font-size: 10pt; line-height: 1.5; }
    .signature-name { font-weight: bold; font-size: 11pt; }
  `;

  return `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>annual_leave_1</title>
  <style>${style}</style>
</head>
<body>
<div class="container">
  <div class="ref-row">
    <span><strong>Ref:</strong> ${refNo}</span>
    <span><strong>${today}</strong></span>
  </div>
  <div class="employee-details">
    <p class="employee-name">${request.employee}</p>
    <p class="employee-position">${request.position}</p>
  </div>
  <div class="page-title">ANNUAL LEAVE 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> leave
    has been approved to commence from <strong>${startStr} - ${endStr}</strong>.
    You are therefore expected to resume duty on <strong>${resumeStr}</strong>.
  </div>
  <div class="computation-header">This is computed as under:</div>
  <table class="leave-table">
    <thead>
      <tr><th style="width:60%;">DETAILS</th><th style="width:40%;text-align:center;">NO. OF DAYS</th></tr>
    </thead>
    <tbody>
      <tr><td style="border:1.5px solid #333; padding:5px 8px;">Leave carried forward 2024/2025</td><td class="right">${carriedForward}</td></tr>
      <tr><td style="border:1.5px solid #333; padding:5px 8px;">Annual leave due — 2025/2026</td><td class="right">${annualDue}</td></tr>
      <tr><td style="border:1.5px solid #333; padding:5px 8px;"><strong>Total leave due</strong></td><td class="right"><strong>${totalDue}</strong></td></tr>
      <tr><td style="border:1.5px solid #333; padding:5px 8px;">Less leave already taken</td><td class="right">${alreadyTaken}</td></tr>
      <tr><td style="border:1.5px solid #333; padding:5px 8px;">Less leave now applied for</td><td class="right">${nowApplied}</td></tr>
      <tr><td style="border:1.5px solid #333; padding:5px 8px;"><strong>Balance due — 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="signature-block">
    <div class="signature">
      <p class="signature-name">${hrSignatureName}</p>
      <p>FOR: HEAD OF SECRETARIAT</p>
    </div>
  </div>
</div>
<script>
  (function() {
    window.print();
    setTimeout(function() { window.close(); }, 500);
  })();
</script>
</body>
</html>`;
}

// ----------------------------------------------------------------------
// PDF generation using browser's print (ensures content is ready)
// ----------------------------------------------------------------------
async function downloadComputationPdf(request: LeaveRequest, hrName?: string): Promise<void> {
  const html = buildComputationHtml(request, hrName);
  const blob = new Blob([html], { type: 'text/html' });
  const url = URL.createObjectURL(blob);
  const iframe = document.createElement('iframe');
  iframe.style.position = 'fixed';
  iframe.style.left = '-10000px';
  iframe.style.top = '-10000px';
  iframe.style.width = '1px';
  iframe.style.height = '1px';
  iframe.style.border = 'none';
  document.body.appendChild(iframe);

  return new Promise((resolve, reject) => {
    const cleanup = () => {
      if (iframe.parentNode) document.body.removeChild(iframe);
      URL.revokeObjectURL(url);
    };
    const timeout = setTimeout(() => {
      cleanup();
      reject(new Error('PDF print timed out'));
    }, 30000);
    iframe.onload = () => {
      clearTimeout(timeout);
      setTimeout(() => {
        cleanup();
        resolve();
      }, 5000);
    };
    iframe.onerror = () => {
      clearTimeout(timeout);
      cleanup();
      reject(new Error('Failed to load print document'));
    };
    iframe.src = url;
  });
}

// ----------------------------------------------------------------------
// Main component
// ----------------------------------------------------------------------
export default function LeaveRequestsTab({
  requests,
  onUpdate,
  showToast,
  isAdmin = false,
}: Props) {
  const { user } = useAuth();
  const [statusFilter, setStatusFilter] = useState('All');
  const [deptFilter, setDeptFilter] = useState('All Departments');
  const [typeFilter, setTypeFilter] = useState('All');
  const [empTypeFilter, setEmpTypeFilter] = useState('All');
  const [search, setSearch] = useState('');
  const [selected, setSelected] = useState<LeaveRequest | null>(null);

  const hrVisibleRequests = requests.filter(
    (r) => r.status === 'HOS Approved' || r.status === 'Approved'
  );

  const filtered = hrVisibleRequests.filter((r) => {
    const ms = statusFilter === 'All' || r.status === statusFilter;
    const md = deptFilter === 'All Departments' || r.dept === deptFilter;
    const mt = typeFilter === 'All' || r.type === typeFilter;
    const met = empTypeFilter === 'All' || r.employeeType === empTypeFilter;
    const mq =
      !search ||
      r.employee.toLowerCase().includes(search.toLowerCase()) ||
      r.id.toLowerCase().includes(search.toLowerCase());
    return ms && md && mt && met && mq;
  });

  const uniqueFiltered = filtered.filter(
    (r, i, arr) => arr.findIndex((x) => x.id === r.id) === i
  );

  const counts: Record<string, number> = { 'HOS Approved': 0, Approved: 0 };
  hrVisibleRequests.forEach((r) => {
    if (r.status in counts) counts[r.status]++;
  });

  const exportCSV = () => {
    const rows = [
      [
        'Request ID',
        'Employee',
        'Department',
        'Type',
        'Employee Type',
        'Start Date',
        'End Date',
        'Days',
        'Status',
        'Submitted On',
        'HOS Approved By',
        'HOS Approved On',
      ],
      ...filtered.map((r) => [
        r.id,
        r.employee,
        r.dept,
        r.type,
        r.employeeType,
        r.startDate,
        r.endDate,
        r.days,
        r.status,
        r.submittedOn,
        r.hosApprovedBy || '',
        r.hosApprovedOn || '',
      ]),
    ];
    const csv = rows.map((row) => row.join(',')).join('\n');
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `leave-records-${new Date().toISOString().split('T')[0]}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const handleDownloadComputation = (req: LeaveRequest) => {
    downloadLeaveComputationForm(req, user?.name);
    showToast('Leave computation form downloaded.', 'success');
  };

  return (
    <div>
      {/* Filter row */}
      <div className="flex flex-wrap items-center gap-3 mb-4">
        <div className="flex gap-2 flex-wrap">
          {(['All', 'HOS Approved', 'Approved'] as const).map((s) => (
            <button
              key={s}
              onClick={() => setStatusFilter(s)}
              className="px-3 py-1.5 rounded-full text-xs font-semibold cursor-pointer whitespace-nowrap transition-all"
              style={
                statusFilter === s
                  ? { background: '#b828a0', color: '#fff' }
                  : { background: '#f3f4f6', color: '#4b5563' }
              }
            >
              {s}
              {s !== 'All' ? ` (${counts[s] || 0})` : ''}
            </button>
          ))}
        </div>
        <div className="ml-auto flex items-center gap-2">
          <button
            onClick={exportCSV}
            className="flex items-center gap-1.5 px-3 py-2 border border-gray-200 rounded-lg text-xs text-gray-600 cursor-pointer hover:bg-gray-50 whitespace-nowrap"
          >
            <i className="ri-download-line"></i> Export CSV
          </button>
        </div>
      </div>

      {/* Info banner */}
      <div className="bg-blue-50 border border-blue-200 rounded-xl px-4 py-3 flex items-start gap-2 mb-4">
        <i className="ri-information-line text-blue-600 mt-0.5"></i>
        <p className="text-xs text-blue-800">
          <strong>HR Records View:</strong> Only HOS‑approved requests are displayed here.
          HR Managers do not approve leave requests — final approval is granted by the
          Head of Secretariat (HOS). You may download computation forms for record‑keeping.
        </p>
      </div>

      {/* Table */}
      <div className="bg-white rounded-xl border border-gray-100 shadow-sm">
        <div className="px-4 py-3 border-b border-gray-100 flex flex-wrap gap-3 items-center">
          <div className="relative flex-1 min-w-[180px]">
            <i className="ri-search-line absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm"></i>
            <input
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Search employee or ID..."
              className="pl-9 pr-4 py-2 border border-gray-200 rounded-lg text-sm w-full outline-none"
            />
          </div>
          <select
            value={deptFilter}
            onChange={(e) => setDeptFilter(e.target.value)}
            className="border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none pr-8 cursor-pointer"
          >
            {DEPARTMENTS.map((d) => (
              <option key={d}>{d}</option>
            ))}
          </select>
          <select
            value={typeFilter}
            onChange={(e) => setTypeFilter(e.target.value)}
            className="border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none pr-8 cursor-pointer"
          >
            <option value="All">All Types</option>
            {LEAVE_POLICIES.map((p) => (
              <option key={p.type} value={p.type}>
                {p.label}
              </option>
            ))}
          </select>
          <select
            value={empTypeFilter}
            onChange={(e) => setEmpTypeFilter(e.target.value)}
            className="border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none pr-8 cursor-pointer"
          >
            <option value="All">All Types</option>
            <option value="Employee">Employee</option>
            <option value="Intern">Intern</option>
          </select>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-gray-100 bg-gray-50/50">
                <th className="text-left px-4 py-3 font-semibold text-gray-500 text-xs uppercase">Request ID</th>
                <th className="text-left px-4 py-3 font-semibold text-gray-500 text-xs uppercase">Employee</th>
                <th className="text-left px-4 py-3 font-semibold text-gray-500 text-xs uppercase">Leave Type</th>
                <th className="text-left px-4 py-3 font-semibold text-gray-500 text-xs uppercase">Start Date</th>
                <th className="text-left px-4 py-3 font-semibold text-gray-500 text-xs uppercase">End Date</th>
                <th className="text-center px-4 py-3 font-semibold text-gray-500 text-xs uppercase">Days</th>
                <th className="text-left px-4 py-3 font-semibold text-gray-500 text-xs uppercase">Reason</th>
                <th className="text-left px-4 py-3 font-semibold text-gray-500 text-xs uppercase">HOS Comment</th>
                <th className="text-left px-4 py-3 font-semibold text-gray-500 text-xs uppercase">Status</th>
                <th className="text-right px-4 py-3 font-semibold text-gray-500 text-xs uppercase">Actions</th>
              </tr>
            </thead>
            <tbody>
              {uniqueFiltered.length === 0 && (
                <tr>
                  <td colSpan={9} className="text-center py-12 text-gray-400 text-sm">
                    No HOS‑approved leave requests found
                  </td>
                </tr>
              )}
              {uniqueFiltered.map((req) => {
                const st = STATUS_CONFIG[req.status] || STATUS_CONFIG.Pending;
                const policy = LEAVE_POLICIES.find((p) => p.type === req.type);
                const canDownload = req.status === 'Approved' || req.status === 'HOS Approved';
                return (
                  <tr key={req.id} className="border-b border-gray-50 hover:bg-gray-50/50 transition-colors">
                    <td className="px-4 py-3 font-mono text-xs text-gray-500">{req.id}</td>
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-2">
                        <div className="w-8 h-8 rounded-full flex items-center justify-center text-white text-xs font-bold flex-shrink-0 bg-[#b828a0]">
                          {req.employee.split(' ').map((n) => n[0]).join('').slice(0, 2)}
                        </div>
                        <div>
                          <p className="font-medium text-gray-800 text-sm">{req.employee}</p>
                          <div className="flex items-center gap-1">
                            <p className="text-xs text-gray-400">{req.dept}</p>
                            <span
                              className={`text-xs px-1.5 py-0.5 rounded-full font-medium ${
                                req.employeeType === 'Intern'
                                  ? 'bg-orange-100 text-orange-700'
                                  : 'bg-blue-100 text-blue-700'
                              }`}
                            >
                              {req.employeeType}
                            </span>
                          </div>
                        </div>
                      </div>
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-1.5">
                        <div className="w-2 h-2 rounded-full flex-shrink-0" style={{ background: policy?.color || '#999' }}></div>
                        <span className="text-gray-700 text-sm whitespace-nowrap">{policy?.label || req.type}</span>
                      </div>
                    </td>
                    <td className="px-4 py-3 text-gray-600 text-sm">{req.startDate}</td>
                    <td className="px-4 py-3 text-gray-600 text-sm">{req.endDate}</td>
                    <td className="px-4 py-3 text-center font-semibold text-gray-800">{req.days}</td>
                    <td className="px-4 py-3 text-xs text-gray-500 max-w-[160px] truncate">{req.reason}</td>
                    <td className="px-4 py-3">
                      {req.hosComment ? (
                        <div className="max-w-[180px]">
                          <p className="text-xs text-green-700 font-medium truncate" title={req.hosComment}>{req.hosComment}</p>
                          {req.hosApprovedBy && <p className="text-xs text-gray-400">{req.hosApprovedBy?.split('(')[0]?.trim()}</p>}
                        </div>
                      ) : (
                        <span className="text-xs text-gray-300">—</span>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <span
                        className="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-semibold"
                        style={{ color: st.color, background: st.bg }}
                      >
                        <i className={st.icon}></i> {req.status}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center justify-end gap-1">
                        {canDownload && (
                          <button
                            onClick={() => handleDownloadComputation(req)}
                            title="Download Leave Computation Form (PDF)"
                            className="flex items-center gap-1 px-2 py-1 rounded-lg bg-blue-50 text-blue-600 hover:bg-blue-100 cursor-pointer text-xs font-medium whitespace-nowrap"
                          >
                            <i className="ri-file-pdf-line"></i> Computation
                          </button>
                        )}
                        <button
                          onClick={() => setSelected(req)}
                          title="View"
                          className="w-7 h-7 flex items-center justify-center rounded-lg bg-blue-50 text-blue-500 hover:bg-blue-100 cursor-pointer"
                        >
                          <i className="ri-eye-line text-sm"></i>
                        </button>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        <div className="px-4 py-2 border-t border-gray-50 bg-gray-50/30">
          <p className="text-xs text-gray-400">Showing {uniqueFiltered.length} of {hrVisibleRequests.length} HOS‑approved requests</p>
        </div>
      </div>

      {selected && (
        <LeaveDetailModal
          request={selected}
          isHR={true}
          isAdmin={isAdmin}
          onClose={() => setSelected(null)}
        />
      )}
    </div>
  );
}