'use client';

import React, { useState, useRef, createRef } from 'react';
import { Box, TextField } from '@mui/material';

interface CodeInputProps {
    onCodeChange?: (code: string) => void;
    isError: boolean;
    clearError?: () => void;
}

export default function MCodeInput({ onCodeChange, isError, clearError }: CodeInputProps) {
    const [codes, setCodes] = useState(['', '', '', '']);

    const inputRefs = useRef([
        createRef<HTMLInputElement>(),
        createRef<HTMLInputElement>(),
        createRef<HTMLInputElement>(),
        createRef<HTMLInputElement>(),
    ]);

    const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>, index: number) => {
        const { value } = e.target;
        const digit = value.replace(/\D/g, '').slice(-1);

        const newCodes = [...codes];
        newCodes[index] = digit;
        setCodes(newCodes);

        if (digit && index < 3) inputRefs.current[index + 1].current?.focus();
        if (onCodeChange) onCodeChange(newCodes.join(''));
        if (clearError) clearError();
    };

    const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement | HTMLDivElement>, index: number) => {
        if (e.key === 'Backspace' && !codes[index]) {
            if (index > 0) {
                inputRefs.current[index - 1].current?.focus();
            }
        }
    };

    return (
        <Box sx={{ display: 'flex', gap: 2 }}>
            {codes.map((code, idx) => (
                <TextField
                    key={idx}
                    error={isError}
                    inputRef={inputRefs.current[idx]}
                    value={code}
                    onChange={e => handleChange(e, idx)}
                    onKeyDown={e => handleKeyDown(e, idx)}
                    inputProps={{
                        maxLength: 1,
                        style: {
                            textAlign: 'center',
                            fontSize: '1.5rem',
                            width: '3rem',
                        },
                    }}
                    sx={{
                        '& .MuiOutlinedInput-root': {
                            backgroundColor: '#f2f2f2',
                            borderRadius: 4,
                            '& fieldset': {
                                borderColor: 'transparent',
                                transition: 'border-color 0.3s ease',
                            },
                            '&.Mui-focused fieldset': {
                                border: '1px solid #1976D2',
                            },
                        },
                    }}
                />
            ))}
        </Box>
    );
}
