'use client';

import * as Yup from 'yup';
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 IconButton from '@mui/material/IconButton';
import LoadingButton from '@mui/lab/LoadingButton';
import InputAdornment from '@mui/material/InputAdornment';

import { paths } from '@/routes/paths';
import RouterLink from '@/routes/router-link';
import { useRouter, useSearchParams } from '@/hooks';
import { useBoolean } from '@/hooks';
import { updateUserPasswordAPI } from '@/utils/axios'; // API call to update password

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

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

export default function AmplifyNewPasswordView() {
  const router = useRouter();
  const password = useBoolean();
  const confirmPassword = useBoolean();

  // Get the email and operationHash from URL parameters
  const searchParams = useSearchParams();
  const email = searchParams.get('email');
  const operationHash = searchParams.get('operationHash');

  const VerifySchema = Yup.object().shape({
    password: Yup.string()
      .min(6, 'Password must be at least 6 characters')
      .required('Password is required'),
    confirmPassword: Yup.string()
      .required('Confirm password is required')
      .oneOf([Yup.ref('password')], 'Passwords must match'),
  });

  const defaultValues = {
    password: '',
    confirmPassword: '',
  };

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

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

  const onSubmit = handleSubmit(async (data) => {
    try {
      // Prepare the request payload for updating the password
      const requestPayload = {
        email: email ?? '',  // Fallback to an empty string if email is null
        password: data.password,
        operationHash: operationHash ?? '',  // Fallback to an empty string if operationHash is null
      };
      
      const response = await updateUserPasswordAPI(requestPayload);
  
  
      if (response && response.id) {

        router.push(paths.auth.jwt.login); // Perform the redirect to login
      } else {
        console.error('Failed to update password:', response?.message || 'Unknown error');
        alert(`Failed to update password: ${response?.message || 'Unknown error'}`);
      }
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
      console.error('Error:', errorMessage);
    }
  });
  const renderForm = (
    <Stack spacing={3} alignItems="center">
      <RHFTextField
        name="password"
        label="Password"
        type={password.value ? 'text' : 'password'}
        InputProps={{
          endAdornment: (
            <InputAdornment position="end">
              <IconButton onClick={password.onToggle} edge="end">
                <Iconify icon={password.value ? 'solar:eye-bold' : 'solar:eye-closed-bold'} />
              </IconButton>
            </InputAdornment>
          ),
        }}
      />

      <RHFTextField
        name="confirmPassword"
        label="Confirm New Password"
        type={confirmPassword.value ? 'text' : 'password'}
        InputProps={{
          endAdornment: (
            <InputAdornment position="end">
              <IconButton onClick={confirmPassword.onToggle} edge="end">
                <Iconify icon={confirmPassword.value ? 'solar:eye-bold' : 'solar:eye-closed-bold'} />
              </IconButton>
            </InputAdornment>
          ),
        }}
      />

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

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

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