"use client"
import * as Yup from 'yup';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';

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

import { paths } from '@/routes/paths';
import { useRouter } from '@/hooks';
import RouterLink from '@/routes/router-link';

import Iconify from '@/shared/components/iconify/iconify';
import FormProvider, { RHFTextField } from '@/shared/components/hook-form';

import axios from 'axios';

import { sendingResetPasswordAPI, verifyOtpAPI } from '@/utils/axios';


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

export default function AmplifyForgotPasswordView() {
  const router = useRouter();


  // State to track OTP step and operation hash
  const [otpSent, setOtpSent] = useState(false);
  const [operationHash, setOperationHash] = useState('');
  const [emailValue, setEmailValue] = useState(''); // State to preserve the email value
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  // Schema for email form

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

  // Schema for OTP form
  const OtpSchema = Yup.object().shape({
    otp: Yup.string().required('OTP is required').min(6, 'OTP must be 6 characters'),
  });

  // Form handling for the email step
  const methods = useForm({
    resolver: yupResolver(ForgotPasswordSchema),
    defaultValues: { email: '' }, 
  });

  // Form handling for the OTP step
  const otpMethods = useForm({
    resolver: yupResolver(OtpSchema),
    defaultValues: { otp: '' }, 
  });

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

  const {
    handleSubmit: handleOtpSubmit,
    formState: { isSubmitting: isOtpSubmitting },
  } = otpMethods;

  // Step 1: Send Reset Password Email and Show OTP Field
  const onSubmit = handleSubmit(async (data) => {
    try {
      

      const response = await sendingResetPasswordAPI({ email: data.email });
      

      if (response && response.operationHash) {
        

        // Save email and operationHash in state
        setEmailValue(data.email); // Set the email in state
        setOperationHash(response.operationHash);

        // Move to OTP step
        setOtpSent(true);
      } else {
        setErrorMessage('Failed to send reset password email.');
      }
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
      console.error('Error:', errorMessage);
    }
  });

  // Step 2: Verify OTP and Redirect to Reset Password Page
  // Step 2: Verify OTP and Redirect to Reset Password Page
const onOtpSubmit = handleOtpSubmit(async (otpData) => {
  try {
    

    const otpResponse = await verifyOtpAPI({
      email: emailValue, // Use the saved email state
      confirmationCode: otpData.otp,
      operationHash,
    });


    // Correct the condition to check for true response
    if (otpResponse === true) {
      const searchParams = new URLSearchParams({
        email: emailValue, // Pass the saved email to the next page
      }).toString();

      const href = `${paths.auth.newPassword}?${searchParams}`;
      router.push(href);
    } else {
      setErrorMessage('Invalid OTP.');
    }
  } catch (error: unknown) {
    const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
    console.error('Error:', errorMessage);
  }
});

  // Render Email Form
  const renderForm = (
    <Stack spacing={3} alignItems="center">
      <RHFTextField name="email" label="Email address" />

      <LoadingButton
        fullWidth
        size="large"
        type="submit"
        variant="contained"
        loading={isSubmitting}
      >
        Send Request
      </LoadingButton>

      <Link
        component={RouterLink}
        href={paths.auth.jwt.login}
        color="inherit"
        variant="subtitle2"
        sx={{
          alignItems: 'center',
          display: 'inline-flex',
        }}
      >
        <Iconify icon="eva:arrow-ios-back-fill" width={16} />
        Return to sign in
      </Link>
    </Stack>
  );

  // Render OTP Form
  const renderOtpForm = (
    <Stack spacing={3} alignItems="center">
      <Typography variant="body2">
        We have sent an OTP to your email: <strong>{emailValue}</strong>
      </Typography>

      <RHFTextField name="otp" label="Enter OTP" />

      <LoadingButton
        fullWidth
        size="large"
        type="submit"
        variant="contained"
        loading={isOtpSubmitting}
      >
        Verify OTP
      </LoadingButton>
    </Stack>
  );

  // Render Header
  const renderHead = (
    <>
      <Iconify icon="eva:lock-outline" sx={{ height: 96 }} />

      <Stack spacing={1} sx={{ mt: 3, mb: 5 }}>
        <Typography variant="h3">Forgot your password?</Typography>

        <Typography variant="body2" sx={{ color: 'text.secondary' }}>
          {otpSent
            ? 'Please enter the OTP sent to your email.'
            : 'Please enter the email address associated with your account, and we will email you a link to reset your password.'}
        </Typography>
      </Stack>
    </>
  );

  return (
    <>
      {renderHead}

      {otpSent ? (
        <FormProvider methods={otpMethods} onSubmit={onOtpSubmit}>
          {renderOtpForm}
        </FormProvider>
      ) : (
        <FormProvider methods={methods} onSubmit={onSubmit}>
          {renderForm}
        </FormProvider>
      )}
    </>
  );
}