import { composeEventHandlers } from "@radix-ui/primitive"
import clsx from "clsx"
import type { ComponentProps } from "react"
import { SvgUse } from "../../shared/SvgUse"
import { Input, InputAdornment, InputAdornmentButton, InputControl, InputRoot } from "../input"
import { InputPasswordPrimitive } from "../input-password-primitive"
import { usePasswordInputContext } from "../input-password-primitive/input-password-primitive"

export type PasswordInputProps = ComponentProps<typeof InputPasswordPrimitive.Root> &
  ComponentProps<typeof Input> & {
    error?: boolean
    size?: "sm" | "md" | "lg"
  }

export const PasswordInput = ({
  visible,
  defaultVisible,
  onVisibleChange,
  error,
  size = "md",
  className,
  ...props
}: PasswordInputProps) => (
  <InputPasswordPrimitive.Root
    visible={visible}
    defaultVisible={defaultVisible}
    onVisibleChange={onVisibleChange}
  >
    <InputRoot {...props} size={size} error={error} className={clsx(className)} />
  </InputPasswordPrimitive.Root>
)
PasswordInput.displayName = "PasswordInput"

export const PasswordInputAdornment = InputAdornment

export const PasswordInputInput = ({
  ref,
  ...props
}: ComponentProps<typeof InputPasswordPrimitive.Input>) => (
  <InputControl>
    <InputPasswordPrimitive.Input ref={ref} asChild {...props}>
      <Input />
    </InputPasswordPrimitive.Input>
  </InputControl>
)
PasswordInputInput.displayName = "PasswordInputInput"

export const PasswordInputAdornmentToggle = ({
  className,
  onClick,
  ...props
}: ComponentProps<typeof InputPasswordPrimitive.Toggle>) => {
  const { visible, onVisibleChange } = usePasswordInputContext()

  return (
    <InputAdornment>
      <InputAdornmentButton
        type="button"
        data-state={visible ? "visible" : "hidden"}
        onClick={composeEventHandlers(onClick, () => onVisibleChange(!visible))}
        className={clsx("group", className)}
        {...props}
      >
        <SvgUse icon="eyes-outline" className="hidden group-data-[state=visible]:block" />
        <SvgUse icon="eyes-off-outline" className="block group-data-[state=visible]:hidden" />
      </InputAdornmentButton>
    </InputAdornment>
  )
}
PasswordInputAdornmentToggle.displayName = "PasswordInputAdornmentToggle"
