import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";

import { cn } from "../lib/utils";

const buttonVariants = cva(
  "tw-figr-font-secondary tw-figr-inline-flex tw-figr-cursor-pointer tw-figr-items-center tw-figr-justify-center tw-figr-whitespace-nowrap tw-figr-transition-colors disabled:tw-figr-cursor-not-allowed disabled:tw-figr-opacity-50",
  {
    variants: {
      variant: {
        primary:
          "tw-figr-rounded-m hover:tw-figr-bg-primary-600 tw-figr-bg-primary tw-figr-text-base-white",
        destructive:
          "tw-figr-rounded-m tw-figr-bg-error-100 hover:tw-figr-bg-error-200 tw-figr-text-base-white",
        secondary:
          "tw-figr-rounded-m tw-figr-bg-secondary tw-figr-text-base-black hover:tw-figr-bg-secondary-700",
        outline:
          "tw-figr-rounded-m tw-figr-border tw-figr-border-neutral-200 tw-figr-bg-base-white tw-figr-text-base-black hover:tw-figr-bg-neutral-100",
        ghost:
          "tw-figr-rounded-m tw-figr-text-base-black hover:tw-figr-bg-neutral-100",
        link: "tw-figr-rounded-m tw-figr-text-base-black hover:tw-figr-text-primary hover:tw-figr-underline",
        "primary-with-icon":
          "tw-figr-rounded-m tw-figr-gap-s tw-figr-bg-primary tw-figr-text-base-white hover:tw-figr-bg-primary-600",
        "outline-with-icon":
          "tw-figr-rounded-m tw-figr-gap-s tw-figr-border tw-figr-border-neutral-200 tw-figr-bg-base-white tw-figr-text-base-black hover:tw-figr-bg-neutral-100",
        icon: "tw-figr-rounded-m tw-figr-gap-s tw-figr-border tw-figr-border-neutral-200 tw-figr-bg-base-white tw-figr-text-base-black hover:tw-figr-bg-neutral-100",
        "icon-rounded":
          "tw-figr-gap-s tw-figr-rounded-full tw-figr-border tw-figr-border-neutral-200 tw-figr-bg-base-white tw-figr-text-base-black hover:tw-figr-bg-neutral-100",
        loading:
          "tw-figr-rounded-m tw-figr-cursor-not-allowed tw-figr-gap-s tw-figr-bg-primary tw-figr-text-base-white tw-figr-opacity-50"
      },
      size: {
        none: "",
        sm: "tw-figr-py-xs tw-figr-px-m",
        md: "tw-figr-py-s tw-figr-px-sm",
        lg: "tw-figr-py-sm tw-figr-px-l",
        icon: "tw-figr-p-sm"
      }
    },
    defaultVariants: {
      variant: "primary",
      size: "md"
    }
  }
);

export interface ButtonProps
  extends React.ButtonHTMLAttributes<HTMLButtonElement>,
    VariantProps<typeof buttonVariants> {
  asChild?: boolean;
}

const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
  ({ className, variant, size, asChild = false, ...props }, ref) => {
    const Comp = asChild ? Slot : "button";

    return (
      <Comp
        className={cn(buttonVariants({ variant, size, className }))}
        ref={ref}
        {...props}
      />
    );
  }
);
Button.displayName = "Button";

export { Button, buttonVariants };
