import * as React from "react"
import { Switch as SwitchPrimitive } from "@base-ui/react/switch"
import { cn } from "../core/cn"

interface SwitchToggleProps extends SwitchPrimitive.Root.Props {
  label?: string
  labelPosition?: "left" | "right"
  className?: string
}

function SwitchToggle({ className, label, labelPosition = "right", id, ...props }: SwitchToggleProps) {
  const internalId = React.useId()
  const switchId = id ?? internalId

  const switchEl = (
    <SwitchPrimitive.Root
      id={switchId}
      data-slot="switch"
      className={cn(
        "peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors outline-none",
        "bg-input focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50",
        "data-checked:bg-primary",
        "disabled:pointer-events-none disabled:opacity-50",
        className
      )}
      {...props}
    >
      <SwitchPrimitive.Thumb
        data-slot="switch-thumb"
        className={cn(
          "pointer-events-none block size-4 rounded-full bg-background shadow-sm ring-0 transition-transform",
          "translate-x-0 data-checked:translate-x-4"
        )}
      />
    </SwitchPrimitive.Root>
  )

  if (!label) return switchEl

  return (
    <div className="flex items-center gap-2">
      {labelPosition === "left" && (
        <label
          htmlFor={switchId}
          data-slot="switch-label"
          className="text-sm font-medium leading-none cursor-pointer select-none peer-disabled:cursor-not-allowed peer-disabled:opacity-50"
        >
          {label}
        </label>
      )}
      {switchEl}
      {labelPosition === "right" && (
        <label
          htmlFor={switchId}
          data-slot="switch-label"
          className="text-sm font-medium leading-none cursor-pointer select-none peer-disabled:cursor-not-allowed peer-disabled:opacity-50"
        >
          {label}
        </label>
      )}
    </div>
  )
}

export { SwitchToggle }
export type { SwitchToggleProps }
