import { BaseForm } from './base-form';
import { useLogin, useTelegramConfirm, useTelegramLogin } from './hooks/telegram';
import { useRefreshToken } from './hooks/token';
import { ButtonLoading, ButtonLogin, ButtonTelegram, ButtonTelegramLogin } from './lib/buttons';
import { FormStateContext } from '@/context/form-state';
import { useContext } from 'react';

export function TelegramForm() {
  useRefreshToken();
  const { handleLogin } = useLogin();
  const { handleTelegramLogin } = useTelegramLogin();
  useTelegramConfirm();

  const {
    state: { step, user },
  } = useContext(FormStateContext);

  if (step === 'login' && user) {
    return <ButtonLoading />;
  }

  if (step === 'telegram') {
    return (
      <BaseForm onSubmit={() => handleTelegramLogin()}>
        <ButtonTelegram>Войти как &nbsp;{user?.displayName}</ButtonTelegram>
      </BaseForm>
    );
  }

  if (step === 'telegram-login') {
    return (
      <BaseForm onSubmit={() => {}}>
        <ButtonTelegramLogin />
      </BaseForm>
    );
  }

  return (
    <BaseForm onSubmit={(data) => handleLogin(data)}>
      <ButtonLogin />
    </BaseForm>
  );
}
