'use client';

// ---------------------------------------------------------------------------------------------------------------------
//!                                                      Imports
// ---------------------------------------------------------------------------------------------------------------------

// ------------------------------------------------------ React --------------------------------------------------------
import { forwardRef, useState } from 'react';
// ---------------------------------------------------------------------------------------------------------------------

// ------------------------------------------------- Assets & Styles ---------------------------------------------------
import EyeSlashIcon from '@/assets/EyeSlashIcon';
import EyeIcon from '@/assets/EyeIcon';
import './styles.scss';
// ---------------------------------------------------------------------------------------------------------------------

const Input = forwardRef(function InputComponent(
	{
		type = 'text',
		label,
		name,
		value,
		defaultValue,
		autoComplete,
		required = false,
		onChange,
		onKeyUp,
		onKeyDown,
	},
	ref
) {
	const [isFocused, setIsFocused] = useState(
		defaultValue || value ? true : false
	);
	const [passwordVisibility, setPasswordVisibility] = useState(false);

	const defaultOnBlur = (ev) => {
		if (ev.currentTarget.value != '') {
			return;
		}

		setIsFocused(false);
	};

	return (
		<div className='inputContainer'>
			<input
				ref={ref}
				type={
					type == 'password'
						? passwordVisibility
							? 'text'
							: 'password'
						: type
				}
				name={name}
				id={name}
				value={value}
				defaultValue={defaultValue}
				autoComplete={autoComplete}
				required={required}
				onChange={onChange}
				onKeyUp={onKeyUp}
				onKeyDown={onKeyDown}
				className='input'
				onFocus={() => setIsFocused(true)}
				onBlur={defaultOnBlur}
			/>
			<label
				htmlFor={name}
				className={`inputLabel ${isFocused ? 'focused' : ''}`}
			>
				{label}
			</label>
			{type == 'password' && (
				<button
					type='button'
					className='passwordToggleButton'
					onClick={() => setPasswordVisibility((prev) => !prev)}
				>
					{passwordVisibility ? <EyeSlashIcon /> : <EyeIcon />}
				</button>
			)}
		</div>
	);
});

export default Input;
