"use client";

import * as React from "react";
import Link from "next/link";
import type { ColumnDef } from "@tanstack/react-table";
import { DataTable, FilterSelect } from "@/components/ui/data-table";
import { Avatar } from "@/components/ui/primitives";
import { StatusBadge, Badge } from "@/components/ui/badge";
import { Money } from "@/components/ui/money";
import { relativeTime, fmtDate } from "@/lib/dates";
import { fmtPercent } from "@/lib/format";
import { pct } from "@/lib/utils";

export interface WorkerRow {
  id: string;
  fullName: string;
  email: string;
  phone: string | null;
  avatarUrl: string | null;
  role: string;
  roleKey: string;
  status: string;
  hireDate: string | null;
  lastLoginAt: string | null;
  lastSeenAt: string | null;
  online: boolean;
  total: number;
  confirmed: number;
  cancelled: number;
  thisMonth: number;
  checkIns: number;
  checkOuts: number;
  commissionEarned: number;
  commissionPaid: number;
  commissionPending: number;
}

export function WorkersTable({ rows, currency, showMoney }: { rows: WorkerRow[]; currency: string; showMoney: boolean }) {
  const [status, setStatus] = React.useState("");
  const data = rows.filter((r) => !status || r.status === status);
  const cols = React.useMemo<ColumnDef<WorkerRow, unknown>[]>(
    () => [
      {
        accessorKey: "fullName",
        header: "Worker",
        cell: ({ row }) => (
          <div className="flex items-center gap-2.5">
            <Avatar name={row.original.fullName} src={row.original.avatarUrl} size="md" online={row.original.online} />
            <div className="min-w-0">
              <Link href={`/workers/${row.original.id}`} className="block truncate text-sm font-medium hover:text-primary">
                {row.original.fullName}
              </Link>
              <span className="block truncate text-2xs text-fg-subtle">{row.original.email}</span>
            </div>
          </div>
        ),
      },
      { accessorKey: "role", header: "Role", cell: ({ row }) => <Badge tone={row.original.roleKey === "ADMIN" ? "brand" : "outline"} size="sm">{row.original.role}</Badge> },
      { accessorKey: "status", header: "Status", cell: ({ row }) => <StatusBadge status={row.original.status} size="sm" /> },
      { accessorKey: "lastSeenAt", header: "Presence", cell: ({ row }) => <span className="text-xs">{row.original.online ? <span className="font-medium text-positive-600">Online</span> : <span className="text-fg-muted">Seen {relativeTime(row.original.lastSeenAt)}</span>}</span> },
      { accessorKey: "thisMonth", header: "This month", meta: { align: "right" }, cell: ({ row }) => <span className="tabular">{row.original.thisMonth}</span> },
      { accessorKey: "confirmed", header: "Confirmed", meta: { align: "right" }, cell: ({ row }) => <span className="tabular text-positive-600">{row.original.confirmed}</span> },
      { accessorKey: "cancelled", header: "Cancelled", meta: { align: "right" }, cell: ({ row }) => <span className="tabular text-negative-600">{row.original.cancelled}</span> },
      { id: "conv", accessorFn: (r) => pct(r.confirmed, r.total), header: "Conv.", meta: { align: "right" }, cell: ({ row }) => <span className="tabular">{fmtPercent(pct(row.original.confirmed, row.original.total), 0)}</span> },
      { id: "ops", accessorFn: (r) => r.checkIns + r.checkOuts, header: "In / out", meta: { align: "right" }, cell: ({ row }) => <span className="tabular text-xs">{row.original.checkIns} / {row.original.checkOuts}</span> },
      ...(showMoney ? [{ accessorKey: "commissionPending", header: "Commission due", meta: { align: "right" }, cell: ({ row }: { row: { original: WorkerRow } }) => <div className="text-right"><Money value={row.original.commissionPending} currency={currency} className="font-medium" /><span className="block text-2xs text-fg-subtle"><Money value={row.original.commissionPaid} currency={currency} compact /> paid</span></div> } as ColumnDef<WorkerRow, unknown>] : []),
      { accessorKey: "hireDate", header: "Hired", cell: ({ row }) => <span className="text-xs text-fg-muted">{row.original.hireDate ? fmtDate(row.original.hireDate) : "—"}</span> },
    ],
    [currency, showMoney]
  );
  return (
    <DataTable
      columns={cols}
      data={data}
      globalFilterFn={(r, q) => [r.fullName, r.email, r.role, r.phone ?? ""].join(" ").toLowerCase().includes(q)}
      searchPlaceholder="Name, email, role…"
      rowHref={(r) => `/workers/${r.id}`}
      toolbar={<FilterSelect value={status} onChange={setStatus} placeholder="All statuses" options={[{ value: "ACTIVE", label: "Active" }, { value: "INACTIVE", label: "Inactive" }, { value: "SUSPENDED", label: "Suspended" }]} />}
      emptyTitle="No workers"
      mobileCard={(r) => (
        <Link href={`/workers/${r.id}`} className="flex items-center gap-3 rounded-lg border border-border bg-surface p-3">
          <Avatar name={r.fullName} size="lg" online={r.online} />
          <span className="min-w-0 flex-1">
            <span className="block truncate text-sm font-semibold">{r.fullName}</span>
            <span className="block text-xs text-fg-muted">
              {r.role} · {r.online ? "online" : `seen ${relativeTime(r.lastSeenAt)}`}
            </span>
            <span className="block text-2xs text-fg-subtle">
              {r.confirmed} confirmed · {r.cancelled} cancelled
            </span>
          </span>
          <StatusBadge status={r.status} size="sm" />
        </Link>
      )}
    />
  );
}
