import { useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { Printer, ChevronLeft, Loader, AlertCircle } from 'lucide-react';
import { useHRStore, Payslip } from '../../store/hr';

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

const statusColor = (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 === 'calculated' || s === 'approved') return 'bg-blue-50 text-blue-700 border-blue-200 dark:bg-blue-900/20 dark:text-blue-300';
  if (s === 'draft' || s === 'pending') return 'bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-900/20 dark:text-amber-300';
  return 'bg-muted text-text-muted border-border';
};

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

interface LineItem {
  label: string;
  amount: number;
}

function EarningsTable({ items }: { items: LineItem[] }) {
  if (items.length === 0) return null;
  return (
    <div className="break-inside-avoid">
      <h4 className="text-[0.7rem] font-black uppercase tracking-widest text-text-muted mb-2 px-1">
        Earnings
      </h4>
      <table className="w-full text-sm border border-border rounded-xl overflow-hidden">
        <thead className="bg-muted/50">
          <tr>
            <th className="text-left px-4 py-2 font-bold">Item</th>
            <th className="text-right px-4 py-2 font-bold">Amount</th>
          </tr>
        </thead>
        <tbody>
          {items.map((it, i) => (
            <tr key={i} className="border-t border-border">
              <td className="px-4 py-2 text-text-secondary">{it.label}</td>
              <td className="px-4 py-2 text-right font-mono">{currency(it.amount)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function DeductionsTable({ items }: { items: LineItem[] }) {
  if (items.length === 0) return null;
  return (
    <div className="break-inside-avoid">
      <h4 className="text-[0.7rem] font-black uppercase tracking-widest text-text-muted mb-2 px-1">
        Deductions
      </h4>
      <table className="w-full text-sm border border-border rounded-xl overflow-hidden">
        <thead className="bg-muted/50">
          <tr>
            <th className="text-left px-4 py-2 font-bold">Item</th>
            <th className="text-right px-4 py-2 font-bold">Amount</th>
          </tr>
        </thead>
        <tbody>
          {items.map((it, i) => (
            <tr key={i} className="border-t border-border">
              <td className="px-4 py-2 text-text-secondary">{it.label}</td>
              <td className="px-4 py-2 text-right font-mono">{currency(it.amount)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

export default function PayslipView() {
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  const payslipId = id ? parseInt(id, 10) : NaN;

  const { currentPayslip: payslip, loading, error, fetchPayslip, resetPayslip } = useHRStore();

  useEffect(() => {
    if (!Number.isFinite(payslipId)) {
      navigate('/dashboard/hr');
      return;
    }
    fetchPayslip(payslipId);
    return () => { resetPayslip(); };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [payslipId]);

  if (loading && !payslip) {
    return (
      <div className="flex flex-col justify-center items-center h-[60vh] gap-4 text-text-muted">
        <Loader className="animate-spin" size={28} />
        <p>Loading payslip…</p>
      </div>
    );
  }

  if (error || !payslip) {
    return (
      <div className="flex flex-col justify-center items-center h-[60vh] gap-4">
        <AlertCircle size={48} className="text-red-500" />
        <p className="text-text-muted font-medium">{error || 'Payslip not found'}</p>
        <button
          onClick={() => navigate('/dashboard/hr')}
          className="px-4 py-2 bg-primary text-white rounded-xl"
        >
          Back to dashboard
        </button>
      </div>
    );
  }

  const p: Payslip = payslip;

  const earnings: LineItem[] = [
    { label: 'Basic salary', amount: p.basic_salary },
    { label: 'Housing allowance', amount: p.housing_allowance },
    { label: 'Transport allowance', amount: p.transport_allowance },
    { label: 'Medical allowance', amount: p.medical_allowance },
    { label: 'Other allowances', amount: p.other_allowances },
  ].filter((i) => Number(i.amount) > 0);

  const deductions: LineItem[] = [
    { label: 'Tax (PAYE)', amount: p.tax_deduction },
    { label: 'Pension contribution', amount: p.pension_deduction },
    { label: 'Other deductions', amount: p.other_deductions },
  ].filter((i) => Number(i.amount) > 0);

  return (
    <div className="space-y-6 animate-in fade-in duration-300 pb-10">
      {/* Top toolbar — hidden on print */}
      <div className="flex items-center justify-between print:hidden">
        <button
          onClick={() => navigate(-1)}
          className="flex items-center gap-1 text-sm font-bold text-text-muted hover:text-text"
        >
          <ChevronLeft size={16} /> Back
        </button>
        <button
          onClick={() => window.print()}
          className="flex items-center gap-2 px-5 py-2.5 rounded-xl bg-primary text-white text-sm font-bold hover:bg-primary-dark transition-all shadow-lg shadow-blue-900/10 active:scale-[0.98]"
        >
          <Printer size={16} /> Print payslip
        </button>
      </div>

      {/* Payslip card */}
      <div
        id="payslip"
        className="bg-card border border-border rounded-2xl shadow-sm overflow-hidden"
      >
        {/* Header band */}
        <div className="px-8 py-6 border-b border-border bg-muted/30 flex flex-col sm:flex-row sm:items-end sm:justify-between gap-4">
          <div>
            <p className="text-[0.65rem] font-black uppercase tracking-[3px] text-primary">
              Payslip
            </p>
            <h1 className="text-2xl font-black mt-1 text-text">
              {p.first_name} {p.last_name}
            </h1>
            <p className="text-sm text-text-muted mt-1">
              {p.designation || '—'} {p.department ? `· ${p.department}` : ''}
            </p>
            <p className="text-[0.7rem] text-text-muted mt-2 font-mono">
              Staff #: {p.staff_number || '—'} · Email: {p.email}
            </p>
          </div>
          <div className="text-right">
            <p className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted">
              Pay period
            </p>
            <p className="text-lg font-bold text-text">
              {monthName(p.period_month)} {p.period_year}
            </p>
            <span
              className={`inline-block mt-2 text-[0.6rem] font-black uppercase tracking-tight px-2.5 py-1 rounded-full border ${statusColor(
                p.status,
              )}`}
            >
              {p.status || 'unknown'}
            </span>
          </div>
        </div>

        {/* Summary tile */}
        <div className="grid grid-cols-1 sm:grid-cols-3 divide-y sm:divide-y-0 sm:divide-x divide-border border-b border-border">
          <div className="px-8 py-6">
            <p className="text-[0.6rem] uppercase font-black tracking-widest text-text-muted">
              Gross
            </p>
            <p className="text-2xl font-black text-emerald-600 mt-1">{currency(p.gross_salary)}</p>
          </div>
          <div className="px-8 py-6">
            <p className="text-[0.6rem] uppercase font-black tracking-widest text-text-muted">
              Total deductions
            </p>
            <p className="text-2xl font-black text-red-500 mt-1">−{currency(p.total_deductions)}</p>
          </div>
          <div className="px-8 py-6 bg-slate-900 text-white">
            <p className="text-[0.6rem] uppercase font-black tracking-widest text-white/60">
              Net pay
            </p>
            <p className="text-3xl font-black mt-1">{currency(p.net_salary)}</p>
            <p className="text-[0.6rem] text-white/60 mt-1">
              Run #{p.run_id} · Payslip #{p.id}
            </p>
          </div>
        </div>

        {/* Line items */}
        <div className="p-8 grid grid-cols-1 lg:grid-cols-2 gap-8">
          <EarningsTable items={earnings} />
          <DeductionsTable items={deductions} />
        </div>

        {/* Footer */}
        <div className="px-8 py-4 border-t border-border bg-muted/30 text-[0.65rem] text-text-muted italic flex flex-col sm:flex-row sm:justify-between gap-1">
          <span>
            Generated by NextGen HR · Payslip ID #{p.id} · UID {p.uid || '—'}
          </span>
          {p.paid_at && <span>Paid at: {new Date(p.paid_at).toLocaleString()}</span>}
        </div>
      </div>

      {/* Print stylesheet */}
      <style>{`
        @media print {
          body * { visibility: hidden; }
          #payslip, #payslip * { visibility: visible; }
          #payslip {
            position: absolute;
            inset: 0;
            margin: 0;
            box-shadow: none;
            border: none;
          }
          @page {
            size: A4;
            margin: 16mm;
          }
        }
      `}</style>
    </div>
  );
}
