"use client";

import * as React from "react";
import type { ColumnDef } from "@tanstack/react-table";
import { Globe } from "lucide-react";
import Link from "next/link";

import { DashboardMasterRowActions } from "@/app/dashboard/_components/dashboard-master-row-actions";
import { ActiveInactiveBadge } from "@/components/shared/status-pill";
import { FRONTEND_ROUTES } from "@/config/frontend-routes";

import { TaxGlobalBadge } from "./status-badge";
import type { TaxRow } from "./schema";

type TaxColumnsOptions = {
  onDeleted?: () => void;
};

function TaxActions({
  row,
  onDeleted,
}: {
  row: TaxRow;
  onDeleted?: () => void;
}) {
  const base = `/dashboard/plans-orders/taxes/${row.id}`;

  return (
    <DashboardMasterRowActions
      editHref={base}
      editAriaLabel="Update tax"
      deleteUrl={FRONTEND_ROUTES.plansOrders.taxes.deleteSubmit}
      entityId={row.id}
      entityName={row.name}
      entityLabel="tax"
      fallbackError="Tax could not be deleted."
      defaultSuccessMessage="Tax deleted."
      onDeleted={onDeleted}
    />
  );
}

export function createTaxColumns({ onDeleted }: TaxColumnsOptions = {}): ColumnDef<TaxRow>[] {
  return [
    {
      accessorKey: "name",
      header: "Name",
      cell: ({ row }) => (
        <div className="space-y-0.5">
          <Link
            href={`/dashboard/plans-orders/taxes/${row.original.id}`}
            className="font-medium text-primary hover:underline"
          >
            {row.original.name}
          </Link>
          {row.original.isGlobal === "yes" ? (
            <span className="inline-flex items-center gap-1 text-muted-foreground text-xs">
              <Globe className="size-3" />
              Global fallback tax
            </span>
          ) : null}
        </div>
      ),
    },
    {
      accessorKey: "percent",
      header: "Percent",
      cell: ({ row }) => (
        <span className="font-semibold tabular-nums text-sm">{row.original.percentFormatted}</span>
      ),
    },
    {
      accessorKey: "isGlobal",
      header: "Is global",
      cell: ({ row }) => (
        <TaxGlobalBadge value={row.original.isGlobal} label={row.original.isGlobalLabel} />
      ),
    },
    {
      accessorKey: "status",
      header: "Status",
      cell: ({ row }) => (
        <ActiveInactiveBadge status={row.original.status} label={row.original.statusLabel} />
      ),
    },
    {
      accessorKey: "dateAdded",
      header: "Date added",
      enableColumnFilter: false,
      cell: ({ row }) => (
        <span className="text-muted-foreground text-sm whitespace-nowrap">{row.original.dateAdded}</span>
      ),
    },
    {
      id: "options",
      header: () => <span className="block w-full text-right">Options</span>,
      cell: ({ row }) => <TaxActions row={row.original} onDeleted={onDeleted} />,
      enableSorting: false,
    },
  ];
}
