"use client";

import type { ColumnDef } from "@tanstack/react-table";
import { Languages, Ship } 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 { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";

import type { CountryBulkLan, CountryRow } from "./schema";

const DELETE_HREF = "/dashboard/master/countries/delete";

function CountryActions({ row }: { row: CountryRow }) {
  const base = `/dashboard/master/countries/${row.id}`;

  return (
    <DashboardMasterRowActions
      editHref={base}
      editAriaLabel="Update country"
      deleteUrl={DELETE_HREF}
      entityId={row.id}
      entityName={row.name}
      entityLabel="country"
      fallbackError="Country could not be deleted."
      defaultSuccessMessage="Country deleted."
    />
  );
}

type BulkColumnHandlers = {
  lan: CountryBulkLan;
  checkedIds: Set<number>;
  translations: Record<number, string>;
  onToggleChecked: (id: number, checked: boolean) => void;
  onTranslationChange: (id: number, value: string) => void;
};

export function createCountryColumns(
  bulk?: BulkColumnHandlers | null,
): ColumnDef<CountryRow>[] {
  const columns: ColumnDef<CountryRow>[] = [
    {
      accessorKey: "name",
      header: "Name",
      cell: ({ row }) => (
        <div className="space-y-1 min-w-[200px]">
          <Link
            href={`/dashboard/master/countries/${row.original.id}`}
            className="font-medium text-primary hover:underline"
          >
            <span data-country-name>{row.original.name}</span>
          </Link>
          <div className="flex flex-wrap items-center gap-2 text-muted-foreground text-xs">
            {row.original.otherName ? <span>{row.original.otherName}</span> : null}
            {row.original.nameAr ? (
              <span className="inline-flex items-center gap-1 font-medium" dir="rtl">
                <Languages className="size-3 shrink-0" />
                {row.original.nameAr}
              </span>
            ) : null}
          </div>
        </div>
      ),
    },
  ];

  if (bulk) {
    columns.push({
      id: "bulkUpdate",
      header: "Bulk Update",
      enableColumnFilter: false,
      cell: ({ row }) => {
        const id = row.original.id;
        const checked = bulk.checkedIds.has(id);
        return (
          <div className="flex min-w-[220px] items-center gap-2">
            <Checkbox
              checked={checked}
              onCheckedChange={(value) => bulk.onToggleChecked(id, value === true)}
              aria-label={`Include ${row.original.name} in apply translation`}
            />
            <Input
              value={bulk.translations[id] ?? ""}
              onChange={(event) => bulk.onTranslationChange(id, event.target.value)}
              dir={bulk.lan === "ar" ? "rtl" : "ltr"}
              className="h-8 bg-background text-xs"
              placeholder={bulk.lan === "ar" ? "Arabic name" : "Dutch name"}
            />
          </div>
        );
      },
    });
  }

  columns.push(
    {
      accessorKey: "code",
      header: "Code",
      cell: ({ row }) => (
        <span className="inline-flex rounded-md border bg-muted/50 px-2 py-0.5 font-mono font-semibold text-xs uppercase tracking-wide">
          {row.original.code}
        </span>
      ),
    },
    {
      accessorKey: "shipping",
      header: "Shipping",
      cell: ({ row }) => (
        <div className="space-y-0.5">
          <span className="font-medium tabular-nums text-sm">
            {row.original.shippingFormatted}
          </span>
          {row.original.enableShipping ? (
            <span className="flex items-center gap-1 text-emerald-700 text-[10px]">
              <Ship className="size-3" />
              Enabled
            </span>
          ) : (
            <span className="text-muted-foreground text-[10px]">Disabled</span>
          )}
        </div>
      ),
    },
    {
      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 }) => <CountryActions row={row.original} />,
      enableSorting: false,
    },
  );

  return columns;
}
