'use client';
import { useState } from 'react';
import { monthlyVariables, MonthlyVariable, VariableType } from './payrollData';

const typeColors: Record<VariableType, string> = {
  'New Hire': 'bg-blue-100 text-blue-700',
  'Termination': 'bg-red-100 text-red-700',
  'Salary Adjustment': 'bg-purple-100 text-purple-700',
  'Grade Change': 'bg-indigo-100 text-indigo-700',
  'Leave Without Pay': 'bg-orange-100 text-orange-700',
  'Bonus': 'bg-green-100 text-green-700',
  'Commission': 'bg-teal-100 text-teal-700',
  'Overtime': 'bg-yellow-100 text-yellow-700',
  'Advance Recovery': 'bg-gray-100 text-gray-700',
};

const typeIcons: Record<VariableType, string> = {
  'New Hire': 'ri-user-add-line',
  'Termination': 'ri-user-unfollow-line',
  'Salary Adjustment': 'ri-exchange-dollar-line',
  'Grade Change': 'ri-medal-line',
  'Leave Without Pay': 'ri-calendar-close-line',
  'Bonus': 'ri-gift-line',
  'Commission': 'ri-percent-line',
  'Overtime': 'ri-time-line',
  'Advance Recovery': 'ri-refund-line',
};

export default function MonthlyVariablesTab() {
  const [vars, setVars] = useState<MonthlyVariable[]>(monthlyVariables);
  const [typeFilter, setTypeFilter] = useState('All');
  const [showAddModal, setShowAddModal] = useState(false);
  const [newVar, setNewVar] = useState({ employeeId: '', employeeName: '', type: 'Bonus' as VariableType, amount: '', description: '', effectiveDate: '2026-04-30' });

  const filtered = typeFilter === 'All' ? vars : vars.filter(v => v.type === typeFilter);

  const totals = {
    additions: vars.filter(v => ['New Hire','Bonus','Commission','Overtime','Salary Adjustment','Grade Change'].includes(v.type) && v.status !== 'Excluded').reduce((s, v) => s + v.amount, 0),
    deductions: vars.filter(v => ['Leave Without Pay','Advance Recovery','Termination'].includes(v.type) && v.status !== 'Excluded').reduce((s, v) => s + v.amount, 0),
  };

  const toggle = (id: string) => {
    setVars(prev => prev.map(v => v.id === id ? { ...v, status: v.status === 'Included' ? 'Excluded' : 'Included' } : v));
  };

  const handleAdd = () => {
    if (!newVar.employeeName || !newVar.amount) return;
    const entry: MonthlyVariable = {
      id: `MV-${String(vars.length + 1).padStart(3, '0')}`,
      employeeId: newVar.employeeId || `EMP-XXXX`,
      employeeName: newVar.employeeName,
      type: newVar.type,
      amount: parseFloat(newVar.amount),
      description: newVar.description,
      effectiveDate: newVar.effectiveDate,
      status: 'Pending',
    };
    setVars(prev => [entry, ...prev]);
    setShowAddModal(false);
    setNewVar({ employeeId: '', employeeName: '', type: 'Bonus', amount: '', description: '', effectiveDate: '2026-04-30' });
  };

  return (
    <div className="space-y-5">
      <div className="grid grid-cols-3 gap-4">
        <div className="bg-white rounded-xl border border-gray-200 p-4">
          <p className="text-xs text-gray-500 mb-1">Total Additions</p>
          <p className="text-2xl font-bold text-green-600">KES {totals.additions.toLocaleString()}</p>
          <p className="text-xs text-gray-400 mt-1">Bonuses, OT, adjustments included</p>
        </div>
        <div className="bg-white rounded-xl border border-gray-200 p-4">
          <p className="text-xs text-gray-500 mb-1">Total Deductions</p>
          <p className="text-2xl font-bold text-red-600">KES {totals.deductions.toLocaleString()}</p>
          <p className="text-xs text-gray-400 mt-1">LWOP, advances, settlements</p>
        </div>
        <div className="bg-white rounded-xl border border-gray-200 p-4">
          <p className="text-xs text-gray-500 mb-1">Net Variable Impact</p>
          <p className="text-2xl font-bold text-gray-800">KES {(totals.additions - totals.deductions).toLocaleString()}</p>
          <p className="text-xs text-gray-400 mt-1">April 2026 payroll cycle</p>
        </div>
      </div>

      <div className="flex flex-wrap items-center justify-between gap-3">
        <div className="flex gap-2 flex-wrap">
          {['All', 'New Hire', 'Bonus', 'Overtime', 'Leave Without Pay', 'Salary Adjustment', 'Termination'].map(t => (
            <button key={t} onClick={() => setTypeFilter(t)} className={`px-3 py-1.5 rounded-lg text-xs whitespace-nowrap cursor-pointer transition-all ${typeFilter === t ? 'bg-pink-600 text-white' : 'bg-white border border-gray-200 text-gray-600 hover:bg-gray-50'}`}>{t}</button>
          ))}
        </div>
        <button onClick={() => setShowAddModal(true)} 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-add-line text-sm"></i></div>
          Add Variable
        </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">Type</th>
              <th className="text-left px-4 py-3 text-gray-600 font-semibold">Employee</th>
              <th className="text-left px-4 py-3 text-gray-600 font-semibold">Description</th>
              <th className="text-left px-4 py-3 text-gray-600 font-semibold">Effective Date</th>
              <th className="text-right px-4 py-3 text-gray-600 font-semibold">Amount (KES)</th>
              <th className="text-center px-4 py-3 text-gray-600 font-semibold">Include</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(v => (
              <tr key={v.id} className={`border-b border-gray-100 hover:bg-gray-50 ${v.status === 'Excluded' ? 'opacity-40' : ''}`}>
                <td className="px-4 py-3">
                  <span className={`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs font-semibold w-fit ${typeColors[v.type]}`}>
                    <i className={`${typeIcons[v.type]} text-xs`}></i>
                    {v.type}
                  </span>
                </td>
                <td className="px-4 py-3">
                  <p className="font-medium text-gray-800">{v.employeeName}</p>
                  <p className="text-xs text-gray-400 font-mono">{v.employeeId}</p>
                </td>
                <td className="px-4 py-3 text-gray-600 max-w-xs text-xs">{v.description}</td>
                <td className="px-4 py-3 text-gray-600">{v.effectiveDate}</td>
                <td className="px-4 py-3 text-right font-mono font-semibold text-gray-800">
                  {v.amount > 0 ? v.amount.toLocaleString() : <span className="text-red-500">Settlement</span>}
                </td>
                <td className="px-4 py-3 text-center">
                  <button onClick={() => toggle(v.id)} className={`w-10 h-5 rounded-full transition-all cursor-pointer relative ${v.status !== 'Excluded' ? 'bg-pink-500' : 'bg-gray-300'}`}>
                    <span className={`absolute top-0.5 w-4 h-4 rounded-full bg-white shadow transition-all ${v.status !== 'Excluded' ? 'right-0.5' : 'left-0.5'}`}></span>
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {showAddModal && (
        <div className="fixed inset-0 bg-black/40 z-50 flex items-center justify-center p-4" onClick={() => setShowAddModal(false)}>
          <div className="bg-white rounded-2xl w-full max-w-lg p-6" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between mb-5">
              <h3 className="font-bold text-gray-800 text-lg">Add Monthly Variable</h3>
              <button onClick={() => setShowAddModal(false)} 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="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Employee ID</label>
                  <input className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-pink-300" placeholder="EMP-00XXX" value={newVar.employeeId} onChange={e => setNewVar(p => ({ ...p, employeeId: e.target.value }))} />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Employee Name *</label>
                  <input className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-pink-300" placeholder="Full name" value={newVar.employeeName} onChange={e => setNewVar(p => ({ ...p, employeeName: e.target.value }))} />
                </div>
              </div>
              <div>
                <label className="block text-xs font-semibold text-gray-600 mb-1">Variable Type *</label>
                <div className="flex flex-wrap gap-2">
                  {(['Bonus','Overtime','Commission','Leave Without Pay','Salary Adjustment','Advance Recovery','New Hire','Termination','Grade Change'] as VariableType[]).map(t => (
                    <button key={t} onClick={() => setNewVar(p => ({ ...p, type: t }))} className={`px-2 py-1 rounded text-xs cursor-pointer whitespace-nowrap ${newVar.type === t ? 'bg-pink-600 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}>{t}</button>
                  ))}
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Amount (KES) *</label>
                  <input type="number" className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-pink-300" placeholder="0.00" value={newVar.amount} onChange={e => setNewVar(p => ({ ...p, amount: e.target.value }))} />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Effective Date</label>
                  <input type="date" className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-pink-300" value={newVar.effectiveDate} onChange={e => setNewVar(p => ({ ...p, effectiveDate: e.target.value }))} />
                </div>
              </div>
              <div>
                <label className="block text-xs font-semibold text-gray-600 mb-1">Description / Remarks</label>
                <textarea className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-pink-300 resize-none" rows={2} placeholder="Brief description..." value={newVar.description} onChange={e => setNewVar(p => ({ ...p, description: e.target.value }))} maxLength={200} />
              </div>
            </div>
            <div className="flex gap-3 mt-5">
              <button onClick={() => setShowAddModal(false)} className="flex-1 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 hover:bg-gray-50 cursor-pointer whitespace-nowrap">Cancel</button>
              <button onClick={handleAdd} className="flex-1 py-2 bg-pink-600 text-white rounded-lg text-sm hover:bg-pink-700 cursor-pointer whitespace-nowrap">Add Variable</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
