import { Button } from "@repo/shadcn-ui/components";
import { cn } from "@repo/shadcn-ui/lib/utils";
import { LoaderCircleIcon, SaveIcon } from "lucide-react";
import * as React from "react";
import { useFormContext } from "react-hook-form";
import { useTranslation } from "../../../i18n.ts";

export type SubmitButtonProps = {
  formId?: string;
  isLoading?: boolean;
  label?: string;
  labelIsLoading?: string;

  variant?: React.ComponentProps<typeof Button>["variant"];
  size?: React.ComponentProps<typeof Button>["size"];
  className?: string;

  preventDoubleSubmit?: boolean; // Evita múltiples submits mientras loading
  hasChanges?: boolean;

  onClick?: React.MouseEventHandler<HTMLButtonElement>;
  disabled?: boolean;
  children?: React.ReactNode;
  "data-testid"?: string;
};

export const SubmitFormButton = ({
  formId,
  isLoading,
  label,
  labelIsLoading,
  variant = "default",
  size = "default",
  className,
  preventDoubleSubmit = true,
  hasChanges = false,
  onClick,
  disabled,
  children,
  "data-testid": dataTestId = "submit-button",
}: SubmitButtonProps) => {
  const { t } = useTranslation();
  const defaultLabel = t ? t("common.save") : "Save";
  const defaultLabelIsLoading = t ? t("common.saving") : "Saving...";

  // ⛳️ RHF opcional: auto-detectar isSubmitting si no se pasó isLoading
  let rhfIsSubmitting = false;
  try {
    const ctx = useFormContext();
    rhfIsSubmitting = !!ctx?.formState?.isSubmitting;
  } catch {
    // No hay provider de RHF; ignorar
  }
  const busy = isLoading ?? rhfIsSubmitting;

  const computedDisabled = !!(disabled || (preventDoubleSubmit && busy));
  const dataState = busy ? "loading" : "idle";

  const handleClick: React.MouseEventHandler<HTMLButtonElement> = (e) => {
    if (preventDoubleSubmit && busy) {
      // Evitar submits duplicados durante loading
      e.preventDefault();
      e.stopPropagation();
      return;
    }
    onClick?.(e);
  };

  return (
    <Button
      type='submit'
      form={formId}
      variant={variant}
      size={size}
      disabled={computedDisabled}
      aria-busy={busy}
      aria-disabled={computedDisabled}
      data-state={dataState}
      onClick={handleClick}
      data-testid={dataTestId}
      className={cn("min-w-[100px] cursor-pointer font-medium", hasChanges && "ring-2 ring-primary/20", className)}
    >
      {children ? (
        children
      ) : (
        <span className='inline-flex items-center gap-2'>
          {busy && (
            <>
              <LoaderCircleIcon className='mr-2 h-3 w-3 animate-spin' aria-hidden='true' />
              <span>{labelIsLoading ?? defaultLabelIsLoading}</span>
            </>
          )}
          {!busy && (
            <>
              <SaveIcon className='mr-2 h-3 w-3' />
              <span>{label ?? defaultLabel}</span>
            </>
          )}
        </span>
      )}
    </Button>
  );
};
