import { motion } from "framer-motion";
import React, { type ReactNode, type ComponentPropsWithoutRef } from "react";
import Lottie from "react-lottie";

import animationData from "@assets/lottie/buttonLoader.json";
import { useTheme } from "@hooks/useTheme";
import { getBorderRadius } from "@utils/getBorderRadius";
import { twMerge } from "@utils/tailwindMerge";

const animationOptions = {
	loop: true,
	autoplay: true,
	animationData: animationData,
	renderSettings: {
		preserveAspectRatio: "xMidYMid slice",
	},
};

// 👇 Correctly extend the props for motion.button
interface ButtonProps extends ComponentPropsWithoutRef<typeof motion.button> {
	label: ReactNode;
	isLoading?: boolean;
	classNames?: string;
}

export const Button = ({
	label,
	isLoading,
	classNames,
	disabled,
	...rest
}: ButtonProps) => {
	const theme = useTheme();

	const style = twMerge(
		"bn-relative bn-h-[50px] bn-text-button bn-text-base bn-flex bn-items-center bn-justify-center bn-border-none bn-bg-theme disabled:bn-bg-layer-2 disabled:bn-text-secondary bn-font-bold bn-w-full bn-text-center bn-cursor-pointer",
		classNames,
	);

	return (
		<motion.button
			layout
			className={style}
			style={{ borderRadius: getBorderRadius(theme.borderRadius, 8) }}
			disabled={disabled}
			{...rest}
		>
			{isLoading && (
				<div className="bn-absolute bn-left-4 bn-top-0 bn-bottom-0 bn-my-auto">
					<Lottie options={animationOptions} width={28} />
				</div>
			)}
			{label}
		</motion.button>
	);
};
