"use client";

import * as React from "react";

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";

import { Eye, Link as LinkIcon, Pencil, Plus } from "lucide-react";

import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { customerUrl, extractCustomerTenantFromPath } from "@/lib/tenant";

import type { ListTransactionRow, TransactionModuleFormConfig } from "./types";

/** Resolves module `listPath` (`/customer/bond`) to the current tenant portal URL. */
export function useCustomerModuleListPath(listPath: string) {
  const pathname = usePathname();

  return React.useMemo(() => {
    if (!listPath.startsWith("/customer/")) {
      return listPath;
    }

    const tenant = extractCustomerTenantFromPath(pathname);
    if (!tenant) {
      return listPath;
    }

    const suffix = listPath.slice("/customer".length) || "/";
    return customerUrl(tenant, suffix);
  }, [listPath, pathname]);
}

export function useTransactionFormEdit(config: Pick<TransactionModuleFormConfig, "listPath">) {
  const router = useRouter();
  const defaultListPath = useCustomerModuleListPath(config.listPath);

  return React.useCallback(
    (row: ListTransactionRow, onCloseDetail?: () => void, overrideListPath?: string) => {
      onCloseDetail?.();
      const listPath = overrideListPath || defaultListPath;
      const formPath = `${listPath}/form`;
      const params = new URLSearchParams();
      if (row.id) params.set("id", row.id);
      if (row.refId) params.set("refId", row.refId);
      const query = params.toString();
      router.push(query ? `${formPath}?${query}` : formPath);
    },
    [defaultListPath, router],
  );
}

type NewTransactionButtonProps = {
  config: Pick<TransactionModuleFormConfig, "listPath" | "newButtonLabel">;
  className?: string;
};

export function NewTransactionButton({ config, className }: NewTransactionButtonProps) {
  const listPath = useCustomerModuleListPath(config.listPath);

  return (
    <Button variant="outline" className={className ?? "h-9 shrink-0"} asChild>
      <Link href={`${listPath}/form`}>
        <Plus className="size-4" />
        {config.newButtonLabel}
      </Link>
    </Button>
  );
}

type TransactionRowPermissionActionsProps = {
  rowName: string;
  canView: boolean;
  canEdit: boolean;
  onView?: () => void;
  onEdit?: () => void;
};

export type StockChildMenuItem = {
  key: "sale" | "option" | "accumulator" | "mark_expired";
  label: string;
  href: string;
  popup?: boolean;
  external?: boolean;
};

export function openTransactionChildPopup(href: string) {
  if (typeof window === "undefined" || !href) {
    return;
  }

  const width = 1100;
  const height = 720;
  const left = Math.max(0, Math.round(window.screenX + (window.outerWidth - width) / 2));
  const top = Math.max(0, Math.round(window.screenY + (window.outerHeight - height) / 2));
  const features = [
    `width=${width}`,
    `height=${height}`,
    `left=${left}`,
    `top=${top}`,
    "scrollbars=yes",
    "resizable=yes",
  ].join(",");

  window.open(href, "transactionChildPopup", features);
}

/** Navigate to a child transaction form in the current portal tab (Sale / Option / Accumulator). */
export function useTransactionChildFormNavigate() {
  const router = useRouter();

  return React.useCallback(
    (href: string) => {
      if (!href) {
        return;
      }
      router.push(href);
    },
    [router],
  );
}

type TransactionRowStockActionsProps = {
  rowName: string;
  canView: boolean;
  canEdit: boolean;
  attachmentUrl?: string | null;
  childMenuItems: StockChildMenuItem[];
  onView?: () => void;
  onEdit?: () => void;
};

export function TransactionRowStockActions({
  rowName,
  canView,
  canEdit,
  attachmentUrl,
  childMenuItems,
  onView,
  onEdit,
}: TransactionRowStockActionsProps) {
  const navigateToChildForm = useTransactionChildFormNavigate();

  const hasAttachment = typeof attachmentUrl === "string" && attachmentUrl.trim() !== "";

  if (!canView && !canEdit && !hasAttachment && childMenuItems.length === 0) {
    return <span className="block text-center text-muted-foreground text-sm">—</span>;
  }

  return (
    <div className="flex w-full items-center justify-end gap-0.5">
      {childMenuItems.length > 0 ? (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              type="button"
              variant="outline"
              size="icon-sm"
              className="size-7 shrink-0"
            >
              <Plus className="size-4" />
              <span className="sr-only">Add related transaction for {rowName}</span>
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="min-w-36">
            {childMenuItems.map((item) => (
              <DropdownMenuItem
                key={item.key}
                onClick={() => {
                  if (item.popup) {
                    openTransactionChildPopup(item.href);
                    return;
                  }
                  if (item.external) {
                    window.open(item.href, "_blank", "noopener,noreferrer");
                    return;
                  }
                  navigateToChildForm(item.href);
                }}
              >
                {item.label}
              </DropdownMenuItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>
      ) : null}
      {hasAttachment ? (
        <Button
          variant="ghost"
          size="icon-sm"
          className="text-blue-600 hover:bg-blue-500/10 hover:text-blue-700 dark:text-blue-400"
          onClick={() => {
            if (!attachmentUrl) {
              return;
            }
            window.open(attachmentUrl, "_blank", "noopener,noreferrer");
          }}
        >
          <LinkIcon className="size-4" />
          <span className="sr-only">Open attachment for {rowName}</span>
        </Button>
      ) : null}
      {canEdit ? (
        <Button
          variant="ghost"
          size="icon-sm"
          className="text-muted-foreground hover:bg-muted hover:text-foreground"
          onClick={onEdit}
        >
          <Pencil className="size-4" />
          <span className="sr-only">Edit transaction for {rowName}</span>
        </Button>
      ) : null}
      {canView ? (
        <Button
          variant="ghost"
          size="icon-sm"
          className="text-teal-600 hover:bg-teal-500/10 hover:text-teal-700 dark:text-teal-400"
          onClick={onView}
        >
          <Eye className="size-4" />
          <span className="sr-only">View details for {rowName}</span>
        </Button>
      ) : null}
    </div>
  );
}

export function TransactionRowPermissionActions({
  rowName,
  canView,
  canEdit,
  onView,
  onEdit,
}: TransactionRowPermissionActionsProps) {
  return (
    <div className="flex w-full items-center justify-end gap-0.5">
      {canEdit ? (
        <Button
          variant="ghost"
          size="icon-sm"
          className="text-muted-foreground hover:bg-muted hover:text-foreground"
          onClick={onEdit}
        >
          <Pencil className="size-4" />
          <span className="sr-only">Edit transaction for {rowName}</span>
        </Button>
      ) : null}
      {canView ? (
        <Button
          variant="ghost"
          size="icon-sm"
          className="text-teal-600 hover:bg-teal-500/10 hover:text-teal-700 dark:text-teal-400"
          onClick={onView}
        >
          <Eye className="size-4" />
          <span className="sr-only">View details for {rowName}</span>
        </Button>
      ) : null}
    </div>
  );
}
