import {
  Button,
  DrawerFooter,
  FormControl,
  FormErrorMessage,
  FormLabel,
  Input,
  Modal,
  ModalBody,
  ModalCloseButton,
  ModalContent,
  ModalHeader,
  ModalOverlay,
  Stack,
  useToast,
} from "@chakra-ui/react";
import * as yup from "yup";
import React, { useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { useForgetPasswordMutation } from "../Services/forget.password.service";
import ToastBox from "../Components/ToastBox";

const validationSchema = yup.object().shape({
  emailAddress: yup
    .string()
    .email("Invalid email format")
    .required("Email address is required")
    .min(6, "Email address must be at least 6 characters long")
    .max(255, "Email address can be at most 255 characters long"),
});

const ForgetPassword = ({ isOpen, onClose, firstField }) => {
  const toast = useToast();
  const [isLoading, setIsLoading] = useState(false);

  const [forgetPassword] = useForgetPasswordMutation();

  const {
    control,
    handleSubmit,
    formState: { errors },
    reset, // Add reset from useForm
  } = useForm({
    resolver: yupResolver(validationSchema),
  });

  const onSubmit = async (formData) => {
    setIsLoading(true);
    try {
      const res = await forgetPassword(formData);
      if (res?.data?.statusCode === 200) {
        toast({
          render: () => <ToastBox message={res?.data?.message} />,
        });
        handleClose();
      } else if (res?.error?.status === 400) {
        toast({
          render: () => (
            <ToastBox message={res?.error?.data?.message} status="error" />
          ),
        });
        handleClose();
    
      }
    } catch (error) {
      console.error(error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleClose = () => {
    setIsLoading(false);
    onClose();
    reset(); // Reset form state when modal closes
  };

  return (
    <Modal
      isCentered
      isOpen={isOpen}
      onClose={handleClose}
      initialFocusRef={firstField}
    >
      <ModalOverlay />
      <ModalContent>
        <form onSubmit={handleSubmit(onSubmit)}>
          <ModalHeader fontSize="md">Forgot Password</ModalHeader>
          <ModalCloseButton />
          <ModalBody pb={4}>
            <Stack spacing={4}>
              <FormControl isInvalid={errors.emailAddress} isRequired>
                <FormLabel fontSize="sm" mb={3} fontWeight={500}>
                  Please Enter Email Address
                </FormLabel>
                <Controller
                  name="emailAddress"
                  control={control}
                  render={({ field }) => (
                    <Input
                      {...field}
                      size="md"
                      fontSize="sm"
                      focusBorderColor="forestGreen.300"
                      rounded={4}
                      type="text"
                    />
                  )}
                />
                <FormErrorMessage fontSize="xs" fontWeight={500}>
                  {errors.emailAddress?.message}
                </FormErrorMessage>
              </FormControl>
            </Stack>
          </ModalBody>

          <DrawerFooter mb={5}>
            <Button
              w="100%"
              colorScheme="forestGreen"
              rounded="md"
              size="md"
              type="submit"
              isLoading={isLoading}
              fontWeight={400}
              fontSize="sm"
            >
              Reset Password
            </Button>
          </DrawerFooter>
        </form>
      </ModalContent>
    </Modal>
  );
};

export default ForgetPassword;
