/* ----------------------------------- yup ---------------------------------- */
import * as Yup from 'yup';
/* ---------------------------------- form ---------------------------------- */
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
/* ---------------------------------- @mui ---------------------------------- */
import { Stack, Alert } from '@mui/material';
import { LoadingButton } from '@mui/lab';
/* ---------------------------------- hooks --------------------------------- */
import useAuth from '../../../hooks/useAuth';
import useIsMountedRef from '../../../hooks/useIsMountedRef';
/* ------------------------------- components ------------------------------- */
import { FormProvider, RHFTextField } from '../../../components/hook-form';
import { enqueueSnackbar } from 'notistack';

/* ---------------------------------- types --------------------------------- */

type LoginFormProps = {
  setEmailOrPhone: Function;
  setLoginOrVerifyCode: Function;
};

type FormValuesProps = {
  email: string;
  afterSubmit?: string;
};

/* -------------------------------------------------------------------------- */

export default function LoginForm({ setEmailOrPhone, setLoginOrVerifyCode }: LoginFormProps) {
  const { login } = useAuth();
  const isMountedRef = useIsMountedRef();

  const LoginSchema = Yup.object().shape({
    email: Yup.string().email('Email must be a valid email address').required('Email is required'),
  });

  const defaultValues = {
    email: '',
  };

  const methods = useForm<FormValuesProps>({
    resolver: yupResolver(LoginSchema),
    defaultValues,
  });

  const {
    reset,
    setError,
    handleSubmit,
    formState: { errors, isSubmitting },
  } = methods;

  const onSubmit = async (data: FormValuesProps) => {
    try {
      await login(data.email);
      setEmailOrPhone(data.email);
      setLoginOrVerifyCode(true);
      reset();
      enqueueSnackbar('Kode OTP telah dikirim, silahkan cek email yang login', {
        variant: 'success',
        autoHideDuration: 2000,
      });
    } catch (error: any) {
      reset();

      if (isMountedRef.current) {
        setError('afterSubmit', { ...error, message: error.data.message });
      }
    }
  };

  return (
    <FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
      <Stack spacing={3}>
        <Alert severity="info">Masukkan akun yang telah terdaftar</Alert>
        {!!errors.afterSubmit && <Alert severity="error">{errors.afterSubmit.message}</Alert>}

        <RHFTextField name="email" label="Email address" />
      </Stack>

      <LoadingButton
        fullWidth
        size="large"
        type="submit"
        variant="contained"
        loading={isSubmitting}
        sx={{ marginTop: 2 }}
      >
        Login
      </LoadingButton>
    </FormProvider>
  );
}
