"use client"

import { SvgUse } from "@ivtui/base"
import clsx from "clsx"
import { OTPInput, OTPInputContext } from "input-otp"
import * as React from "react"

function InputOTP({
  className,
  containerClassName,
  ...props
}: React.ComponentProps<typeof OTPInput> & {
  containerClassName?: string
}) {
  return (
    <OTPInput
      data-slot="input-otp"
      containerClassName={clsx(
        "flex items-center gap-2 has-disabled:opacity-50",
        containerClassName,
      )}
      className={clsx("disabled:cursor-not-allowed", className)}
      {...props}
    />
  )
}

function InputOTPGroup({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div data-slot="input-otp-group" className={clsx("flex items-center", className)} {...props} />
  )
}

function InputOTPSlot({
  index,
  className,
  containerCaretClassName,
  caretClassName,
  ...props
}: React.ComponentProps<"div"> & {
  index: number
  containerCaretClassName?: string
  caretClassName?: string
}) {
  const inputOTPContext = React.useContext(OTPInputContext)
  const { char, hasFakeCaret, isActive } = inputOTPContext.slots[index]

  return (
    <div
      data-slot="input-otp-slot"
      data-active={isActive}
      className={clsx(
        "size-10 text-xl !rounded-lg border border-gray-200 relative flex items-center justify-center transition-all outline-none",
        "data-[active=true]:z-10 data-[active=true]:border-blue-400 data-[active=true]:ring-blue-100",
        className,
      )}
      {...props}
    >
      {char}
      {hasFakeCaret && (
        <div
          className={clsx(
            "pointer-events-none absolute inset-0 flex items-center justify-center",
            containerCaretClassName,
          )}
        >
          <div
            className={clsx(
              "animate-pulse bg-black h-4 w-px duration-1000 opacity-0",
              caretClassName,
            )}
          />
        </div>
      )}
    </div>
  )
}

function InputOTPSeparator({ ...props }: React.ComponentProps<"div">) {
  return (
    // biome-ignore lint/a11y/useFocusableInteractive: Ignore this
    // biome-ignore lint/a11y/useSemanticElements: Ignore this
    // biome-ignore lint/a11y/useAriaPropsForRole: Ignore this
    <div data-slot="input-otp-separator" role="separator" {...props}>
      <SvgUse icon="minus" />
    </div>
  )
}

export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator }
