'use client';

import { z as zod } from 'zod';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';

import Link from '@mui/material/Link';
import Alert from '@mui/material/Alert';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import LoadingButton from '@mui/lab/LoadingButton';

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

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

import { requestPasswordReset } from 'src/auth/context/jwt';

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

const ForgotPasswordSchema = zod.object({
  email: zod
    .string()
    .min(1, { message: 'Email is required!' })
    .email({ message: 'Email must be a valid email address!' }),
});

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

export function JwtForgotPasswordView() {
  const [errorMsg, setErrorMsg] = useState('');
  const [successMsg, setSuccessMsg] = useState('');

  const methods = useForm({
    resolver: zodResolver(ForgotPasswordSchema),
    defaultValues: { email: '' },
  });

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

  const onSubmit = handleSubmit(async (data) => {
    try {
      await requestPasswordReset({ email: data.email });
      setSuccessMsg('Password reset instructions have been sent to your email.');
      setErrorMsg('');
    } catch (error) {
      console.error(error);
      const msg = error?.response?.data?.message || error?.response?.data?.detail || 'Error sending request. Please check your email.';
      setErrorMsg(msg);
    }
  });

  return (
    <>
      <Stack spacing={1.5} sx={{ mb: 5 }}>
        <Typography variant="h5">Forgot your password?</Typography>

        <Typography variant="body2" sx={{ color: 'text.secondary' }}>
          Enter your email address and we will send you a link to reset your password.
        </Typography>
      </Stack>

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

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

      {!successMsg && (
        <Form methods={methods} onSubmit={onSubmit}>
          <Stack spacing={3}>
            <Field.Text name="email" label="Email address" InputLabelProps={{ shrink: true }} />

            <LoadingButton
              fullWidth
              color="inherit"
              size="large"
              type="submit"
              variant="contained"
              loading={isSubmitting}
              loadingIndicator="Sending..."
            >
              Send reset link
            </LoadingButton>
          </Stack>
        </Form>
      )}

      <Link
        component={RouterLink}
        href={paths.auth.jwt.signIn}
        variant="body2"
        color="inherit"
        sx={{ display: 'block', mt: 3, textAlign: 'center' }}
      >
        Back to sign in
      </Link>
    </>
  );
}
