import { useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Wallet, AlertCircle, Plus, RefreshCw, ChevronLeft, ChevronRight,
  Calculator, CreditCard, XCircle, Receipt, Loader2, Calendar,
} from 'lucide-react';
import { useFinanceStore } from '../../store/finance';
import { Modal, ModalBody } from '../../components/ui/Modal';

const PAGE_SIZE = 20;

const currency = (n: number) =>
  new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 }).format(
    Number.isFinite(n) ? n : 0,
  );

const statusBadge = (status: string) => {
  const s = status.toLowerCase();
  if (s === 'paid') return 'bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-900/20 dark:text-emerald-300';
  if (s === 'approved') return 'bg-blue-50 text-blue-700 border-blue-200 dark:bg-blue-900/20 dark:text-blue-300';
  if (s === 'calculated') return 'bg-indigo-50 text-indigo-700 border-indigo-200 dark:bg-indigo-900/20 dark:text-indigo-300';
  if (s === 'cancelled') return 'bg-rose-50 text-rose-700 border-rose-200 dark:bg-rose-900/20 dark:text-rose-300';
  return 'bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-900/20 dark:text-amber-300';
};

const monthName = (m: number) =>
  ['January','February','March','April','May','June','July','August','September','October','November','December'][
    Math.max(0, Math.min(11, m - 1))
  ] || `M${m}`;

