import * as Yup from 'yup';
// form
import { yupResolver } from '@hookform/resolvers/yup';
import { useForm } from 'react-hook-form';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Link as RouterLink, useNavigate } from 'react-router-dom';

// @mui
import { Alert, IconButton, InputAdornment, Stack, Typography } from '@mui/material';
import { LoadingButton } from '@mui/lab';
// hooks
import useIsMountedRef from '@/hooks/useIsMountedRef';
// components
import { FormProvider, RHFTextField } from '@/components/hook-form';
import axios from '@/utils/axios';
import Iconify from '@/components/Iconify';

// ----------------------------------------------------------------------

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

type Props = {
  token: string;
};

export default function ForgetPasswordForm({ token }: Props) {
  const isMountedRef = useIsMountedRef();
  const navigate = useNavigate();

  const [showPasswordNew, setShowPasswordNew] = useState(false);
  const [showPasswordConfirmNew, setShowPasswordConfirmNew] = useState(false);
  const ResetPasswordSchema = Yup.object().shape({});

  const methods = useForm<FormValuesProps>({
    resolver: yupResolver(ResetPasswordSchema),
    // defaultValues: { email: 'demo@minimals.cc' },
  });

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

  const onSubmit = async (data: FormValuesProps) => {
    try {
      await axios.post('/forget-password', { ...data, token });
      console.log(data);

      // await new Promise((resolve) => setTimeout(resolve, 500));
      await new Promise((resolve) => setTimeout(resolve, 500));

      if (isMountedRef.current) {
        navigate('/auth/login', { replace: true });
      }
    } catch (error) {
      console.log(error.response.data);
      if (isMountedRef.current) {
        setError('afterSubmit', { ...error, message: error.response.data.message });
      }
    }
  };

  return (
    <FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
      <Stack spacing={3}>
        {!!errors.afterSubmit && <Alert severity="error">{errors.afterSubmit.message}</Alert>}
        <Typography>Kata Sandi Baru</Typography>
        <RHFTextField
          name="new_password"
          label="Kata Sandi Baru"
          type={showPasswordNew ? 'text' : 'password'}
          InputProps={{
            endAdornment: (
              <InputAdornment position="end">
                <IconButton onClick={() => setShowPasswordNew(!showPasswordNew)} edge="end">
                  <Iconify icon={showPasswordNew ? 'eva:eye-fill' : 'eva:eye-off-fill'} />
                </IconButton>
              </InputAdornment>
            ),
          }}
        />
        <Typography>Konfirmasi Kata Sandi </Typography>
        <RHFTextField
          name="confirm_new_password"
          label="Konfirmasi Kata Sandi"
          type={showPasswordConfirmNew ? 'text' : 'password'}
          InputProps={{
            endAdornment: (
              <InputAdornment position="end">
                <IconButton
                  onClick={() => setShowPasswordConfirmNew(!showPasswordConfirmNew)}
                  edge="end"
                >
                  <Iconify icon={showPasswordConfirmNew ? 'eva:eye-fill' : 'eva:eye-off-fill'} />
                </IconButton>
              </InputAdornment>
            ),
          }}
        />

        <LoadingButton
          fullWidth
          size="large"
          type="submit"
          variant="contained"
          loading={isSubmitting}
        >
          Reset Password
        </LoadingButton>
      </Stack>
    </FormProvider>
  );
}
