import React, { useState, useEffect } from 'react';
import { Input } from '@/components/ui';
import { HiOutlineEyeOff, HiOutlineEye } from 'react-icons/hi';
import { BsCapslockFill } from 'react-icons/bs';

const PasswordInput = (props) => {
  const { onVisibleChange, ...rest } = props;

  const [pwInputType, setPwInputType] = useState('password');
  const [capsLockOn, setCapsLockOn] = useState(false);

  useEffect(() => {
    const handleKeyUp = (event) => {
      if (event instanceof KeyboardEvent) {
        setCapsLockOn(event.getModifierState('CapsLock'));
      }
    };

    window.addEventListener('keyup', handleKeyUp);

    return () => {
      window.removeEventListener('keyup', handleKeyUp);
    };
  }, []);

  const onPasswordVisibleClick = (e) => {
    e.preventDefault();
    const nextValue = pwInputType === 'password' ? 'text' : 'password';
    setPwInputType(nextValue);
    onVisibleChange?.(nextValue === 'text');
  };

  return (
    <Input
      {...rest}
      type={pwInputType}
      suffix={
        <>
          {capsLockOn ? (
            <span title="Caps Lock is on" className="mx-2">
              <BsCapslockFill />
            </span>
          ) : null}
          <span className="cursor-pointer text-xl" onClick={(e) => onPasswordVisibleClick(e)}>
            {pwInputType === 'password' ? <HiOutlineEyeOff /> : <HiOutlineEye />}
          </span>
        </>
      }
    />
  );
};

export default PasswordInput;
