"use client";

import * as React from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import type { ColumnDef } from "@tanstack/react-table";
import { Check, Coins, Undo2, X } from "lucide-react";
import { DataTable, FilterSelect } from "@/components/ui/data-table";
import { StatusBadge } from "@/components/ui/badge";
import { Money } from "@/components/ui/money";
import { Button } from "@/components/ui/button";
import { Avatar } from "@/components/ui/primitives";
import { useConfirm } from "@/components/ui/confirm";
import { fmtDate, fmtDateTime } from "@/lib/dates";
import { COMMISSION_STATUSES, COMMISSION_STATUS_META } from "@/lib/domain";
import { updateCommissionStatus } from "@/lib/actions/commissions";

export interface CommissionRow {
  id: string;
  code: string;
  amount: number;
  status: string;
  triggerEvent: string;
  createdAt: string;
  approvedAt: string | null;
  paidAt: string | null;
  adminNotes: string | null;
  worker: { id: string; fullName: string };
  reservation: { id: string; code: string; checkIn: string; status: string; customer: string; apartment: string };
  approvedBy: string | null;
}

export function CommissionsTable({ rows, workers, currency, canManage, initialStatus, initialWorker, mode }: { rows: CommissionRow[]; workers: { id: string; fullName: string }[]; currency: string; canManage: boolean; initialStatus: string; initialWorker: string; mode: "admin" | "worker" }) {
  const router = useRouter();
  const confirm = useConfirm();
  const [status, setStatus] = React.useState(initialStatus);
  const [worker, setWorker] = React.useState(initialWorker);
  const data = rows.filter((r) => (!status || r.status === status) && (!worker || r.worker.id === worker));

  async function act(ids: string[], next: "APPROVED" | "PAID" | "CANCELLED" | "REVERSED" | "PENDING", clear?: () => void) {
    const needsNote = next === "CANCELLED" || next === "REVERSED";
    const { ok, reason } = await confirm({
      title: `${next === "APPROVED" ? "Approve" : next === "PAID" ? "Mark as paid" : next === "CANCELLED" ? "Cancel" : next === "REVERSED" ? "Reverse" : "Reopen"} ${ids.length} commission${ids.length > 1 ? "s" : ""}?`,
      description: next === "PAID" ? "Workers are notified that their commission was paid out." : next === "REVERSED" ? "Use this when a paid commission must be clawed back. The record is kept." : undefined,
      destructive: needsNote,
      requireReason: needsNote,
      confirmLabel: "Confirm",
    });
    if (!ok) return;
    const res = await updateCommissionStatus(ids, next, reason);
    if (!res.ok) return toast.error(res.error);
    toast.success(`${res.data.updated} commission${res.data.updated === 1 ? "" : "s"} updated`);
    clear?.();
    router.refresh();
  }

  const cols = React.useMemo<ColumnDef<CommissionRow, unknown>[]>(
    () => [
      { accessorKey: "code", header: "Commission", cell: ({ row }) => <span className="font-mono text-xs">{row.original.code}</span> },
      ...(mode === "admin" ? [{ id: "worker", accessorFn: (r: CommissionRow) => r.worker.fullName, header: "Worker", cell: ({ row }: { row: { original: CommissionRow } }) => <Link href={`/workers/${row.original.worker.id}`} className="flex items-center gap-2 text-sm font-medium hover:text-primary"><Avatar name={row.original.worker.fullName} size="xs" />{row.original.worker.fullName}</Link> } as ColumnDef<CommissionRow, unknown>] : []),
      {
        id: "reservation",
        accessorFn: (r) => r.reservation.code,
        header: "Reservation",
        cell: ({ row }) => (
          <div className="min-w-0">
            <Link href={`/reservations/${row.original.reservation.id}`} className="font-mono text-xs font-semibold hover:text-primary">
              {row.original.reservation.code}
            </Link>
            <span className="block truncate text-xs text-fg-muted">
              {row.original.reservation.customer} · {row.original.reservation.apartment} · {fmtDate(row.original.reservation.checkIn, { style: "short" })}
            </span>
          </div>
        ),
      },
      { id: "resStatus", accessorFn: (r) => r.reservation.status, header: "Res. status", cell: ({ row }) => <StatusBadge status={row.original.reservation.status} size="sm" /> },
      { accessorKey: "amount", header: "Amount", meta: { align: "right" }, cell: ({ row }) => <Money value={row.original.amount} currency={currency} className="font-semibold" /> },
      { accessorKey: "status", header: "Status", cell: ({ row }) => <StatusBadge status={row.original.status} size="sm" /> },
      {
        accessorKey: "createdAt",
        header: "Timeline",
        cell: ({ row }) => (
          <span className="block text-2xs text-fg-muted">
            Created {fmtDate(row.original.createdAt, { style: "short" })}
            {row.original.approvedAt ? ` · approved ${fmtDate(row.original.approvedAt, { style: "short" })}${row.original.approvedBy ? ` by ${row.original.approvedBy.split(" ")[0]}` : ""}` : ""}
            {row.original.paidAt ? ` · paid ${fmtDate(row.original.paidAt, { style: "short" })}` : ""}
            {row.original.adminNotes ? <span className="block italic">“{row.original.adminNotes}”</span> : null}
          </span>
        ),
      },
      ...(canManage
        ? [
            {
              id: "actions",
              header: "",
              enableHiding: false,
              cell: ({ row }: { row: { original: CommissionRow } }) => {
                const c = row.original;
                return (
                  <span className="flex justify-end gap-0.5">
                    {c.status === "PENDING" ? (
                      <Button size="iconXs" variant="ghost" className="text-positive-600" title="Approve" onClick={() => act([c.id], "APPROVED")}>
                        <Check />
                      </Button>
                    ) : null}
                    {c.status === "APPROVED" ? (
                      <Button size="iconXs" variant="ghost" className="text-positive-600" title="Mark paid" onClick={() => act([c.id], "PAID")}>
                        <Coins />
                      </Button>
                    ) : null}
                    {c.status === "PENDING" || c.status === "APPROVED" ? (
                      <Button size="iconXs" variant="ghost" className="text-negative-600" title="Cancel" onClick={() => act([c.id], "CANCELLED")}>
                        <X />
                      </Button>
                    ) : null}
                    {c.status === "PAID" ? (
                      <Button size="iconXs" variant="ghost" className="text-negative-600" title="Reverse" onClick={() => act([c.id], "REVERSED")}>
                        <Undo2 />
                      </Button>
                    ) : null}
                    {c.status === "CANCELLED" ? (
                      <Button size="iconXs" variant="ghost" title="Reopen" onClick={() => act([c.id], "PENDING")}>
                        <Undo2 />
                      </Button>
                    ) : null}
                  </span>
                );
              },
            } as ColumnDef<CommissionRow, unknown>,
          ]
        : []),
    ],
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [currency, canManage, mode]
  );

  return (
    <DataTable
      columns={cols}
      data={data}
      globalFilterFn={(r, q) => [r.code, r.worker.fullName, r.reservation.code, r.reservation.customer].join(" ").toLowerCase().includes(q)}
      searchPlaceholder="Worker, reservation, customer…"
      exportName={mode === "admin" ? "commissions" : undefined}
      initialSorting={[{ id: "createdAt", desc: true }]}
      selectable={canManage}
      bulkActions={(sel, clear) => {
        const ids = sel.map((s) => s.id);
        const st = new Set(sel.map((s) => s.status));
        return (
          <>
            {st.has("PENDING") ? (
              <Button size="xs" onClick={() => act(sel.filter((s) => s.status === "PENDING").map((s) => s.id), "APPROVED", clear)}>
                <Check /> Approve
              </Button>
            ) : null}
            {st.has("APPROVED") ? (
              <Button size="xs" onClick={() => act(sel.filter((s) => s.status === "APPROVED").map((s) => s.id), "PAID", clear)}>
                <Coins /> Mark paid
              </Button>
            ) : null}
            <Button size="xs" variant="ghost" onClick={() => act(ids, "CANCELLED", clear)}>
              Cancel
            </Button>
          </>
        );
      }}
      emptyTitle="No commissions"
      emptyDescription={mode === "worker" ? "Commissions appear here when reservations you create become eligible." : "Commissions are generated automatically when worker reservations become eligible."}
      toolbar={
        <>
          <FilterSelect value={status} onChange={setStatus} placeholder="All statuses" options={COMMISSION_STATUSES.map((s) => ({ value: s, label: COMMISSION_STATUS_META[s].label }))} />
          {mode === "admin" ? <FilterSelect value={worker} onChange={setWorker} placeholder="All workers" options={workers.map((w) => ({ value: w.id, label: w.fullName }))} /> : null}
        </>
      }
      mobileCard={(c) => (
        <Link href={`/reservations/${c.reservation.id}`} className="flex items-center gap-3 rounded-lg border border-border bg-surface p-3">
          <span className="min-w-0 flex-1">
            <span className="block text-sm font-medium">
              {c.reservation.code} · {c.reservation.customer}
            </span>
            <span className="block text-xs text-fg-muted">
              {mode === "admin" ? `${c.worker.fullName} · ` : ""}
              {fmtDateTime(c.createdAt)}
            </span>
          </span>
          <StatusBadge status={c.status} size="sm" />
          <Money value={c.amount} currency={currency} className="font-semibold" />
        </Link>
      )}
    />
  );
}