export default function PayrollRuns() {
  const navigate = useNavigate();
  const {
    payrollRuns,
    loading,
    error,
    fetchPayrollRuns,
    createPayrollRun,
    calculatePayroll,
    payPayrollRun,
    cancelPayrollRun,
  } = useFinanceStore();

  const [status, setStatus] = useState('');
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(0);
  const [busy, setBusy] = useState<number | null>(null);
  const [showCreate, setShowCreate] = useState(false);
  const [banner, setBanner] = useState<{ kind: 'ok' | 'err'; msg: string } | null>(null);

  const [createForm, setCreateForm] = useState({
    period_month: new Date().getMonth() + 1,
    period_year: new Date().getFullYear(),
    description: '',
  });

  useEffect(() => {
    fetchPayrollRuns();
  }, [fetchPayrollRuns]);

  const filtered = useMemo(() => {
    return payrollRuns.filter((r) => {
      if (status && r.status !== status) return false;
      if (!search.trim()) return true;
      const needle = search.toLowerCase();
      const periodLabel = `${monthName(r.period_month)} ${r.period_year}`.toLowerCase();
      return (
        periodLabel.includes(needle) ||
        (r.description || '').toLowerCase().includes(needle)
      );
    });
  }, [payrollRuns, status, search]);

  const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
  const pageRows = filtered.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE);

  const onCreate = async (e: React.FormEvent) => {
    e.preventDefault();
    setBusy(-1);
    setBanner(null);
    try {
      await createPayrollRun(createForm);
      setBanner({ kind: 'ok', msg: `Created payroll run for ${monthName(createForm.period_month)} ${createForm.period_year}.` });
      setShowCreate(false);
    } catch (err: any) {
      setBanner({ kind: 'err', msg: err?.response?.data?.error || err?.message || 'Failed to create payroll run.' });
    } finally {
      setBusy(null);
    }
  };

  const run = async (id: number, action: 'calculate' | 'pay' | 'cancel') => {
    setBusy(id);
    setBanner(null);
    try {
      if (action === 'calculate') await calculatePayroll(id);
      else if (action === 'pay') await payPayrollRun(id);
      else await cancelPayrollRun(id);
      setBanner({ kind: 'ok', msg: `Run #${id} ${action}d.` });
    } catch (err: any) {
      setBanner({ kind: 'err', msg: err?.response?.data?.error || err?.message || `Failed to ${action} run.` });
    } finally {
      setBusy(null);
    }
  };

  return (
    <div className="space-y-6 animate-in fade-in duration-300 pb-10">
      <div className="flex flex-col md:flex-row md:items-end justify-between gap-4">
        <div>
          <h1 className="text-3xl font-extrabold text-text tracking-tight">Payroll Runs</h1>
          <p className="text-text-muted mt-1 text-lg">
            Bursar's view of monthly payroll — data lives in HR's controller.
          </p>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={() => fetchPayrollRuns()}
            className="flex items-center gap-2 px-4 py-2 rounded-xl border border-border text-text text-sm font-bold hover:bg-muted transition-all"
          >
            <RefreshCw size={16} /> Refresh
          </button>
          <button
            onClick={() => setShowCreate(true)}
            className="flex items-center gap-2 bg-primary hover:bg-primary-dark text-white px-5 py-2.5 rounded-xl font-semibold transition-all shadow-lg shadow-blue-900/10 active:scale-[0.98]"
          >
            <Plus size={18} />
            <span>New Run</span>
          </button>
        </div>
      </div>

      {/* Filters */}
      <div className="bg-card rounded-2xl border border-border p-5 shadow-sm">
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
          <div className="relative sm:col-span-2">
            <Receipt size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" />
            <input
              type="text"
              placeholder="Search description or period…"
              value={search}
              onChange={(e) => { setSearch(e.target.value); setPage(0); }}
              className="w-full pl-9 pr-3 py-2.5 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30"
            />
          </div>
          <select
            value={status}
            onChange={(e) => { setStatus(e.target.value); setPage(0); }}
            className="px-3 py-2.5 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30"
          >
            <option value="">All statuses</option>
            <option value="draft">Draft</option>
            <option value="calculated">Calculated</option>
            <option value="approved">Approved</option>
            <option value="paid">Paid</option>
            <option value="cancelled">Cancelled</option>
          </select>
        </div>
        <p className="text-[0.65rem] mt-3 text-text-muted">
          {loading ? 'Loading…' : `${filtered.length} payroll run${filtered.length === 1 ? '' : 's'}`}
        </p>
      </div>

      {banner && (
        <div
          className={`rounded-2xl border p-4 flex items-center gap-3 text-sm ${
            banner.kind === 'ok'
              ? 'bg-emerald-50 border-emerald-200 text-emerald-700 dark:bg-emerald-950/30 dark:border-emerald-900 dark:text-emerald-300'
              : 'bg-red-50 border-red-200 text-red-700 dark:bg-red-950/30 dark:border-red-900 dark:text-red-300'
          }`}
        >
          {banner.kind === 'ok' ? <Calculator size={18} /> : <AlertCircle size={18} />}
          <span className="flex-1">{banner.msg}</span>
          <button onClick={() => setBanner(null)} className="text-xs font-bold underline">Dismiss</button>
        </div>
      )}

      {error && (
        <div className="bg-red-50 dark:bg-red-950/30 border border-red-200 dark:border-red-900 rounded-2xl p-4 flex items-center gap-3 text-red-700 dark:text-red-300">
          <AlertCircle size={18} />
          <span className="text-sm">{error}</span>
        </div>
      )}

      <div className="bg-card rounded-2xl border border-border overflow-hidden shadow-sm">
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead className="bg-muted/80 border-b border-border">
              <tr>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">
                  Period
                </th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">
                  Description
                </th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">
                  Gross
                </th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">
                  Deductions
                </th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">
                  Net
                </th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">
                  Status
                </th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {pageRows.length > 0 ? (
                pageRows.map((r) => (
                  <tr key={r.id} className="hover:bg-muted/40 transition-colors">
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="flex items-center gap-2">
                        <div className="p-1.5 rounded-md bg-primary/10 text-primary">
                          <Calendar size={14} />
                        </div>
                        <div>
                          <p className="text-[0.85rem] font-semibold text-text">
                            {monthName(r.period_month)} {r.period_year}
                          </p>
                          <p className="text-[0.65rem] text-text-muted">Run #{r.id}</p>
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4 text-[0.85rem] text-text-secondary max-w-xs truncate">
                      {r.description || '—'}
                    </td>
                    <td className="px-6 py-4 text-right text-[0.85rem] font-bold text-text whitespace-nowrap">
                      {currency(Number(r.total_gross))}
                    </td>
                    <td className="px-6 py-4 text-right text-[0.85rem] font-bold text-rose-500 whitespace-nowrap">
                      −{currency(Number(r.total_deductions))}
                    </td>
                    <td className="px-6 py-4 text-right text-[0.85rem] font-black text-emerald-600 whitespace-nowrap">
                      {currency(Number(r.total_net))}
                    </td>
                    <td className="px-6 py-4">
                      <span className={`text-[0.6rem] font-black uppercase tracking-tight px-2 py-1 rounded-full border ${statusBadge(r.status)}`}>
                        {r.status}
                      </span>
                    </td>
                    <td className="px-6 py-4 text-right whitespace-nowrap">
                      <div className="inline-flex items-center gap-1">
                        {r.status === 'draft' && (
                          <button
                            onClick={() => run(r.id, 'calculate')}
                            disabled={busy === r.id}
                            className="p-2 rounded-lg hover:bg-indigo-500 hover:text-white text-indigo-500 disabled:opacity-40 transition-all"
                            title="Calculate"
                            aria-label="Calculate payroll"
                          >
                            {busy === r.id ? <Loader2 size={16} className="animate-spin" /> : <Calculator size={16} />}
                          </button>
                        )}
                        {(r.status === 'calculated' || r.status === 'approved') && (
                          <button
                            onClick={() => run(r.id, 'pay')}
                            disabled={busy === r.id}
                            className="p-2 rounded-lg hover:bg-emerald-500 hover:text-white text-emerald-600 disabled:opacity-40 transition-all"
                            title="Mark paid"
                            aria-label="Mark payroll as paid"
                          >
                            {busy === r.id ? <Loader2 size={16} className="animate-spin" /> : <CreditCard size={16} />}
                          </button>
                        )}
                        {r.status !== 'paid' && r.status !== 'cancelled' && (
                          <button
                            onClick={() => run(r.id, 'cancel')}
                            disabled={busy === r.id}
                            className="p-2 rounded-lg hover:bg-rose-500 hover:text-white text-rose-500 disabled:opacity-40 transition-all"
                            title="Cancel"
                            aria-label="Cancel payroll run"
                          >
                            <XCircle size={16} />
                          </button>
                        )}
                        <button
                          onClick={() => navigate('/finance/payslips')}
                          className="p-2 rounded-lg hover:bg-primary hover:text-white text-text-muted transition-all"
                          title="View payslips"
                          aria-label="View payslips"
                        >
                          <Wallet size={16} />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={7} className="px-6 py-10 text-center text-text-muted text-sm">
                    No payroll runs match the current filters.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>

        <div className="px-6 py-4 border-t border-border bg-muted/30 flex items-center justify-between">
          <span className="text-[0.7rem] font-bold text-text-muted">
            Page {page + 1} of {totalPages}
          </span>
          <div className="inline-flex items-center gap-2">
            <button
              disabled={page === 0}
              onClick={() => setPage((p) => Math.max(0, p - 1))}
              className="flex items-center gap-1 px-3 py-1.5 rounded-lg border border-border bg-card text-xs font-bold disabled:opacity-40 hover:bg-muted transition-all"
            >
              <ChevronLeft size={14} /> Prev
            </button>
            <button
              disabled={page + 1 >= totalPages}
              onClick={() => setPage((p) => p + 1)}
              className="flex items-center gap-1 px-3 py-1.5 rounded-lg border border-border bg-card text-xs font-bold disabled:opacity-40 hover:bg-muted transition-all"
            >
              Next <ChevronRight size={14} />
            </button>
          </div>
        </div>
      </div>

      {showCreate && (
        <Modal
          open={true}
          onClose={() => setShowCreate(false)}
          title="New payroll run"
          icon={Plus}
          maxWidth="max-w-md"
          footer={
            <>
              <button type="button" onClick={() => setShowCreate(false)} disabled={busy === -1} className="px-4 py-2 rounded-xl border border-border text-text text-sm font-bold hover:bg-muted transition-all">Cancel</button>
              <button type="submit" form="payroll-run-form" disabled={busy === -1} className="flex items-center gap-2 px-4 py-2 rounded-xl bg-primary text-white text-sm font-bold hover:bg-primary-dark disabled:opacity-40 transition-all">
                {busy === -1 ? <Loader2 size={14} className="animate-spin" /> : <Plus size={14} />}
                <span>Create</span>
              </button>
            </>
          }
        >
          <ModalBody>
            <form id="payroll-run-form" onSubmit={onCreate}>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs font-bold uppercase tracking-wider text-text-muted mb-1">Month</label>
                  <select value={createForm.period_month} onChange={(e) => setCreateForm({ ...createForm, period_month: Number(e.target.value) })} className="w-full px-3 py-2 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30">
                    {Array.from({ length: 12 }, (_, i) => i + 1).map((m) => (
                      <option key={m} value={m}>{monthName(m)}</option>
                    ))}
                  </select>
                </div>
                <div>
                  <label className="block text-xs font-bold uppercase tracking-wider text-text-muted mb-1">Year</label>
                  <input type="number" min={2000} max={2100} value={createForm.period_year} onChange={(e) => setCreateForm({ ...createForm, period_year: Number(e.target.value) })} className="w-full px-3 py-2 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30" />
                </div>
              </div>
              <div className="mt-3">
                <label className="block text-xs font-bold uppercase tracking-wider text-text-muted mb-1">
                  Description (optional)
                </label>
                <input type="text" value={createForm.description} onChange={(e) => setCreateForm({ ...createForm, description: e.target.value })} placeholder="e.g. July 2026 salaries" className="w-full px-3 py-2 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30" />
              </div>
            </form>
          </ModalBody>
        </Modal>
      )}
    </div>
  );
}