import {
  Box,
  Button,
  Checkbox,
  FormControl,
  FormLabel,
  Input,
  Modal,
  ModalBody,
  ModalCloseButton,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalOverlay,
  Text,
  Textarea,
  useBoolean,
} from "@chakra-ui/react";
import React, { useEffect, useState } from "react";
import PropTypes from "prop-types";

import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import { useForm } from "react-hook-form";
import ReactQuill from "react-quill";

export const conformModalSchema = yup.object().shape({
  comment: yup
    .string()
    .min(2, "Minimum length should be 2 characters.")
    .max(150, "Maximum length should be 150 characters.")
    // .matches(/^[^\d]+$/, "Sponsor Name cannot contain numbers")
    .required("Comment is required"),
  subject: yup.string().notRequired(),
  emailTemplate: yup.string().notRequired(),
});

const ConfirmReversalPopups = ({
  isOpen,
  onClose,
  handleConfirm,
  isLoading,
}) => {
  const {
    watch,
    register,
    reset,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(conformModalSchema),
    mode: "all",
  });

  const [richTextValue, setRichTextValue] = useState("");

  useEffect(() => {
    setValue("emailTemplate", richTextValue);
  }, [richTextValue]);

   // Reset the form when the modal closes
   useEffect(() => {
    if (!isOpen) {
      reset(); // Clear the form state
    }
  }, [isOpen, reset]);

  const [emailApproval, setEmailApproval] = useBoolean(false);

  const modules = {
    toolbar: [
      //   [{ header: "1" }, { header: "2" },
      //   // { font: [] }
      // ],
      // [{ size: [] }],
      ["bold", "italic", "underline", "strike", "blockquote"],
      [{ list: "ordered" }, { list: "bullet" }],
      ["clean"],
    ],
  };

  return (
    <Modal isOpen={isOpen} onClose={onClose}>
      <ModalOverlay />
      <ModalContent pb={4}>
        <ModalHeader fontSize={"md"}>Approve</ModalHeader>
        <ModalCloseButton />
        <Box
          as="form"
          onSubmit={handleSubmit((data) => {
            handleConfirm(data);
            reset();
            onClose();
          })}
        >
          <ModalBody>
            <FormControl mb={4} isRequired>
              <FormLabel fontSize="sm">Comment</FormLabel>
              <Textarea
                rows={6}
                focusBorderColor="green.400"
                name="comment"
                {...register("comment")}
                fontSize="sm"
                type="textarea"
                size="md"
                placeholder={"Enter your comment...."}
                rounded={"md"}
                resize={"none"}
                mb={2}
              />
              {errors.comment ? (
                <Text fontSize="xs" color="red">
                  {errors.comment.message}
                </Text>
              ) : (
                <Text fontSize="xs" color="gray.500">
                  Maximum length should be 150 characters. You have entered{" "}
                  {watch()?.comment?.length || 0} characters.
                </Text>
              )}
            </FormControl>
            <Checkbox
              colorScheme="forestGreen"
              onChange={setEmailApproval.toggle}
              defaultChecked={emailApproval}
            >
              <Text mb={0} fontSize={"sm"}>
                Send an email to the user upon approval
              </Text>
            </Checkbox>
            {emailApproval && (
              <Box className="messageBox">
                <FormControl mb={4}>
                  <FormLabel fontSize="sm" mb={1}>
                    Subject
                  </FormLabel>
                  <Input
                    focusBorderColor="green.400"
                    name="fileName"
                    {...register("subject")}
                    fontSize="sm"
                    type="text"
                    size="sm"
                  />
                </FormControl>
                <FormControl mb={12}>
                  <FormLabel fontSize="sm" mb={1}>
                    Message
                  </FormLabel>
                  <ReactQuill
                    theme="snow"
                    style={{
                      height: 150,
                    }}
                    value={richTextValue}
                    onChange={setRichTextValue}
                    modules={modules}
                    placeholder="Start typing here..."
                  />
                </FormControl>
              </Box>
            )}
          </ModalBody>
          <ModalFooter>
            <Button
              colorScheme="gray"
              mr={3}
              onClick={onClose}
              size={"sm"}
              rounded={"sm"}
            >
              Cancel
            </Button>
            <Button
              colorScheme="forestGreen"
              variant="solid"
              size={"sm"}
              rounded={"sm"}
              type="submit"
              fontWeight={400}
            >
              Send
            </Button>
          </ModalFooter>
        </Box>
      </ModalContent>
    </Modal>
  );
};

ConfirmReversalPopups.propTypes = {
  isOpen: PropTypes.bool.isRequired,
  onClose: PropTypes.func.isRequired,
  handelApproved: PropTypes.func.isRequired,
  isLoading: PropTypes.func.isRequired,
  richTextValue: PropTypes.any.isRequired,
  setRichTextValue: PropTypes.any.isRequired,
};

export default ConfirmReversalPopups;
