"use client";

import type { ColumnDef } from "@tanstack/react-table";
import { ExternalLink, Pencil, Settings, Shield, Shuffle } from "lucide-react";
import Link from "next/link";

import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";

import { CustomerStatusBadge } from "./status-badge";
import type { CustomerRow } from "./schema";
import { DashboardDeleteAction } from "@/app/dashboard/_components/dashboard-delete-action";
import { FRONTEND_ROUTES } from "@/config/frontend-routes";
import { customerPortalAbsoluteUrl } from "@/lib/tenant/urls";

function customerDetailHref(customerId: number, action?: string, parentCustomerId?: number) {
  const params = new URLSearchParams();
  if (action) params.set("action", action);
  if (parentCustomerId) params.set("parentCustomer", String(parentCustomerId));
  const query = params.toString();
  return `/dashboard/customers/${customerId}${query ? `?${query}` : ""}`;
}

function customerImpersonateHref(customerId: number, parentCustomerId?: number) {
  const params = new URLSearchParams({ id: String(customerId) });
  if (parentCustomerId) params.set("parentCustomer", String(parentCustomerId));
  return `/dashboard/customers/impersonate?${params.toString()}`;
}

function CustomerActions({
  row,
  parentCustomerId,
  onOpenPortalRoutes,
}: {
  row: CustomerRow;
  parentCustomerId?: number;
  onOpenPortalRoutes?: (row: CustomerRow) => void;
}) {
  const detailHref = customerDetailHref(row.id, undefined, parentCustomerId);
  const settingsHref = customerDetailHref(row.id, "settings", parentCustomerId);
  const impersonateHref = customerImpersonateHref(row.id, parentCustomerId);

  return (
    <div className="inline-flex flex-nowrap items-center justify-end gap-0.5">
      <Tooltip>
        <TooltipTrigger asChild>
          <Button variant="default" size="icon-sm" className="size-7" asChild>
            <Link href={settingsHref} aria-label="Dashboard settings">
              <Settings className="size-3.5" />
            </Link>
          </Button>
        </TooltipTrigger>
        <TooltipContent>Dashboard settings</TooltipContent>
      </Tooltip>
      {!parentCustomerId ? (
        <Tooltip>
          <TooltipTrigger asChild>
            <Button
              variant="outline"
              size="icon-sm"
              className="size-7"
              type="button"
              aria-label="Portal permissions"
              onClick={() => onOpenPortalRoutes?.(row)}
            >
              <Shield className="size-3.5" />
            </Button>
          </TooltipTrigger>
          <TooltipContent>Portal Apps &amp; permissions</TooltipContent>
        </Tooltip>
      ) : null}
      {row.canImpersonate ? (
        <Tooltip>
          <TooltipTrigger asChild>
            <Button
              variant={row.accountType === "C" ? "secondary" : "default"}
              size="icon-sm"
              className={cn("size-7", row.accountType === "C" && "bg-orange-500 hover:bg-orange-600")}
              asChild
            >
              <a
                href={impersonateHref}
                target="_blank"
                rel="noreferrer"
                aria-label="Login as customer"
              >
                <Shuffle className="size-3.5" />
              </a>
            </Button>
          </TooltipTrigger>
          <TooltipContent>
            {row.accountType === "C" ? "Login as corporate console" : "Login as customer"}
          </TooltipContent>
        </Tooltip>
      ) : null}
      <Tooltip>
        <TooltipTrigger asChild>
          <Button variant="secondary" size="icon-sm" className="size-7" asChild>
            <Link href={detailHref} aria-label="Update customer">
              <Pencil className="size-3.5" />
            </Link>
          </Button>
        </TooltipTrigger>
        <TooltipContent>Update</TooltipContent>
      </Tooltip>
      {row.isRemovable ? (
        <DashboardDeleteAction
          deleteUrl={FRONTEND_ROUTES.customers.deleteSubmit}
          entityId={row.id}
          fallbackError="Customer could not be deleted."
          defaultSuccessMessage="Customer deleted."
          dialogTitle="Delete customer?"
          dialogDescription={
            <>
              This will delete {row.firstName} {row.lastName} ({row.email}). This action cannot be
              undone.
            </>
          }
          confirmLabel="Delete customer"
          deleteAriaLabel="Delete customer"
        />
      ) : null}
    </div>
  );
}

