import {
  Badge,
  Box,
  Button,
  FormControl,
  FormHelperText,
  FormLabel,
  Input,
  Modal,
  ModalBody,
  ModalCloseButton,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalOverlay,
  Text,
  Textarea,
  useDisclosure,
  useToast,
} from "@chakra-ui/react";
import React, { useEffect, useState } from "react";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import { useForm } from "react-hook-form";
import {
  useGetDepositRequestByIdQuery,
  useGetDepositRequestQuery,
  useUpdateDepositRequestMutation,
} from "../../Services/deposit.request.service";
import FullscreenLoaders from "../../Components/Loaders/FullscreenLoaders";
import ToastBox from "../../Components/ToastBox";
import { useGetDrawalRequestQuery } from "../../Services/drawal.request.service";
import {
  useApproveDepositRequestMutation,
  useGetDeleteRequestByIdQuery,
  useGetDeleteRequestQuery,
} from "../../Services/delete.request.service";

const FILE_TYPES = ["image/jpeg", "image/png", "image/gif"];

// export const conformModalSchema = yup.object().shape({
//   adminComment: yup.string().notRequired(),
// });

export const conformModalSchema = yup.object().shape({
  adminComment: yup.string().notRequired(),
});

const DeletionRequestApprove = ({
  isOpen,
  onClose,
  firstField,
  id,
  data: requestData,
}) => {
  const toast = useToast();
  const [file, setFile] = useState();
  const [isBtnLoading, setIsBtnLoading] = useState(false);
  const [isBtnLoadingReject, setIsBtnLoadingReject] = useState(false);
  const [isReject, setIsReject] = useState(false);

  const fileredData = requestData?.find((item) => item?.id === id);
  const [updateApproveRequest] = useApproveDepositRequestMutation();
  const { data, isLoading } = useGetDeleteRequestByIdQuery(id, {
    skip: !id,
  });

  const {
    register,
    reset,
    watch,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(conformModalSchema),
    mode: "all",
  });

  const { refetch } = useGetDeleteRequestQuery();

  useEffect(() => {
    reset({
      comment: fileredData?.comment,
    });
  }, [requestData, id]);

  const onSubmit = async (data) => {
    setIsBtnLoading(isReject ? false : true);
    setIsBtnLoadingReject(isReject);
    const approveReq = {
      adminComment: data?.adminComment,
      deletionStatus: isReject ? "Reject" : "Approved",
    };

    try {
      const res = await updateApproveRequest({ id, data: approveReq });

      if (res?.error) {
        toast({
          render: () => (
            <ToastBox message={res?.error?.data?.message} status={"error"} />
          ),
        });
        heandleOnClose();
      } else if (res?.data?.statusCode === 200) {
        toast({
          render: () => <ToastBox message={res?.data?.message} />,
        });
        refetch();
        heandleOnClose();
      }
    } catch (error) {
      console.log(error);
    }
  };

  const onReject = () => {};

  useEffect(() => {
    if (data) {
      reset({
        comment: data?.data?.comment,
      });
    }
  }, [data, reset]);

  const heandleOnClose = () => {
    reset();
    onClose();
    setIsBtnLoading(false);
    setIsReject(false);
    setIsBtnLoadingReject(false);
  };

  return (
    <Modal
      isOpen={isOpen}
      onClose={heandleOnClose}
      initialFocusRef={firstField}
    >
      <ModalOverlay />

      <ModalContent pb={4}>
        {/* <ModalHeader fontSize={"md"}>Confirm</ModalHeader> */}
        <ModalCloseButton />
        {isLoading ? (
          <FullscreenLoaders height={"50vh"} />
        ) : (
          <Box as="form" onSubmit={handleSubmit(onSubmit)}>
            <ModalBody>
              <FormControl mt={6} mb={4}>
                <FormLabel fontSize="sm">
                  Investor Comment{" "}
                  <Badge colorScheme="green">{fileredData?.currencyCode}</Badge>
                </FormLabel>
                {/* <Textarea
                  focusBorderColor="green.400"
                  name="comment"
                  {...register("comment")}
                  fontSize="sm"
                  type="text"
                  size="sm"
                  readOnly
                  rows={5}
                />
                {errors.comment && (
                  <Text fontSize="xs" color="red">
                    {errors.comment.message}
                  </Text>
                )} */}

                <Text fontSize="sm" fontWeight={500} color={"gray.600"}>
                  {data?.data?.comment}
                </Text>
              </FormControl>
              <FormControl mb={4} isRequired>
                <FormLabel fontSize="sm">Admin Comment</FormLabel>
                <Textarea
                  rows={5}
                  focusBorderColor="green.400"
                  name="adminComment"
                  {...register("adminComment")}
                  fontSize="sm"
                  type="textarea"
                  size="sm"
                  placeholder={"Enter your comment...."}
                  resize={"none"}
                  mb={2}
                />
                {errors.adminComment && (
                  <Text fontSize="xs" color="red">
                    {errors.adminComment.message}
                  </Text>
                )}
                <FormHelperText fontSize="xs" color="gray.500">
                  <Text as={"span"} me={2}>
                    {" "}
                    Maximum length should be 200 characters. You have entered
                  </Text>
                  {watch("adminComment")?.length || 0} characters.
                </FormHelperText>
              </FormControl>
            </ModalBody>
            <ModalFooter>
              <Button
                colorScheme="red"
                mr={3}
                type="submit"
                size={"sm"}
                rounded={"sm"}
                variant={"ghost"}
                onClick={() => setIsReject(true)}
                isLoading={isBtnLoadingReject}
                fontWeight={500}
              >
                Reject
              </Button>
              <Button
                colorScheme="forestGreen"
                variant="solid"
                size={"sm"}
                rounded={"sm"}
                isLoading={isBtnLoading}
                type="submit"
              >
                Approve
              </Button>
            </ModalFooter>
          </Box>
        )}
      </ModalContent>
    </Modal>
  );
};

export default DeletionRequestApprove;
