"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import { Plus } from "lucide-react";

import type { DerivativesFixedIncomePagePermissions } from "@/app/customer/_lib/customer-api-permissions";
import {
  BOND_CHILD_LABELS,
  buildBondChildFormHref,
  type BondEditableChildKind,
} from "@/app/customer/[tenant]/derivatives-fixed-income/_lib/bond-child-types";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";

type DerivativesCreateMenuProps = {
  listPath: string;
  permissions: DerivativesFixedIncomePagePermissions;
};

type CreateMenuItem = {
  key: BondEditableChildKind;
  label: string;
  href: string;
};

export function DerivativesCreateMenu({ listPath, permissions }: DerivativesCreateMenuProps) {
  const router = useRouter();

  const items = React.useMemo(() => {
    const menuItems: CreateMenuItem[] = [];

    if (permissions.bond_accumulator_create) {
      menuItems.push({
        key: "bond_accumulator",
        label: BOND_CHILD_LABELS.bond_accumulator,
        href: buildBondChildFormHref(listPath, "bond_accumulator"),
      });
    }

    if (permissions.bond_funds_accumulator_create) {
      menuItems.push({
        key: "bond_funds_accumulator",
        label: BOND_CHILD_LABELS.bond_funds_accumulator,
        href: buildBondChildFormHref(listPath, "bond_funds_accumulator"),
      });
    }

    return menuItems;
  }, [
    listPath,
    permissions.bond_accumulator_create,
    permissions.bond_funds_accumulator_create,
  ]);

  if (items.length === 0) {
    return null;
  }

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant="outline" size="icon-lg" className="h-9 w-9 shrink-0">
          <Plus className="size-4" />
          <span className="sr-only">Create derivative transaction</span>
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="min-w-36">
        {items.map((item) => (
          <DropdownMenuItem key={item.key} onClick={() => router.push(item.href)}>
            {item.label}
          </DropdownMenuItem>
        ))}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
