"use client";

import { cva, type VariantProps } from "class-variance-authority";

import { cn } from "@/lib/utils";
import { Button } from "../button";
import { Checkbox } from "../checkbox";
import { Label } from "../label";

const buttonVariants = cva(
  cn(
    "w-full",
    "cursor-pointer",
    "inline-flex items-center justify-center gap-4",
    "font-manrope text-[18px]/[18px] font-medium",
    "pl-[26px] pr-[18px] py-[18px]",
    "transition-[background-color,border-color,color]",
    "duration-200",
    "disabled:opacity-20",
    "border-2",
    "[-webkit-tap-highlight-color:transparent]",
    "[transform:translateZ(0)]"
  ),
  {
    variants: {
      cornerRadius: {
        "3xl": "rounded-3xl",
        full: "rounded-full",
      },
      active: {
        true: "bg-gradient-to-r from-[#EBF5FF] to-[#DBEAFE] border-primary shadow-blue-glow-2 text-primary",
        false: "bg-background border-border shadow-black-glow text-black",
      },
    },
    defaultVariants: {
      cornerRadius: "3xl",
      active: false,
    },
  }
);

export interface MainButtonProps
  extends React.ComponentProps<typeof Button>,
    VariantProps<typeof buttonVariants> {
  emoji?: string;
  isCheckbox?: boolean;
  checkboxProps?: React.ComponentProps<typeof Checkbox>;
}

function MainButton({
  className,
  cornerRadius,
  active,
  children,
  emoji,
  isCheckbox,
  checkboxProps,
  disabled,
  ...props
}: MainButtonProps) {
  return (
    <Button
      data-slot="main-button"
      className={cn(buttonVariants({ cornerRadius, active, className }))}
      {...props}
      onClick={(e: React.MouseEvent<HTMLButtonElement>) => {
        if (disabled) return;
        const targetEl = e.target as HTMLElement | null;
        const isCheckboxTarget = targetEl?.closest('[data-slot="checkbox"]');
        if (isCheckboxTarget) {
          return;
        }
        e.preventDefault();
        props.onClick?.(e);
      }}
      asChild
    >
      <Label
        data-disabled={disabled}
        className={cn(
          disabled && "pointer-events-none opacity-20 cursor-not-allowed"
        )}
      >
        {emoji && <span className="text-[40px]">{Array.from(emoji)[0]}</span>}
        <p className="w-full text-left min-h-[38px] flex items-center">
          {children}
        </p>
        {isCheckbox && (
          <Checkbox
            {...checkboxProps}
            checked={active ?? false}
            disabled={disabled}
            onClick={(e) => {
              if (disabled) return;
              e.stopPropagation();
              props.onClick?.(
                e as unknown as React.MouseEvent<HTMLButtonElement>
              );
            }}
          />
        )}
      </Label>
    </Button>
  );
}

export { MainButton, buttonVariants };
