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

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

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

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

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

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

  const LoginSchema = Yup.object().shape({
    phone: Yup.string().required('Phone is required'),
  });

  const defaultValues = {
    phone: '',
  };

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

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

  const onSubmit = async (data: FormValuesProps) => {
    try {
      await login(0 + data.phone);
      setEmailOrPhone(0 + data.phone);
      setLoginOrVerifyCode(true);
      reset();
      enqueueSnackbar('Kode OTP telah dikirim, silahkan cek pada nomor yang telah 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="phone"
          label="Phone Number"
          type={'number'}
          InputProps={{
            startAdornment: <InputAdornment position="start">+62</InputAdornment>,
          }}
        />
      </Stack>

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