import { useEffect } from 'react';
import { Box, TextField } from '@mui/material';
import type { SxProps } from '@mui/material';
import trim from 'lodash/trim';
import noop from 'lodash/noop';
import { mergeSx } from '../Util/style';

export const VERIFY_CODE_LENGTH = 6;

export default function VerificationCode({
  length = VERIFY_CODE_LENGTH,
  code,
  onChange = noop,
  onComplete = noop,
  sx = {},
}: {
  length?: number;
  code: string;
  onChange?: (_code: string) => void;
  onComplete?: (_code: string) => void;
  sx?: SxProps;
}) {
  useEffect(() => {
    if (code.length === length) {
      onComplete?.(code);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [code, length]);
  return (
    <Box
      sx={mergeSx(
        {
          width: '100%',
          maxWidth: 360,
          display: 'flex',
          justifyContent: 'space-between',
          gap: 1.5,
        },
        sx
      )}>
      {[...Array(length)].map((_, index) => (
        <TextField
          id={`code-input-${index}`}
          // eslint-disable-next-line react/no-array-index-key
          key={`code-input-${index}`}
          value={trim(code[index]) || ''}
          type="number"
          onChange={(e) => {
            const newCode = code.split('');
            newCode[index] = e.target.value;
            onChange?.(newCode.join(''));
            if (e.target.value && index < 5) {
              document.getElementById(`code-input-${index + 1}`)?.focus();
            }
          }}
          onKeyDown={(e) => {
            if (e.key === 'Backspace' && !trim(code[index]) && index > 0) {
              document.getElementById(`code-input-${index - 1}`)?.focus();
            }
          }}
          required
          autoComplete="off"
          slotProps={{
            htmlInput: {
              maxLength: 1,
              sx: {
                textAlign: 'center',
                fontSize: '1.5rem',
                '&::-webkit-inner-spin-button, &::-webkit-outer-spin-button': {
                  WebkitAppearance: 'none',
                  margin: 0,
                },
              },
              autoComplete: 'off',
              pattern: '[0-9]',
              inputMode: 'numeric',
            },
          }}
        />
      ))}
    </Box>
  );
}
