import React, { forwardRef } from "react"
import { tv } from "tailwind-variants"
import { type VariantProps } from "tailwind-variants"
import { backgroundVariants, borderVariants } from "../../styles"
import { classNames } from "../../utils"
import { textBodyVariants } from "../Text/TextBody"
import { UnstyledButton, UnstyledButtonProps } from "../UnstyledButton"

export type SwitchPillProps = UnstyledButtonProps &
  VariantProps<typeof switchPillVariants> & {
    size?: "sm" | "lg" | "md"
  }

const switchPillVariants = tv({
  base: classNames("transition-colors duration-150 ease-out"),
  variants: {
    variant: {
      default: "",
      transparent: "",
    },
    checked: {
      true: "text-text-primary font-medium",
      false: "text-text-secondary",
    },
    size: {
      sm: "h-6 rounded px-1.5",
      md: "h-7 rounded-md px-2",
      lg: "h-8 rounded-md px-2.5",
    },
  },
  defaultVariants: {
    variant: "default",
    size: "sm",
  },
  compoundVariants: [
    {
      variant: "default",
      checked: true,
      className: classNames(
        backgroundVariants({
          background: "additional-1",
          interactive: true,
        }),
        borderVariants({ border: "border-2", interactive: true }),
      ),
    },
    {
      variant: "default",
      checked: false,
      className: classNames(
        backgroundVariants({ background: "primary", interactive: true }),
        borderVariants({ border: "border-1", interactive: true }),
      ),
    },
    {
      variant: "transparent",
      checked: true,
      className: classNames(
        backgroundVariants({
          background: "additional-1",
          interactive: true,
          transparent: true,
        }),
        borderVariants({
          border: "border-2",
          interactive: true,
          transparent: true,
        }),
      ),
    },
    {
      variant: "transparent",
      checked: false,
      className: classNames(
        backgroundVariants({
          background: "primary",
          interactive: true,
          transparent: true,
        }),
        borderVariants({
          border: "border-1",
          interactive: true,
          transparent: true,
        }),
      ),
    },
  ],
})

export const SwitchPill = forwardRef<HTMLButtonElement, SwitchPillProps>(
  function SwitchPill(
    { className, children, variant, checked = false, size = "sm", ...rest },
    ref,
  ) {
    return (
      <UnstyledButton
        aria-checked={Boolean(checked)}
        className={classNames(
          "items-center justify-center gap-1 whitespace-nowrap",
          textBodyVariants({ size: size === "sm" ? "xs" : "sm" }),
          switchPillVariants({ variant, checked, size }),
          className,
        )}
        ref={ref}
        role="switch"
        {...rest}
      >
        {children}
      </UnstyledButton>
    )
  },
)
