import React, {FC} from 'react';

import {EnterCodeStyle as S} from './styles/enter-code.style';
import {useEnterCode} from './hooks/use-enter-code';
import {IEnterCode} from './enter-code.type';
import {useTheme} from '@mui/material';

export const EnterCodeComponent: FC<IEnterCode> = ({
    onComplete,
    fields,
    label,
    hint,
    size,
    error,
    ...rest
}) => {
    const {processInput, onKeyUp, code, inputs} = useEnterCode({
        onComplete,
        fields,
    });
    const theme = useTheme();

    return (
        <S.Container>
            {label && <S.Label>{label}</S.Label>}
            <S.Wrapper size={size}>
                {code.map((num, idx) => {
                    return (
                        <S.Input
                            // @ts-ignore
                            size={size}
                            className={`${S.placeholder(theme)}`}
                            error={error}
                            key={idx}
                            inputMode='numeric'
                            maxLength={fields - idx}
                            value={num}
                            autoFocus={!code[0].length && idx === 0}
                            onChange={(e) => processInput(e, idx)}
                            onKeyUp={(e) => onKeyUp(e, idx)}
                            ref={(ref) => inputs.current.push(ref)}
                            {...rest}
                        />
                    );
                })}
            </S.Wrapper>
            {hint && <S.Description error={error}>{hint}</S.Description>}
        </S.Container>
    );
};
