'use client';

import React, {FC, useState} from 'react';
import {InputStyle as S} from './input.style';
import {IInput} from './input.type';
import {RedStarComponent} from '../../atoms/red-star/red-star.component';
import {useTheme} from '@mui/material/styles';

/**
 *
 * @author Ali M. Sadeghi
 * @version 0.0.2
 * @description A React component that renders an input field.
 * @madeUse Emotion
 */
export const InputComponent: FC<IInput> = ({
    id,
    label,
    hint,
    error,
    color,
    disabled,
    containerClassName,
    endAdornment,
    startAdornment,
    autoComplete,
    autoFocus,
    mandatory,
    ...rest
}) => {
    const [isFocused, setIsFocused] = useState(autoFocus || false);
    const focusHandler = () => setIsFocused(true);
    const blurHandler = () => setIsFocused(false);
    const theme = useTheme();

    return (
        <S.Wrapper className={containerClassName}>
            <S.Header>
                {mandatory && <RedStarComponent />}
                {label && (
                    <S.Label dir='auto' htmlFor={id}>
                        {label}
                    </S.Label>
                )}
            </S.Header>
            <S.Container
                error={error}
                disabled={disabled}
                color={color}
                className={`${isFocused && 'focused'} ${
                    disabled && 'disabled'
                } ${error && 'error'}`}
            >
                {startAdornment && (
                    <S.StartAdornment>{startAdornment}</S.StartAdornment>
                )}
                <S.Field
                    dir='auto'
                    autoComplete={autoComplete}
                    autoFocus={autoFocus}
                    disabled={disabled}
                    onFocus={focusHandler}
                    onBlur={blurHandler}
                    className={`field ${S.placeholder(theme)}`}
                    error={error}
                    id={id}
                    {...rest}
                />
                {endAdornment && (
                    <S.EndAdornment>{endAdornment}</S.EndAdornment>
                )}
            </S.Container>
            {hint && (
                <S.Description dir='auto' error={error}>
                    {hint}
                </S.Description>
            )}
        </S.Wrapper>
    );
};
