'use client';
import { useEffect, useRef } from 'react';
import { Employee } from './EmployeesContent';

interface Props {
  employees: Employee[];
  onClose: () => void;
}

function exportCSV(employees: Employee[]) {
  const headers = ['ID', 'Name', 'Email', 'Phone', 'Department', 'Role', 'Status', 'Employment Type', 'Date Joined', 'Salary', 'National ID', 'KRA PIN'];
  const rows = employees.map(e => [
    e.id, e.name, e.email, e.phone, e.dept, e.role, e.status, e.employmentType, e.joined, e.salary, e.nationalId, e.kraPin
  ]);
  const content = [headers, ...rows].map(r => r.map(c => `"${c}"`).join(',')).join('\n');
  download('employees.csv', content, 'text/csv');
}

function exportExcel(employees: Employee[]) {
  const headers = ['ID', 'Name', 'Email', 'Phone', 'Department', 'Role', 'Status', 'Employment Type', 'Date Joined', 'Salary', 'National ID', 'KRA PIN'];
  const rows = employees.map(e => [
    e.id, e.name, e.email, e.phone, e.dept, e.role, e.status, e.employmentType, e.joined, e.salary, e.nationalId, e.kraPin
  ]);
  const table = [headers, ...rows].map(r => r.join('\t')).join('\n');
  download('employees.xls', table, 'application/vnd.ms-excel');
}

function exportWord(employees: Employee[]) {
  const rows = employees.map(e => `
    <tr>
      <td>${e.id}</td><td>${e.name}</td><td>${e.dept}</td><td>${e.role}</td>
      <td>${e.status}</td><td>${e.salary}</td><td>${e.joined}</td>
    </tr>`).join('');
  const html = `
    <html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word'>
    <head><meta charset='utf-8'><title>Uwezo Fund - Employee Records</title></head>
    <body>
      <h2 style="color:#7B1FA2">Uwezo Fund — Employee Records</h2>
      <p>Generated: ${new Date().toLocaleDateString()}</p>
      <table border="1" cellpadding="6" cellspacing="0" style="border-collapse:collapse;width:100%;font-size:12px">
        <thead style="background:#7B1FA2;color:white">
          <tr><th>ID</th><th>Name</th><th>Department</th><th>Role</th><th>Status</th><th>Salary</th><th>Date Joined</th></tr>
        </thead>
        <tbody>${rows}</tbody>
      </table>
    </body></html>`;
  download('employees.doc', html, 'application/msword');
}

function exportPDF(employees: Employee[]) {
  const rows = employees.map(e =>
    `<tr><td>${e.id}</td><td>${e.name}</td><td>${e.dept}</td><td>${e.role}</td><td>${e.status}</td><td>${e.salary}</td><td>${e.joined}</td></tr>`
  ).join('');
  const html = `<!DOCTYPE html><html><head><meta charset='utf-8'><title>Employee Records</title>
    <style>
      body{font-family:Arial,sans-serif;padding:20px;color:#333}
      h2{color:#7B1FA2}
      table{width:100%;border-collapse:collapse;font-size:11px;margin-top:16px}
      th{background:#7B1FA2;color:white;padding:8px 6px;text-align:left}
      td{padding:7px 6px;border-bottom:1px solid #eee}
      tr:nth-child(even){background:#f9f5ff}
    </style></head><body>
    <h2>Uwezo Fund — Employee Records</h2>
    <p style="font-size:12px;color:#666">Generated: ${new Date().toLocaleDateString()} | Total: ${employees.length} employees</p>
    <table><thead><tr><th>ID</th><th>Name</th><th>Department</th><th>Role</th><th>Status</th><th>Salary</th><th>Date Joined</th></tr></thead>
    <tbody>${rows}</tbody></table></body></html>`;
  import('../../../lib/autoDownloadPdf').then(({ printHtmlInIframe }) => {
    printHtmlInIframe(html, 30000).catch(() => {});
  });
}

function download(filename: string, content: string, type: string) {
  const blob = new Blob([content], { type });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  a.click();
  URL.revokeObjectURL(url);
}

export default function ExportDropdown({ employees, onClose }: Props) {
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) onClose();
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [onClose]);

  const options = [
    { label: 'Export as PDF', icon: 'ri-file-pdf-line', color: 'text-red-600', action: () => { exportPDF(employees); onClose(); } },
    { label: 'Export as Excel', icon: 'ri-file-excel-line', color: 'text-green-600', action: () => { exportExcel(employees); onClose(); } },
    { label: 'Export as Word', icon: 'ri-file-word-line', color: 'text-blue-600', action: () => { exportWord(employees); onClose(); } },
  ];

  return (
    <div ref={ref} className="absolute right-0 top-full mt-1 bg-white border border-gray-200 rounded-xl shadow-xl z-50 w-48 py-1 overflow-hidden">
      {options.map(opt => (
        <button key={opt.label} onClick={opt.action}
          className="w-full flex items-center gap-3 px-4 py-2.5 text-sm text-gray-700 hover:bg-purple-50 cursor-pointer whitespace-nowrap transition-colors">
          <div className={`w-5 h-5 flex items-center justify-center ${opt.color}`}>
            <i className={`${opt.icon} text-base`}></i>
          </div>
          {opt.label}
        </button>
      ))}
    </div>
  );
}
