import styles from './Form.module.scss';
import type { FormData, FormProps } from './lib/types';
import { publicRuntimeConfig } from '@/config/runtime';
import { FormStateContext } from '@/context/form-state';
import type { PropsWithChildren } from 'react';
import { useContext } from 'react';
import { useForm } from 'react-hook-form';

const { TELEGRAM_BOT_URL } = publicRuntimeConfig;

export function BaseForm({ children, onSubmit }: FormProps & PropsWithChildren) {
  const { handleSubmit, register } = useForm<FormData>();
  const {
    state: { error, step, tfa },
  } = useContext(FormStateContext);

  return (
    <form className={styles.form} onSubmit={handleSubmit(onSubmit)}>
      <input
        disabled={step !== 'login'}
        type="text"
        placeholder="Логин"
        required
        autoComplete="on"
        {...register('login', { required: true })}
      />
      <input
        disabled={step !== 'login'}
        type="password"
        placeholder="Пароль"
        required
        autoComplete="on"
        {...register('password', { required: true })}
      />
      {tfa ? (
        <a target="_blank" className="info" href={TELEGRAM_BOT_URL} rel="noreferrer">
          Открыть чат с ботом
        </a>
      ) : null}
      {error ? <span className="error">{error}</span> : null}
      {children}
    </form>
  );
}
