"use client";

import { useEffect, useState, type MouseEvent, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { TableRow } from "@/components/ui/table";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { CopyPlus } from "lucide-react";
import { handleDuplicatePurchaseOrderFromHistory } from "@/lib/actions";

type PurchaseHistoryContextRowProps = {
  orderId: string;
  returnPath: string;
  duplicateLabel: string;
  className?: string;
  children: ReactNode;
};

export default function PurchaseHistoryContextRow({
  orderId,
  returnPath,
  duplicateLabel,
  className,
  children,
}: PurchaseHistoryContextRowProps) {
  const [menuState, setMenuState] = useState({ open: false, x: 0, y: 0 });
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  const handleContextMenu = (event: MouseEvent<HTMLTableRowElement>) => {
    event.preventDefault();
    setMenuState({ open: true, x: event.clientX, y: event.clientY });
  };

  return (
    <>
      <TableRow className={className} onContextMenu={handleContextMenu}>
        {children}
      </TableRow>

      <DropdownMenu
        open={menuState.open}
        onOpenChange={(open) => setMenuState((prev) => ({ ...prev, open }))}
      >
        {mounted && createPortal(
          <DropdownMenuTrigger asChild>
            <button
              type="button"
              aria-hidden="true"
              className="fixed h-0 w-0 opacity-0 pointer-events-none"
              style={{ left: menuState.x, top: menuState.y }}
            />
          </DropdownMenuTrigger>,
          document.body,
        )}
        <DropdownMenuContent align="start" sideOffset={8}>
          <form action={handleDuplicatePurchaseOrderFromHistory}>
            <input type="hidden" name="sourceOrderId" value={orderId} />
            <input type="hidden" name="returnPath" value={returnPath} />
            <DropdownMenuItem asChild>
              <button type="submit" className="w-full text-start">
                <CopyPlus className="me-2 h-4 w-4" />
                {duplicateLabel}
              </button>
            </DropdownMenuItem>
          </form>
        </DropdownMenuContent>
      </DropdownMenu>
    </>
  );
}
