"use client"
import * as SwitchPrimitives from "@radix-ui/react-switch"
import React, { forwardRef, ElementRef, ComponentPropsWithoutRef } from "react"
import { VariantProps, tv } from "tailwind-variants"
import { disabledVariants } from "../../styles"
import { classNames } from "../../utils"

export type SwitchProps = Pick<
  ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>,
  | "aria-label"
  | "checked"
  | "onCheckedChange"
  | "disabled"
  | "id"
  | "name"
  | "className"
> &
  VariantProps<typeof switchVariants> & {
    size?: "sm" | "md"
  }

const switchVariants = tv({
  base: "inline-flex shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-hidden",
  variants: {
    checked: {
      false:
        "bg-bg-additional-2 hover:bg-bg-additional-3 active:bg-bg-additional-3",
      true: "bg-blue-3 hover:bg-blue-4 active:bg-blue-4",
    },
    size: {
      sm: "h-5 min-h-[20px] w-10 min-w-[40px]",
      md: "h-6 min-h-[24px] w-12 min-w-[48px]",
    },
  },
})

const thumbVariants = tv({
  base: "pointer-events-none flex items-center justify-center rounded-full bg-white transition-transform",
  variants: {
    checked: {
      false: "translate-x-0",
      true: "",
    },
    size: {
      sm: "size-4",
      md: "size-5",
    },
  },
  compoundVariants: [
    {
      size: "md",
      checked: true,
      class: "translate-x-6",
    },
    {
      size: "sm",
      checked: true,
      class: "translate-x-5",
    },
  ],
})

export const Switch = forwardRef<
  ElementRef<typeof SwitchPrimitives.Root>,
  SwitchProps
>(function Switch(
  { checked = false, disabled, size = "md", className, ...rest },
  ref,
) {
  return (
    <SwitchPrimitives.Root
      checked={checked}
      className={classNames(
        switchVariants({ checked, size }),
        disabledVariants({ disabled }),
        className,
      )}
      disabled={disabled}
      ref={ref}
      {...rest}
    >
      <SwitchPrimitives.Thumb
        className={classNames(thumbVariants({ checked, size }))}
      />
    </SwitchPrimitives.Root>
  )
})
