import { Button } from "@repo/shadcn-ui/components";
import { cn } from '@repo/shadcn-ui/lib/utils';
import { XIcon } from "lucide-react";
import * as React from "react";
import { useCallback } from "react";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "../../../i18n.ts";
import { useUnsavedChangesContext } from "../use-unsaved-changes-notifier";

export type CancelFormButtonProps = {
  to?: string; /// Ruta a la que navegar si no se pasa onCancel
  onCancel?: () => void | Promise<void>; // Prioritaria sobre "to"
  label?: string;
  variant?: React.ComponentProps<typeof Button>["variant"];
  size?: React.ComponentProps<typeof Button>["size"];
  className?: string;
  disabled?: boolean;
  "data-testid"?: string;
};

export const CancelFormButton = ({
  to,
  onCancel,
  label,
  variant = "outline",
  size = "default",
  className,
  disabled,
  "data-testid": dataTestId = "cancel-button",
}: CancelFormButtonProps) => {
  const navigate = useNavigate();

  const { t } = useTranslation();
  const defaultLabel = t ? t("common.cancel") : "Cancel";
  const { requestConfirm } = useUnsavedChangesContext();

  const handleClick = useCallback(async () => {
    const ok = requestConfirm ? await requestConfirm() : true;
    if (!ok) return;

    if (onCancel) {
      await onCancel();
      return;
    }

    if (to) {
      navigate(to);
    }
    // si no hay ni onCancel ni to → no hace nada
  }, [requestConfirm, onCancel, to, navigate]);

  return (
    <Button
      type='button'
      variant={variant}
      size={size}
      className={cn("cursor-pointer", className)}
      onClick={handleClick}
      disabled={disabled}
      aria-disabled={disabled}
      data-testid={dataTestId}
    >
      <XIcon className='mr-2 h-3 w-3' />
      <span>{label ?? defaultLabel}</span>
    </Button>
  );
};
