'use client'

import * as React from 'react'
import { Button } from '@/components/ui/button'
import { Input, type InputProps } from '@/components/ui/input'
import { cn } from '@/lib/utils'

const PasswordInput = React.forwardRef<HTMLInputElement, InputProps>(
  ({ className, ...props }, ref) => {
    const [showPassword, setShowPassword] = React.useState(false)
    const [inputType, setInputType] = React.useState('password')


    React.useEffect(() => {
      setInputType(showPassword ? 'text' : 'password')
    }, [showPassword])

    return (
      <div className='relative'>
        <Input
          type={inputType}
          className={cn('hide-password-toggle pr-10', className)}
          ref={ref}
          key={inputType}
          {...props}
        />
        <Button
          type='button'
          variant='ghost'
          size='sm'
          className='absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent'
          onClick={() => setShowPassword(prev => !prev)}
        >
          {showPassword ? (
            <>
              <span
                aria-hidden='true'
                className='font-cbicons text-[rgb(138,145,158)] text-[16px]'
                data-icon-name='visibleInactive'
                data-testid='icon-base-glyph'
                role='img'
              >
                不
              </span>
            </>
          ) : (
            <span
                aria-hidden='true'
                className='font-cbicons text-[rgb(138,145,158)] text-[16px]'
                data-icon-name='visibleInactive'
                data-testid='icon-base-glyph'
                role='img'
              >
                拾
              </span>
          )}
          <span className='sr-only'>
            {showPassword ? 'Hide password' : 'Show password'}
          </span>
        </Button>

        <style>{`
					.hide-password-toggle::-ms-reveal,
					.hide-password-toggle::-ms-clear {
						visibility: hidden;
						pointer-events: none;
						display: none;
					}
				`}</style>
      </div>
    )
  }
)
PasswordInput.displayName = 'PasswordInput'

export { PasswordInput }
