import { useEffect, useState } from 'react';
import { Play, CheckCircle, Trash2, Calendar, DollarSign } from 'lucide-react';
import toast from 'react-hot-toast';
import api from '../api/axios';
import { formatCurrency, statusColors } from '../utils/format';

const MONTHS = [
  'January', 'February', 'March', 'April', 'May', 'June',
  'July', 'August', 'September', 'October', 'November', 'December',
];

export default function Payroll() {
  const now = new Date();
  const [month, setMonth] = useState(now.getMonth() + 1);
  const [year, setYear] = useState(now.getFullYear());
  const [payrolls, setPayrolls] = useState([]);
  const [summary, setSummary] = useState(null);
  const [loading, setLoading] = useState(true);
  const [generating, setGenerating] = useState(false);

  const load = () => {
    setLoading(true);
    Promise.all([
      api.get('/payrolls', { params: { month, year } }),
      api.get('/payrolls/summary', { params: { month, year } }),
    ])
      .then(([pRes, sRes]) => {
        setPayrolls(pRes.data);
        setSummary(sRes.data);
      })
      .finally(() => setLoading(false));
  };

  useEffect(() => { load(); }, [month, year]);

  const handleGenerate = async () => {
    setGenerating(true);
    try {
      const { data } = await api.post('/payrolls/generate', { month, year });
      toast.success(data.message);
      load();
    } catch (err) {
      toast.error(err.response?.data?.message || 'Generation failed');
    } finally {
      setGenerating(false);
    }
  };

  const markPaid = async (id) => {
    try {
      await api.patch(`/payrolls/${id}/status`, { status: 'paid' });
      toast.success('Marked as paid');
      load();
    } catch (err) {
      toast.error(err.response?.data?.message || 'Error');
    }
  };

  const handleDelete = async (id) => {
    if (!confirm('Delete this payroll record?')) return;
    try {
      await api.delete(`/payrolls/${id}`);
      toast.success('Deleted');
      load();
    } catch (err) {
      toast.error(err.response?.data?.message || 'Cannot delete');
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
        <div>
          <h1 className="font-display text-2xl font-bold text-slate-800">Payroll</h1>
          <p className="text-slate-500">Process and track monthly salary payments</p>
        </div>
        <div className="flex flex-wrap items-center gap-3">
          <select className="input-field w-auto" value={month} onChange={(e) => setMonth(Number(e.target.value))}>
            {MONTHS.map((m, i) => (
              <option key={m} value={i + 1}>{m}</option>
            ))}
          </select>
          <select className="input-field w-auto" value={year} onChange={(e) => setYear(Number(e.target.value))}>
            {[2024, 2025, 2026, 2027].map((y) => (
              <option key={y} value={y}>{y}</option>
            ))}
          </select>
          <button onClick={handleGenerate} disabled={generating} className="btn-primary">
            <Play className="h-4 w-4" />
            {generating ? 'Generating...' : 'Generate Payroll'}
          </button>
        </div>
      </div>

      {summary && (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
          {[
            { icon: Calendar, label: 'Records', value: summary.count, color: 'from-brand-500 to-brand-600' },
            { icon: DollarSign, label: 'Total Gross', value: formatCurrency(summary.totalGross), color: 'from-violet-500 to-purple-600' },
            { icon: DollarSign, label: 'Total Net', value: formatCurrency(summary.totalNet), color: 'from-emerald-500 to-teal-600' },
            { icon: CheckCircle, label: 'Paid', value: `${summary.paidCount} / ${summary.count}`, color: 'from-amber-500 to-orange-500' },
          ].map(({ icon: Icon, label, value, color }) => (
            <div key={label} className={`rounded-2xl bg-gradient-to-br ${color} p-5 text-white shadow-lg`}>
              <Icon className="mb-2 h-5 w-5 opacity-80" />
              <p className="text-sm text-white/80">{label}</p>
              <p className="font-display text-xl font-bold">{value}</p>
            </div>
          ))}
        </div>
      )}

      <div className="card overflow-hidden p-0">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-slate-50">
              <tr className="text-left text-slate-500">
                <th className="px-6 py-4 font-medium">Employee</th>
                <th className="px-6 py-4 font-medium">Department</th>
                <th className="px-6 py-4 font-medium">Gross</th>
                <th className="px-6 py-4 font-medium">Deductions</th>
                <th className="px-6 py-4 font-medium">Net Pay</th>
                <th className="px-6 py-4 font-medium">Status</th>
                <th className="px-6 py-4 font-medium">Actions</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr><td colSpan={7} className="px-6 py-12 text-center text-slate-400">Loading...</td></tr>
              ) : payrolls.length === 0 ? (
                <tr>
                  <td colSpan={7} className="px-6 py-12 text-center">
                    <p className="text-slate-400">No payroll for this period</p>
                    <button onClick={handleGenerate} className="mt-2 text-brand-600 font-medium hover:underline">
                      Generate payroll now
                    </button>
                  </td>
                </tr>
              ) : (
                payrolls.map((p) => (
                  <tr key={p._id} className="border-t border-slate-100 hover:bg-slate-50/50">
                    <td className="px-6 py-4">
                      <p className="font-medium text-slate-800">
                        {p.employee?.firstName} {p.employee?.lastName}
                      </p>
                      <p className="text-xs text-slate-400">{p.employee?.employeeId}</p>
                    </td>
                    <td className="px-6 py-4 text-slate-600">{p.employee?.department?.name || '—'}</td>
                    <td className="px-6 py-4">{formatCurrency(p.grossPay)}</td>
                    <td className="px-6 py-4 text-red-600">-{formatCurrency(p.deductions)}</td>
                    <td className="px-6 py-4 font-bold text-emerald-600">{formatCurrency(p.netPay)}</td>
                    <td className="px-6 py-4">
                      <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium capitalize ${statusColors[p.status]}`}>
                        {p.status}
                      </span>
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex gap-2">
                        {p.status !== 'paid' && (
                          <button
                            onClick={() => markPaid(p._id)}
                            className="rounded-lg p-2 text-emerald-600 hover:bg-emerald-50"
                            title="Mark as paid"
                          >
                            <CheckCircle className="h-4 w-4" />
                          </button>
                        )}
                        {p.status !== 'paid' && (
                          <button
                            onClick={() => handleDelete(p._id)}
                            className="rounded-lg p-2 text-slate-400 hover:bg-red-50 hover:text-red-600"
                          >
                            <Trash2 className="h-4 w-4" />
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
