'use client';
import { useState } from 'react';
import { payrollEmployees, PayrollEmployee, EmploymentStatus } from './payrollData';

const statusColors: Record<EmploymentStatus, string> = {
  Active: 'bg-green-100 text-green-700',
  'On Leave': 'bg-yellow-100 text-yellow-700',
  Terminated: 'bg-red-100 text-red-700',
};

export default function EmployeeMasterTab() {
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('All');
  const [selected, setSelected] = useState<PayrollEmployee | null>(null);

  const filtered = payrollEmployees.filter(e => {
    const matchSearch = e.fullName.toLowerCase().includes(search.toLowerCase()) || e.id.toLowerCase().includes(search.toLowerCase());
    const matchStatus = statusFilter === 'All' || e.status === statusFilter;
    return matchSearch && matchStatus;
  });

  return (
    <div className="space-y-5">
      <div className="flex flex-wrap gap-3 items-center justify-between">
        <div className="flex gap-3 flex-wrap">
          <div className="relative">
            <div className="w-4 h-4 flex items-center justify-center absolute left-3 top-1/2 -translate-y-1/2 text-gray-400">
              <i className="ri-search-line text-sm"></i>
            </div>
            <input className="pl-9 pr-3 py-2 border border-gray-200 rounded-lg text-sm w-64 focus:outline-none focus:ring-2 focus:ring-pink-300" placeholder="Search employee ID or name..." value={search} onChange={e => setSearch(e.target.value)} />
          </div>
          <div className="flex gap-2">
            {['All', 'Active', 'On Leave', 'Terminated'].map(s => (
              <button key={s} onClick={() => setStatusFilter(s)} className={`px-3 py-2 rounded-lg text-sm whitespace-nowrap cursor-pointer transition-all ${statusFilter === s ? 'bg-pink-600 text-white' : 'bg-white border border-gray-200 text-gray-600 hover:bg-gray-50'}`}>{s}</button>
            ))}
          </div>
        </div>
        <button className="flex items-center gap-2 px-4 py-2 bg-pink-600 text-white rounded-lg text-sm whitespace-nowrap cursor-pointer hover:bg-pink-700">
          <div className="w-4 h-4 flex items-center justify-center"><i className="ri-download-line text-sm"></i></div>
          Export to Payroll
        </button>
      </div>

      <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
        <table className="w-full text-sm">
          <thead>
            <tr className="bg-gray-50 border-b border-gray-200">
              <th className="text-left px-4 py-3 text-gray-600 font-semibold">Employee ID</th>
              <th className="text-left px-4 py-3 text-gray-600 font-semibold">Name</th>
              <th className="text-left px-4 py-3 text-gray-600 font-semibold">Department</th>
              <th className="text-left px-4 py-3 text-gray-600 font-semibold">Grade</th>
              <th className="text-left px-4 py-3 text-gray-600 font-semibold">Status</th>
              <th className="text-right px-4 py-3 text-gray-600 font-semibold">Basic Salary</th>
              <th className="text-right px-4 py-3 text-gray-600 font-semibold">Total Package</th>
              <th className="text-left px-4 py-3 text-gray-600 font-semibold">Bank</th>
              <th className="text-center px-4 py-3 text-gray-600 font-semibold">Actions</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map((emp, i) => {
              const totalAllowances = emp.housingAllowance + emp.transportAllowance + emp.otherAllowances.reduce((s, a) => s + a.amount, 0);
              const totalDeductions = emp.deductions.reduce((s, d) => s + d.amount, 0);
              const gross = emp.basicSalary + totalAllowances;
              return (
                <tr key={emp.id} className={`border-b border-gray-100 hover:bg-gray-50 ${i % 2 === 0 ? '' : 'bg-gray-50/30'}`}>
                  <td className="px-4 py-3 font-mono text-xs text-pink-700 font-semibold">{emp.id}</td>
                  <td className="px-4 py-3 font-medium text-gray-800">{emp.fullName}</td>
                  <td className="px-4 py-3 text-gray-600">{emp.department}</td>
                  <td className="px-4 py-3"><span className="px-2 py-0.5 bg-purple-100 text-purple-700 rounded text-xs font-semibold">{emp.grade}</span></td>
                  <td className="px-4 py-3"><span className={`px-2 py-0.5 rounded-full text-xs font-semibold ${statusColors[emp.status]}`}>{emp.status}</span></td>
                  <td className="px-4 py-3 text-right font-mono text-gray-700">{emp.basicSalary.toLocaleString()}</td>
                  <td className="px-4 py-3 text-right font-mono font-semibold text-gray-800">{gross.toLocaleString()}</td>
                  <td className="px-4 py-3 text-gray-600 text-xs">{emp.bankName}</td>
                  <td className="px-4 py-3 text-center">
                    <button onClick={() => setSelected(emp)} className="w-7 h-7 flex items-center justify-center mx-auto text-pink-600 hover:bg-pink-50 rounded cursor-pointer">
                      <i className="ri-eye-line"></i>
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        <div className="px-4 py-3 border-t border-gray-100 text-xs text-gray-500">
          Showing {filtered.length} of {payrollEmployees.length} employees
        </div>
      </div>

      {selected && (
        <div className="fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4" onClick={() => setSelected(null)}>
          <div className="bg-white rounded-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200">
              <div>
                <h3 className="font-bold text-gray-800 text-lg">{selected.fullName}</h3>
                <p className="text-sm text-gray-500">{selected.id} · {selected.position} · {selected.department}</p>
              </div>
              <button onClick={() => setSelected(null)} className="w-8 h-8 flex items-center justify-center rounded-lg hover:bg-gray-100 cursor-pointer text-gray-500"><i className="ri-close-line text-lg"></i></button>
            </div>
            <div className="p-6 space-y-5">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-xs text-gray-500 mb-1">Grade / Status</p>
                  <p className="font-semibold text-gray-700">{selected.grade} · <span className={`text-xs px-2 py-0.5 rounded-full ${statusColors[selected.status]}`}>{selected.status}</span></p>
                </div>
                <div>
                  <p className="text-xs text-gray-500 mb-1">Joining / Confirmation Date</p>
                  <p className="font-semibold text-gray-700">{selected.joiningDate} / {selected.confirmationDate}</p>
                </div>
                <div>
                  <p className="text-xs text-gray-500 mb-1">TIN Number</p>
                  <p className="font-semibold text-gray-700 font-mono">{selected.tin}</p>
                </div>
                <div>
                  <p className="text-xs text-gray-500 mb-1">National ID</p>
                  <p className="font-semibold text-gray-700 font-mono">{selected.nationalId}</p>
                </div>
              </div>
              <div className="bg-gray-50 rounded-xl p-4">
                <p className="text-xs font-semibold text-gray-500 uppercase mb-3">Bank Details</p>
                <div className="grid grid-cols-3 gap-3 text-sm">
                  <div><p className="text-xs text-gray-500">Bank</p><p className="font-medium">{selected.bankName}</p></div>
                  <div><p className="text-xs text-gray-500">Account No.</p><p className="font-mono font-medium">{selected.accountNumber}</p></div>
                  <div><p className="text-xs text-gray-500">Branch Code</p><p className="font-mono font-medium">{selected.branchCode}</p></div>
                </div>
              </div>
              <div>
                <p className="text-xs font-semibold text-gray-500 uppercase mb-3">Salary Structure (Effective {selected.effectiveDate})</p>
                <div className="space-y-2">
                  <div className="flex justify-between text-sm"><span className="text-gray-600">Basic Salary</span><span className="font-mono font-semibold">KES {selected.basicSalary.toLocaleString()}</span></div>
                  <div className="flex justify-between text-sm"><span className="text-gray-600">Housing Allowance</span><span className="font-mono">KES {selected.housingAllowance.toLocaleString()}</span></div>
                  <div className="flex justify-between text-sm"><span className="text-gray-600">Transport Allowance</span><span className="font-mono">KES {selected.transportAllowance.toLocaleString()}</span></div>
                  {selected.otherAllowances.map(a => (
                    <div key={a.name} className="flex justify-between text-sm"><span className="text-gray-600">{a.name}</span><span className="font-mono">KES {a.amount.toLocaleString()}</span></div>
                  ))}
                  <div className="border-t border-gray-200 pt-2 flex justify-between text-sm font-semibold">
                    <span className="text-green-700">Gross Earnings</span>
                    <span className="font-mono text-green-700">KES {(selected.basicSalary + selected.housingAllowance + selected.transportAllowance + selected.otherAllowances.reduce((s, a) => s + a.amount, 0)).toLocaleString()}</span>
                  </div>
                  {selected.deductions.map(d => (
                    <div key={d.name} className="flex justify-between text-sm"><span className="text-red-600">{d.name}</span><span className="font-mono text-red-600">- KES {d.amount.toLocaleString()}</span></div>
                  ))}
                  <div className="border-t border-gray-200 pt-2 flex justify-between text-sm font-bold">
                    <span className="text-gray-800">Net Pay</span>
                    <span className="font-mono text-gray-800">KES {(selected.basicSalary + selected.housingAllowance + selected.transportAllowance + selected.otherAllowances.reduce((s, a) => s + a.amount, 0) - selected.deductions.reduce((s, d) => s + d.amount, 0)).toLocaleString()}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
