'use client';

import React, { useCallback, useEffect, useRef, useState } from 'react';

import styles from './ExpositoryItemCodeInput.module.scss';
import { useRouter } from 'next/navigation';

export default function ExpositoryItemCodeInput() {
  const { push } = useRouter();

  const inputRef1 = useRef<HTMLInputElement | null>(null);
  const inputRef2 = useRef<HTMLInputElement | null>(null);
  const inputRef3 = useRef<HTMLInputElement | null>(null);

  const [code1, setCode1] = useState<string>('');
  const [code2, setCode2] = useState<string>('');
  const [code3, setCode3] = useState<string>('');

  useEffect(() => {
    let timeout = setTimeout(() => {
      if (inputRef1?.current) {
        (inputRef1.current as HTMLInputElement).focus();
      }
    }, 100);

    return () => { clearTimeout(timeout) };
  }, []);

  const onChange = (
    value: string,
    setValue: (v: string) => void,
    nextRef?: React.RefObject<HTMLInputElement>
  ) => {
    if (setValue) {
      setValue(value);

      if (value?.length && nextRef?.current) {
        (nextRef.current)?.focus();
      }
    }
  }

  const onSubmit = useCallback(() => {
    const code = `${code1}${code2}${code3}`;
    
    if (code?.length) {
      push(`/codigo/${code}`);

      setCode1('');
      setCode2('');
      setCode3('');
    }
  }, [code1, code2, code3, push]);

  useEffect(() => {
    if (!!code1?.length && !!code2?.length && !!code3?.length) {
      onSubmit();
    }
  }, [code1?.length, code2?.length, code3?.length, onSubmit])

  return (
    <form
      className={styles.ExpositoryItemCodeInput}
      onSubmit={(event) => {
        event.preventDefault();

        onSubmit();
      }}
    >
      <ul>
        <li>
          <input
            ref={inputRef1}
            type="text"
            value={code1}
            maxLength={1}
            onChange={(event) => onChange(event?.target?.value || '', setCode1, inputRef2)}
          />
        </li>
        <li>
          <input
            ref={inputRef2}
            type="text"
            value={code2}
            maxLength={1}
            onChange={(event) => onChange(event?.target?.value || '', setCode2, inputRef3)}
          />
        </li>
        <li>
          <input
            ref={inputRef3}
            type="text"
            value={code3}
            maxLength={1}
            onChange={(event) => onChange(event?.target?.value || '', setCode3)}
          />
        </li>
      </ul>
      <button type="submit" />
    </form>
  );
};
