import * as z from 'zod';
import * as yup from 'yup';
import { useForm } from 'react-hook-form';
import { useEffect, useState } from 'react';
import { useBoolean } from 'minimal-shared/hooks';
// import { zodResolver } from '@hookform/resolvers/zod';
import { yupResolver } from '@hookform/resolvers/yup';

import Box from '@mui/material/Box';
import Link from '@mui/material/Link';
import Alert from '@mui/material/Alert';
import Button from '@mui/material/Button';
import IconButton from '@mui/material/IconButton';
import InputAdornment from '@mui/material/InputAdornment';

import { paths } from 'src/routes/paths';
import { useRouter } from 'src/routes/hooks';
import { RouterLink } from 'src/routes/components';

import VisibilityProvider from 'src/shared/VisibilityProvider';

import { Iconify } from 'src/components/iconify';
import { Form, Field, schemaUtils } from 'src/components/hook-form';

import NewReCaptcha from 'src/auth/components/ReCaptcha';

import { useAuthContext } from '../../hooks';
import { getErrorMessage } from '../../utils';
import { FormHead } from '../../components/form-head';
import useLogin from './useLogin';
import { useNavigate } from 'react-router';

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

export type SignInSchemaType = z.infer<typeof SignInSchema>;

export const SignInSchema = z.object({
  email: schemaUtils.email(),
  password: z
    .string()
    .min(1, { error: 'Password is required!' })
    .min(6, { error: 'Password must be at least 6 characters!' }),
});

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

/**
 * Form Validation Schema
 */
const schema = yup.object().shape({
  email: yup.string().email('You must enter a valid email').required('You must enter a email'),
  password: yup.string().required('Please enter your password.'),
});

export function JwtSignInView() {
  const router = useRouter();
  const navigate = useNavigate();

  const showPassword = useBoolean();

  const { checkUserSession } = useAuthContext();

  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [isValidCaptcha, setIsValidCaptcha] = useState<boolean | null>(null);
  const [isMaxLogin, setIsMaxLogin] = useState<number>(0);
  const [isLocked, setIsLocked] = useState<boolean>(false);
  const [countdown, setCountdown] = useState<number>(0);

  const loginAction = useLogin();

  const methods = useForm({
    mode: 'onChange',
    defaultValues: {
      email: '',
      password: '',
    },
    resolver: yupResolver(schema),
  });

  const { isValid } = methods.formState;

  const shouldDisableButton = !isValid || !isValidCaptcha;

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

  useEffect(() => {
    if (!isLocked) return;

    setCountdown(15);

    const updateCountdown = (prev: number) => {
      if (prev <= 1) {
        clearInterval(timer);
        setIsMaxLogin(0);
        setIsLocked(false);
        return 0;
      }
      return prev - 1;
    };

    const timer = setInterval(() => {
      setCountdown(updateCountdown);
    }, 1000);

    // eslint-disable-next-line consistent-return
    return () => clearInterval(timer);
  }, [isLocked]);

  const onSubmit = handleSubmit(async (formData) => {
    try {
      if (isLocked) {
        setErrorMessage(`Kesempatan habis! Tunggu ${countdown} detik`);
        return;
      }

      if (isMaxLogin >= 3) {
        setIsLocked(true);
        setErrorMessage('Kesempatan Anda sudah habis, tunggu 15 detik lagi');
        return;
      }

      const data = await loginAction.mutateAsync(formData);
      navigate('/dashboard');

      console.log(data);
    } catch (error) {
      console.error(error);
      const feedbackMessage = getErrorMessage(error);
      setIsMaxLogin((prev) => prev + 1);
      setErrorMessage(feedbackMessage);
    }
  });

  const renderForm = () => (
    <Box sx={{ gap: 3, display: 'flex', flexDirection: 'column' }}>
      <Field.Text name="email" label="Email address" slotProps={{ inputLabel: { shrink: true } }} />

      <Box sx={{ gap: 1.5, display: 'flex', flexDirection: 'column' }}>
        <Field.Text
          name="password"
          label="Password"
          placeholder="6+ characters"
          type={showPassword.value ? 'text' : 'password'}
          slotProps={{
            inputLabel: { shrink: true },
            input: {
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton onClick={showPassword.onToggle} edge="end">
                    <Iconify
                      icon={showPassword.value ? 'solar:eye-bold' : 'solar:eye-closed-bold'}
                    />
                  </IconButton>
                </InputAdornment>
              ),
            },
          }}
        />

        <Link
          component={RouterLink}
          href="#"
          variant="body2"
          color="inherit"
          sx={{ alignSelf: 'flex-end' }}
        >
          Forgot password?
        </Link>

        <VisibilityProvider show>
          <NewReCaptcha isValidCaptcha={isValidCaptcha} setIsValidCaptcha={setIsValidCaptcha} />
        </VisibilityProvider>
      </Box>

      <Button
        fullWidth
        color="inherit"
        size="large"
        type="submit"
        variant="contained"
        loading={isSubmitting}
        loadingIndicator="Sign in..."
        disabled={shouldDisableButton}
      >
        Sign in
      </Button>
    </Box>
  );

  return (
    <>
      <FormHead
        title="Sign in to your account"
        // description={
        //   <>
        //     {`Don’t have an account? `}
        //     <Link component={RouterLink} href={paths.auth.jwt.signUp} variant="subtitle2">
        //       Get started
        //     </Link>
        //   </>
        // }
        sx={{ textAlign: { xs: 'center', md: 'left' } }}
      />

      {/* <Alert severity="info" sx={{ mb: 3 }}>
        Use <strong>{defaultValues.email}</strong>
        {' with password '}
        <strong>{defaultValues.password}</strong>
      </Alert> */}

      {!!errorMessage && (
        <Alert severity="error" sx={{ mb: 3 }}>
          {errorMessage}
        </Alert>
      )}

      <Form methods={methods} onSubmit={onSubmit}>
        {renderForm()}
      </Form>
    </>
  );
}