export function createCustomerColumns({
  parentCustomerId,
  onOpenCredentials,
  onOpenPortalRoutes,
}: {
  parentCustomerId?: number;
  onOpenCredentials?: (row: CustomerRow) => void;
  onOpenPortalRoutes?: (row: CustomerRow) => void;
}): ColumnDef<CustomerRow>[] {
  return [
  {
    accessorKey: "id",
    header: "Customer ID",
    cell: ({ row }) => (
      <div className="space-y-1">
        <div className="font-mono text-xs">{row.original.dbName}</div>
        <CustomerStatusBadge status={row.original.status} label={row.original.statusLabel} />
      </div>
    ),
  },
  {
    id: "fullName",
    header: "Full Name",
    cell: ({ row }) => (
      <div className="flex flex-col gap-1 text-sm">
        <Link
          href={`/dashboard/customers/${row.original.id}?action=view`}
          className="font-medium text-primary hover:underline"
        >
          {row.original.firstName} {row.original.lastName}
        </Link>
        {row.original.childCount > 0 ? (
          <Link
            href={`/dashboard/customers?parentCustomer=${row.original.id}`}
            className="text-primary text-xs hover:underline"
          >
            {row.original.childCount} sub-customer{row.original.childCount === 1 ? "" : "s"}
          </Link>
        ) : null}
        {row.original.joinDate ? (
          <div className="text-muted-foreground text-xs">Joined: {row.original.joinDate}</div>
        ) : null}
        {onOpenCredentials ? (
          <button
            type="button"
            onClick={() => onOpenCredentials(row.original)}
            className="w-fit text-left text-primary text-xs hover:underline"
          >
            Send login details
          </button>
        ) : (
          <Link
            href={customerDetailHref(row.original.id, "send-credentials", parentCustomerId)}
            className="w-fit text-primary text-xs hover:underline"
          >
            Send login details
          </Link>
        )}
      </div>
    ),
  },
  {
    accessorKey: "subdomain",
    header: "Subdomain",
    cell: ({ row }) => (
      <div className="space-y-1.5 text-sm">
        {row.original.subdomain ? (
          <a
            href={
              row.original.subdomain.includes(".")
                ? `https://${row.original.subdomain}`
                : customerPortalAbsoluteUrl(row.original.subdomain, "/dashboard")
            }
            target="_blank"
            rel="noreferrer"
            className="inline-flex items-center gap-1 text-primary hover:underline"
          >
            {row.original.subdomain}
            <ExternalLink className="size-3" />
          </a>
        ) : (
          <span className="text-muted-foreground">—</span>
        )}
        <div className="flex flex-wrap gap-1">
          <Button variant="outline" size="sm" className="h-7 gap-1 text-xs">
            <Shuffle className="size-3" />
            Impersonate
          </Button>
        </div>
        <Link href="#" className="text-primary text-xs hover:underline">
          All orders
        </Link>
        {!row.original.subdomainCreated ? (
          <div className="space-y-1">
            <p className="font-medium text-destructive text-xs">Subdomain not created</p>
            <Button size="sm" className="h-7 text-xs">
              Create subdomain
            </Button>
          </div>
        ) : null}
      </div>
    ),
  },
  {
    accessorKey: "accountTypeLabel",
    header: "Account Type",
    cell: ({ row }) => (
      <div className="space-y-1">
        <span
          className={cn(
            "font-semibold text-xs uppercase tracking-wide",
            row.original.accountType === "C" ? "text-orange-600" : "text-slate-700",
          )}
        >
          {row.original.accountTypeLabel}
        </span>
        <button type="button" className="block text-orange-600 text-xs uppercase hover:underline">
          Mark as corporate
        </button>
      </div>
    ),
  },
  {
    accessorKey: "createdBy",
    header: "Created By",
    cell: ({ row }) => row.original.createdBy ?? "—",
  },
  {
    accessorKey: "email",
    header: "Email",
    cell: ({ row }) => (
      <a href={`mailto:${row.original.email}`} className="text-primary text-sm hover:underline">
        {row.original.email}
      </a>
    ),
  },
  {
    id: "options",
    header: () => <span className="block w-full text-right">Options</span>,
    cell: ({ row }) => (
      <div className="whitespace-nowrap">
        <CustomerActions
          row={row.original}
          parentCustomerId={parentCustomerId}
          onOpenPortalRoutes={onOpenPortalRoutes}
        />
      </div>
    ),
    enableSorting: false,
  },
  ];
}
