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

// Validation schema
const passwordSchema = yup.object().shape({
  oldPassword: yup.string().required("Current Password is required"),
  newPassword: yup
    .string()
    .required("New Password is required")
    .min(8, "Password must be at least 8 characters long")
    .max(16, "Password must be at most 50 characters long")
    .matches(/[A-Z]/, "Password must contain at least one uppercase letter")
    .matches(/[a-z]/, "Password must contain at least one lowercase letter")
    .matches(/[0-9]/, "Password must contain at least one number")
    .matches(
      /[@$!%*?&#]/,
      "Password must contain at least one special character"
    ),
  confirmNewPassword: yup
    .string()
    .required("Confirm Password is required")
    .oneOf([yup.ref("newPassword")], "Passwords must match"),
});

const ChangePassword = ({
  isOpen,
  onClose,
  firstField,
  actionId,
  setActionId,
}) => {
  const [isLoading, setIsLoading] = useState(false);
  const [alert, setAlert] = useState(false);
  const [showCurrentPassword, setShowCurrentPassword] = useState(false);
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const toast = useToast();

  const [updatePassword] = useUpdatePasswordMutation();

  // Form handling
  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(passwordSchema),
    mode: "all",
  });

  // Form submit handler
  const onSubmit = async (data) => {
    setIsLoading(true);
    try {
      const res = await updatePassword(data); // Assuming API request works as expected
      if (res?.data?.statusCode === 200) {
        toast({
          render: () => <ToastBox message={res?.data?.message} />,
        });
        handleClose();
      } else if (res?.error) {
        toast({
          render: () => (
            <ToastBox message={res?.error?.data?.message} status={"error"} />
          ),
        });
      }
    } catch (error) {
      console.error(error);
    } finally {
      setIsLoading(false);
    }
  };

  // Handle modal close
  const handleClose = () => {
    setAlert(false);
    onClose();
    reset();
  };

  return (
    <>
      <Modal isOpen={isOpen} onClose={onClose} initialFocusRef={firstField}>
        <ModalOverlay />
        <ModalContent>
          <ModalHeader fontSize="md">Change Password</ModalHeader>
          <ModalCloseButton />
          <ModalBody pb={6}>
            <Stack spacing={4}>
              {/* Current Password */}
              <FormControl isInvalid={errors.oldPassword}>
                <FormLabel fontSize="sm" mb={1} fontWeight={500}>
                  Current Password
                </FormLabel>
                <InputGroup size="sm">
                  <Input
                    {...register("oldPassword")}
                    fontSize="sm"
                    type={showCurrentPassword ? "text" : "password"}
                    focusBorderColor="forestGreen.300"
                  />
                  <InputRightElement width="4.5rem">
                    <Button
                      h="1.5rem"
                      size="xs"
                      onClick={() => setShowCurrentPassword((prev) => !prev)}
                    >
                      {showCurrentPassword ? "Hide" : "Show"}
                    </Button>
                  </InputRightElement>
                </InputGroup>
                <FormErrorMessage>
                  {errors.oldPassword?.message}
                </FormErrorMessage>
              </FormControl>

              {/* New Password */}
              <FormControl isInvalid={errors.newPassword}>
                <FormLabel fontSize="sm" mb={1}>
                  New Password
                </FormLabel>
                <InputGroup size="sm">
                  <Input
                    {...register("newPassword")}
                    fontSize="sm"
                    type={showNewPassword ? "text" : "password"}
                    focusBorderColor="forestGreen.300"
                  />
                  <InputRightElement width="4.5rem">
                    <Button
                      h="1.5rem"
                      size="xs"
                      onClick={() => setShowNewPassword((prev) => !prev)}
                    >
                      {showNewPassword ? "Hide" : "Show"}
                    </Button>
                  </InputRightElement>
                </InputGroup>
                <FormErrorMessage>
                  {errors.newPassword?.message}
                </FormErrorMessage>
              </FormControl>

              {/* Confirm Password */}
              <FormControl isInvalid={errors.confirmNewPassword}>
                <FormLabel fontSize="sm" mb={1}>
                  Confirm New Password
                </FormLabel>
                <InputGroup size="sm">
                  <Input
                    {...register("confirmNewPassword")}
                    fontSize="sm"
                    type={showConfirmPassword ? "text" : "password"}
                    focusBorderColor="forestGreen.300"
                  />
                  <InputRightElement width="4.5rem">
                    <Button
                      h="1.5rem"
                      size="xs"
                      onClick={() => setShowConfirmPassword((prev) => !prev)}
                    >
                      {showConfirmPassword ? "Hide" : "Show"}
                    </Button>
                  </InputRightElement>
                </InputGroup>
                <FormErrorMessage>
                  {errors.confirmNewPassword?.message}
                </FormErrorMessage>
              </FormControl>
            </Stack>
          </ModalBody>

          <DrawerFooter mb={5}>
            <Button
              onClick={handleClose}
              bg="#e0ebeb"
              size="sm"
              mr={3}
              rounded={"sm"}
            >
              Cancel
            </Button>
            <Button
              rounded={"sm"}
              colorScheme="forestGreen"
              size="sm"
              onClick={() => setAlert(true)}
              isLoading={isLoading}
            >
              Save
            </Button>
          </DrawerFooter>
        </ModalContent>
      </Modal>

      <CustomAlertDialog
        isOpen={alert}
        onClose={() => setAlert(false)}
        alertHandler={handleSubmit(onSubmit)}
        message={"Are you sure you want to change the password?"}
        isLoading={isLoading}
      />
    </>
  );
};

export default ChangePassword;
