'use client'

import * as React from 'react'
import { cn } from '@/lib/utils/cn'
import { ErrorIcon } from '../icons/form-icon'
export interface InputProps extends React.ComponentProps<'input'> {
  label?: string
  containerClass?: string
  labelClass?: string
  hasError?: boolean
  errorMessage?: string
  iconLeft?: React.ReactNode
  iconRight?: React.ReactNode
}

export function CustomInput({
  label,
  containerClass,
  labelClass,
  className,
  hasError = false,
  errorMessage,
  iconLeft,
  iconRight,
  ...props
}: InputProps) {
  const id = React.useId()
  const isFilled = props.value != null && String(props.value).length > 0

  const paddingLeft = iconLeft ? 'pl-8' : ''
  const paddingRight = iconRight ? 'pr-8' : ''
  const hoverBg = !isFilled ? 'group-hover:bg-neutral-500 hover:bg-neutral-500' : ''

  return (
    <div className={cn(containerClass)}>
      {label && (
        <label
          htmlFor={id}
          className={cn(
            'uppercase block text-grey-50 caption-medium-medium pointer-events-none pb-2',
            labelClass,
          )}
        >
          {label}
        </label>
      )}

      <div className="relative">
        {iconLeft && (
          <span className="absolute left-2 top-1/2 -translate-y-1/2 z-10 flex items-center">
            {iconLeft}
          </span>
        )}

        <input
          id={id}
          data-slot="input"
          {...props}
          // value={props.value ?? ''}
          className={cn(
            'group font-b2-regular placeholder:text-grey-200 text-base-white',
            'flex h-12 w-full min-w-0 rounded-md border px-4 py-3 text-base outline-none',
            'bg-neutral-700 focus:bg-neutral-700',
            paddingLeft,
            paddingRight,
            hoverBg,
            'shadow-xs transition-[background-color,box-shadow]',
            'disabled:cursor-not-allowed disabled:opacity-50',
            'focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]',
            'aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40',
            hasError ? 'border-func-red-main dark:border-red' : 'border-[#FCFCFC33]',
            className,
          )}
        />

        {iconRight && (
          <span className="absolute right-2 top-1/2 -translate-y-1/2 z-10 flex items-center">
            {iconRight}
          </span>
        )}
      </div>
      {hasError && errorMessage && (
        <div className="flex items-center justify-start mt-2">
          <ErrorIcon width={20} height={20} className="text-func-red-main flex-shrink-0" />
          <p className={cn('label-medium-regular ml-1 text-func-red-main')}>{errorMessage}</p>
        </div>
      )}
    </div>
  )
}
