import { useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Wallet, AlertCircle, ChevronLeft, ChevronRight, Search, RefreshCw,
  Receipt, X, Calendar,
} from 'lucide-react';
import { useHRStore, Payslip } from '../../store/hr';
import { useAuthStore } from '../../store/auth';
import { Drawer } from '../../components/ui/Drawer';

const PAGE_SIZE = 25;

const currency = (n: number) =>
  new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 2 }).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 === 'calculated' || s === 'approved') return 'bg-blue-50 text-blue-700 border-blue-200 dark:bg-blue-900/20 dark:text-blue-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 Payslips() {
  const navigate = useNavigate();
  const { user } = useAuthStore();
  const {
    payslips,
    loading,
    error,
    fetchPayslips,
    fetchPayslip,
    currentPayslip,
    resetPayslip,
  } = useHRStore();

  const [search, setSearch] = useState('');
  const [periodFilter, setPeriodFilter] = useState('');
  const [page, setPage] = useState(0);
  const [opening, setOpening] = useState<number | null>(null);

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

  const filtered = useMemo(() => {
    return payslips.filter((p) => {
      const periodLabel = `${monthName(p.period_month)} ${p.period_year}`;
      if (periodFilter && `${p.period_year}-${String(p.period_month).padStart(2, '0')}` !== periodFilter) {
        return false;
      }
      if (!search.trim()) return true;
      const needle = search.toLowerCase();
      return (
        periodLabel.toLowerCase().includes(needle) ||
        (p.first_name || '').toLowerCase().includes(needle) ||
        (p.last_name || '').toLowerCase().includes(needle) ||
        (p.staff_number || '').toLowerCase().includes(needle)
      );
    });
  }, [payslips, search, periodFilter]);

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

  // distinct periods for the period dropdown
  const periods = useMemo(() => {
    const set = new Set<string>();
    payslips.forEach((p) => {
      set.add(`${p.period_year}-${String(p.period_month).padStart(2, '0')}`);
    });
    return Array.from(set).sort().reverse();
  }, [payslips]);

  const openDetail = async (id: number) => {
    setOpening(id);
    try {
      await fetchPayslip(id);
    } finally {
      setOpening(null);
    }
  };

  const closeDetail = () => {
    setOpening(null);
    resetPayslip();
  };

  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">Payslips</h1>
          <p className="text-text-muted mt-1 text-lg">
            {user && ['hr','bursar','principal','school_admin','systems_admin','accountant'].includes(user.role)
              ? 'Browse all staff payslips by period.'
              : 'Your own payslips, scoped to your account.'}
          </p>
        </div>
        <button
          onClick={() => fetchPayslips()}
          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>
      </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">
            <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" />
            <input
              type="text"
              placeholder="Search name, staff #, 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={periodFilter}
            onChange={(e) => { setPeriodFilter(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 periods</option>
            {periods.map((p) => {
              const [y, m] = p.split('-').map(Number);
              return (
                <option key={p} value={p}>{monthName(m)} {y}</option>
              );
            })}
          </select>
        </div>
        <p className="text-[0.65rem] mt-3 text-text-muted">
          {loading ? 'Loading…' : `${filtered.length} payslip${filtered.length === 1 ? '' : 's'}`}
        </p>
      </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">
                  Staff
                </th>
                <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 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((p) => (
                  <tr key={p.id} className="hover:bg-muted/40 transition-colors">
                    <td className="px-6 py-4">
                      <div>
                        <p className="text-[0.85rem] font-semibold text-text">
                          {p.first_name || ''} {p.last_name || ''}
                        </p>
                        <p className="text-[0.65rem] text-text-muted">
                          #{p.staff_number || p.staff_id}
                        </p>
                      </div>
                    </td>
                    <td className="px-6 py-4 text-[0.85rem] text-text-secondary whitespace-nowrap">
                      <span className="inline-flex items-center gap-1">
                        <Calendar size={12} />
                        {monthName(p.period_month)} {p.period_year}
                      </span>
                    </td>
                    <td className="px-6 py-4 text-right text-[0.85rem] font-bold text-text whitespace-nowrap">
                      {currency(Number(p.gross_salary))}
                    </td>
                    <td className="px-6 py-4 text-right text-[0.85rem] font-bold text-rose-500 whitespace-nowrap">
                      −{currency(Number(p.total_deductions))}
                    </td>
                    <td className="px-6 py-4 text-right text-[0.85rem] font-black text-emerald-600 whitespace-nowrap">
                      {currency(Number(p.net_salary))}
                    </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(p.status)}`}>
                        {p.status || 'unknown'}
                      </span>
                    </td>
                    <td className="px-6 py-4 text-right whitespace-nowrap">
                      <button
                        onClick={() => openDetail(p.id)}
                        disabled={opening === p.id}
                        className="p-2 rounded-lg hover:bg-primary hover:text-white text-text-muted transition-all disabled:opacity-40"
                        title="View payslip"
                        aria-label="View payslip"
                      >
                        <Receipt size={16} />
                      </button>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={7} className="px-6 py-10 text-center text-text-muted text-sm">
                    No payslips 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>

      {/* Detail drawer */}
      {currentPayslip && (
        <Drawer
          open={true}
          onClose={closeDetail}
          title={`${currentPayslip.first_name} ${currentPayslip.last_name}`}
          icon={Wallet}
          maxWidth="max-w-md"
          footer={
            <button
              onClick={() => {
                const id = currentPayslip.id;
                closeDetail();
                navigate(`/hr/payslips/${id}`);
              }}
              className="w-full flex items-center justify-center gap-2 px-4 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"
            >
              <Wallet size={14} /> Open full payslip view
            </button>
          }
        >
          <div className="px-6 py-5 space-y-3">
              <div className="grid grid-cols-3 gap-3">
                <Summary label="Gross" value={currency(Number(currentPayslip.gross_salary))} tone="emerald" />
                <Summary label="Deductions" value={`−${currency(Number(currentPayslip.total_deductions))}`} tone="rose" />
                <Summary label="Net" value={currency(Number(currentPayslip.net_salary))} tone="dark" />
              </div>

              <div className="bg-muted/30 rounded-2xl border border-border p-4">
                <p className="text-[0.6rem] uppercase font-black tracking-widest text-text-muted mb-2">Earnings</p>
                <Row label="Basic salary" value={Number(currentPayslip.basic_salary)} />
                <Row label="Housing allowance" value={Number(currentPayslip.housing_allowance)} />
                <Row label="Transport allowance" value={Number(currentPayslip.transport_allowance)} />
                <Row label="Medical allowance" value={Number(currentPayslip.medical_allowance)} />
                <Row label="Other allowances" value={Number(currentPayslip.other_allowances)} />
              </div>

              <div className="bg-muted/30 rounded-2xl border border-border p-4">
                <p className="text-[0.6rem] uppercase font-black tracking-widest text-text-muted mb-2">Deductions</p>
                <Row label="Tax (PAYE)" value={Number(currentPayslip.tax_deduction)} />
                <Row label="Pension contribution" value={Number(currentPayslip.pension_deduction)} />
                <Row label="Other deductions" value={Number(currentPayslip.other_deductions)} />
              </div>

              <button
                onClick={() => {
                  const id = currentPayslip.id;
                  closeDetail();
                  navigate(`/hr/payslips/${id}`);
                }}
                className="w-full flex items-center justify-center gap-2 px-4 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"
              >
                <Wallet size={14} /> Open full payslip view
              </button>
          </div>
      </Drawer>
      )}
    </div>
  );
}

function Row({ label, value }: { label: string; value: number }) {
  return (
    <div className="flex items-center justify-between py-1 text-sm">
      <span className="text-text-secondary">{label}</span>
      <span className="font-mono text-text">{currency(value)}</span>
    </div>
  );
}

function Summary({
  label,
  value,
  tone,
}: {
  label: string;
  value: string;
  tone: 'emerald' | 'rose' | 'dark';
}) {
  const toneCls =
    tone === 'emerald'
      ? 'bg-emerald-50 dark:bg-emerald-950/30 border-emerald-200 dark:border-emerald-900'
      : tone === 'rose'
      ? 'bg-rose-50 dark:bg-rose-950/30 border-rose-200 dark:border-rose-900'
      : 'bg-slate-900 text-white border-transparent';
  const valueCls =
    tone === 'dark' ? 'text-white' : tone === 'emerald' ? 'text-emerald-600' : 'text-rose-500';
  const labelCls = tone === 'dark' ? 'text-white/60' : 'text-text-muted';
  return (
    <div className={`p-3 rounded-xl border ${toneCls}`}>
      <p className={`text-[0.6rem] uppercase font-black tracking-widest ${labelCls}`}>{label}</p>
      <p className={`text-base font-black mt-1 ${valueCls}`}>{value}</p>
    </div>
  );
}