'use client';
import { useState } from 'react';
import { TerminationRecord, TerminationCategory } from './terminationData';

const catColors: Record<TerminationCategory, string> = {
  Voluntary: 'bg-purple-100 text-purple-700',
  Involuntary: 'bg-red-100 text-red-700',
  Other: 'bg-gray-100 text-gray-600',
};

interface Props {
  records: TerminationRecord[];
  onSelectRecord: (r: TerminationRecord) => void;
  onNewTermination: () => void;
}

const PAGE_SIZES = [10, 25, 50, 100];

export default function TerminationRegisterTab({ records, onSelectRecord, onNewTermination }: Props) {
  const [search, setSearch] = useState('');
  const [filterCat, setFilterCat] = useState('All');
  const [pageSize, setPageSize] = useState(10);
  const [page, setPage] = useState(1);

  const filtered = records.filter(r => {
    const q = search.toLowerCase();
    const matchSearch = r.employeeName.toLowerCase().includes(q) || r.employeeId.toLowerCase().includes(q);
    const matchCat = filterCat === 'All' || r.category === filterCat;
    return matchSearch && matchCat;
  });

  const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
  const paginated = filtered.slice((page - 1) * pageSize, page * pageSize);

  const exportCSV = () => {
    const headers = ['Case No', 'Employee Name', 'Employee ID', 'Department', 'Position', 'Termination Date', 'Category', 'Reason', 'Supporting Letter'];
    const rows = filtered.map(r => [
      r.caseNo, r.employeeName, r.employeeId, r.department, r.position,
      r.terminationDate, r.category, r.reason, r.supportingLetter ? 'Yes' : 'No',
    ]);
    const csv = [headers, ...rows].map(row => row.map(v => `"${v}"`).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 = 'termination_register.csv'; a.click();
    URL.revokeObjectURL(url);
  };

  const exportPDF = () => {
    const content = filtered.map(r =>
      `${r.caseNo} | ${r.employeeName} | ${r.employeeId} | ${r.department} | ${r.terminationDate} | ${r.category} | ${r.reason}`
    ).join('\n');
    const blob = new Blob([`TERMINATION REGISTER\n\nCase No | Employee | ID | Department | Date | Category | Reason\n${'─'.repeat(80)}\n${content}`], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = 'termination_register.txt'; a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div>
      <div className="flex items-center justify-between gap-3 mb-5">
        <div className="flex gap-2 flex-wrap">
          {['All', 'Voluntary', 'Involuntary', 'Other'].map(c => (
            <button key={c} onClick={() => { setFilterCat(c); setPage(1); }}
              className={`px-3 py-1.5 rounded-lg text-xs font-medium cursor-pointer whitespace-nowrap border transition-all ${filterCat === c ? 'text-white border-transparent' : 'bg-white border-gray-200 text-gray-600 hover:border-pink-300'}`}
              style={filterCat === c ? { background: '#b828a0', borderColor: '#b828a0' } : {}}>
              {c}
            </button>
          ))}
        </div>
        <div className="flex gap-2">
          <button onClick={exportCSV}
            className="flex items-center gap-1.5 px-3 py-2 rounded-lg border border-gray-200 text-xs font-medium text-gray-600 hover:bg-gray-50 cursor-pointer whitespace-nowrap">
            <div className="w-4 h-4 flex items-center justify-center"><i className="ri-file-excel-line"></i></div>
            Export CSV
          </button>
          <button onClick={exportPDF}
            className="flex items-center gap-1.5 px-3 py-2 rounded-lg border border-gray-200 text-xs font-medium text-gray-600 hover:bg-gray-50 cursor-pointer whitespace-nowrap">
            <div className="w-4 h-4 flex items-center justify-center"><i className="ri-file-pdf-line"></i></div>
            Export PDF
          </button>
          <button onClick={onNewTermination}
            className="flex items-center gap-2 px-4 py-2 rounded-lg text-white text-sm font-semibold cursor-pointer whitespace-nowrap shadow"
            style={{ background: '#b828a0' }}>
            <div className="w-4 h-4 flex items-center justify-center"><i className="ri-add-line"></i></div>
            Initiate Termination
          </button>
        </div>
      </div>

      <div className="flex items-center gap-3 mb-4">
        <div className="relative flex-1">
          <div className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 flex items-center justify-center">
            <i className="ri-search-line text-gray-400 text-sm"></i>
          </div>
          <input value={search} onChange={e => { setSearch(e.target.value); setPage(1); }}
            placeholder="Search by employee name or ID…"
            className="w-full pl-9 pr-3 py-2 border border-gray-200 rounded-lg text-sm bg-white focus:outline-none focus:border-pink-400" />
        </div>
        <div className="flex items-center gap-2 text-xs text-gray-500">
          <span>Rows:</span>
          {PAGE_SIZES.map(s => (
            <button key={s} onClick={() => { setPageSize(s); setPage(1); }}
              className={`px-2.5 py-1 rounded border cursor-pointer ${pageSize === s ? 'text-white border-transparent' : 'border-gray-200 text-gray-600 hover:border-pink-300'}`}
              style={pageSize === s ? { background: '#b828a0' } : {}}>
              {s}
            </button>
          ))}
        </div>
      </div>

      <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-gray-100 bg-gray-50">
              <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500">EMPLOYEE NAME</th>
              <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500">EMPLOYEE ID</th>
              <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500">TERMINATION DATE</th>
              <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500">CATEGORY</th>
              <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500">REASON</th>
              <th className="text-left px-4 py-3 text-xs font-semibold text-gray-500">SUPPORTING LETTER</th>
              <th className="text-right px-4 py-3 text-xs font-semibold text-gray-500">ACTION</th>
            </tr>
          </thead>
          <tbody>
            {paginated.map(r => (
              <tr key={r.id} className="border-b border-gray-50 hover:bg-pink-50/30 transition-colors cursor-pointer" onClick={() => onSelectRecord(r)}>
                <td className="px-4 py-3">
                  <div className="font-medium text-gray-800">{r.employeeName}</div>
                  <div className="text-xs text-gray-400">{r.department} · {r.position}</div>
                </td>
                <td className="px-4 py-3 font-mono text-xs text-gray-500">{r.employeeId}</td>
                <td className="px-4 py-3 text-gray-600 text-xs">{r.terminationDate}</td>
                <td className="px-4 py-3">
                  <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${catColors[r.category]}`}>{r.category}</span>
                </td>
                <td className="px-4 py-3 text-gray-700 text-xs">{r.reason}</td>
                <td className="px-4 py-3">
                  {r.supportingLetter ? (
                    <button onClick={e => e.stopPropagation()}
                      className="flex items-center gap-1 text-xs text-blue-600 hover:underline cursor-pointer whitespace-nowrap">
                      <div className="w-4 h-4 flex items-center justify-center"><i className="ri-download-line"></i></div>
                      {r.supportingLetter}
                    </button>
                  ) : (
                    <span className="text-xs text-gray-400">—</span>
                  )}
                </td>
                <td className="px-4 py-3 text-right">
                  <button onClick={e => { e.stopPropagation(); onSelectRecord(r); }}
                    className="px-3 py-1 rounded-lg text-xs font-medium cursor-pointer whitespace-nowrap border border-pink-200 text-pink-700 hover:bg-pink-50">
                    View
                  </button>
                </td>
              </tr>
            ))}
            {paginated.length === 0 && (
              <tr><td colSpan={7} className="text-center py-10 text-gray-400">No records match your search.</td></tr>
            )}
          </tbody>
        </table>
      </div>

      <div className="flex items-center justify-between mt-4 text-xs text-gray-500">
        <span>Showing {Math.min((page - 1) * pageSize + 1, filtered.length)}–{Math.min(page * pageSize, filtered.length)} of {filtered.length} records</span>
        <div className="flex gap-1">
          <button onClick={() => setPage(p => Math.max(1, p - 1))} disabled={page === 1}
            className="px-3 py-1.5 rounded border border-gray-200 cursor-pointer disabled:opacity-40 hover:bg-gray-50">Prev</button>
          {Array.from({ length: totalPages }, (_, i) => i + 1).filter(p => p === 1 || p === totalPages || Math.abs(p - page) <= 1).map((p, i, arr) => (
            <span key={p}>
              {i > 0 && arr[i - 1] !== p - 1 && <span className="px-2">…</span>}
              <button onClick={() => setPage(p)}
                className={`px-3 py-1.5 rounded border cursor-pointer ${page === p ? 'text-white border-transparent' : 'border-gray-200 hover:bg-gray-50'}`}
                style={page === p ? { background: '#b828a0' } : {}}>
                {p}
              </button>
            </span>
          ))}
          <button onClick={() => setPage(p => Math.min(totalPages, p + 1))} disabled={page === totalPages}
            className="px-3 py-1.5 rounded border border-gray-200 cursor-pointer disabled:opacity-40 hover:bg-gray-50">Next</button>
        </div>
      </div>
    </div>
  );
}
