import {
  Badge,
  Box,
  Button,
  HStack,
  Modal,
  ModalBody,
  ModalCloseButton,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalOverlay,
  Table,
  Tbody,
  Text,
  Th,
  Tr,
  useDisclosure,
  useToast,
} from "@chakra-ui/react";
import NormalData from "../../../../Components/DataTable/NormalTable";
import { useContext, useState } from "react";
import {
  useExitIOTransactionMutation,
  useGetDistributedToInvestorMutation,
  useGetDistributionInvestorMutation,
  useGetIOByIdQuery,
} from "../../../../Services/io.service";
import { useParams } from "react-router-dom";
import { useEffect } from "react";
import { useForm } from "react-hook-form";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import ToastBox from "../../../../Components/ToastBox";
import GlobalStateContext from "../../../../Contexts/GlobalStateContext";
import ApprovedCancelTransaction from "./ApprovedCancelTransaction";
import RequestRejectModal from "./RequestRejectModal";
import { encryptString, isMaker } from "../../../../Constants/Constants";

const ViewCancel = ({ isOpen, onClose, id: cancleId }) => {
  const params = useParams();
  const toast = useToast();
  const id = params?.id;
  const [isCalculateLoading, setIsCalculateLoading] = useState(false);
  const [isFinalCalculateLoading, setIsFinalCalculateLoading] = useState(false);
  const [calcualtedData, setCalculatedDate] = useState(null);
  const [isCalcualtedData, setIsCalcualtedData] = useState(false);
  const { investors, setInvestors, slideFromRight, IODetails } =
    useContext(GlobalStateContext);

  const [actionId, setActionId] = useState(false);

  const {
    isOpen: isConfirmOpen,
    onOpen: onConfirmOpen,
    onClose: onConfirmClose,
  } = useDisclosure();
  const {
    isOpen: isRejectOpen,
    onOpen: onRejectOpen,
    onClose: onRejectClose,
  } = useDisclosure();

  const investorExit = yup.object().shape({
    amount: yup
      .string()
      .required("Amount is required")
      .test(
        "max",
        `Distribution amount should not be greater than IO cash amount ${IODetails?.ioCash}`,
        function (value) {
          const { ioCash } = IODetails || {}; // Safely get ioCash
          if (value && ioCash) {
            return parseFloat(value) <= parseFloat(ioCash); // Ensure both are compared as numbers
          }
          return true; // If ioCash is not available, skip validation
        }
      ),
  });

  const {
    control,
    handleSubmit,
    formState: { errors },
    reset,
  } = useForm({
    resolver: yupResolver(investorExit),
  });

  useEffect(() => {
    console.log("hiit     useEffectc");
    if (id && IODetails) {
      handleCalculate(id, {
        amount: IODetails?.ioMVNAV,
      });
    }
    reset({
      amount: IODetails?.ioMVNAV,
    });
  }, [IODetails, id]);

  const handleCalculate = async (id, data) => {
    try {
      const res = await getDistributionInvestment({ id, data });
      console.log(res?.data?.data);

      if (res?.error?.status === 401) {
        setIsCalculateLoading(false);
        setIsCalcualtedData(false);
      } else if (res?.data?.statusCode === 200) {
        setCalculatedDate(res?.data?.data);
        setIsCalculateLoading(false);
        setIsCalcualtedData(true);
      }
    } catch (error) {}
  };

  const [getDistributionInvestment] = useGetDistributionInvestorMutation();

  const investor = yup.object().shape({
    amount: yup.string().required("Amount is required"),
  });

  // ====================================================[Table Setup]================================================================
  const tableHeadRow = [
    "Client ID",
    "First name",
    "Last name",
    "Investment amount",
    "Percentage",
    "Market Value",
    "Return on Investment",
    "Distribution",
    "Distribution Percent",
    "Total Return",
    "Total return on Investment",
  ];

  const extractedArray = IODetails?.investors?.map((item, index) => ({
    id: item?.id,
    "Client ID": (
      <Text
        justifyContent={slideFromRight ? "right" : "center"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {item?.clientReference_id}
      </Text>
    ),
    "First name": (
      <Text
        justifyContent={slideFromRight ? "right" : "center"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {item.firstName}
      </Text>
    ),
    "Last name": (
      <Text
        justifyContent={slideFromRight ? "right" : "center"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {item.lastName}
      </Text>
    ),
    "Investment amount": (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        <Badge ms={1} colorScheme="green" me={1}>
          $
        </Badge>
        {/* {`$${formatCurrency(item.InvestedAmount_USD)}`} */}
        {`${parseFloat(item.InvestedAmount_USD || 0).toLocaleString(undefined, {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2,
        })}`}
      </Text>
    ),
    Percentage: (
      <Text
        justifyContent={slideFromRight ? "right" : "center"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {item.Investor_Holidings} %
      </Text>
    ),
    "Market Value": (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        <Badge ms={1} colorScheme="green" me={1}>
          $
        </Badge>
        {`${parseFloat(item.Market_Value || 0).toLocaleString(undefined, {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2,
        })}`}
      </Text>
    ),
    "Return on Investment": (
      <Text
        justifyContent={slideFromRight ? "right" : "center"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        h={6}
        className="d-flex align-items-center web-text-small"
      >
        {item.Return_On_Investment || 0} %
      </Text>
    ),
    Distribution: (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        <Badge ms={1} colorScheme="green" me={1}>
          $
        </Badge>
        {/* {`$${item.Distribution_Amt}`} */}
        {`${parseFloat(item.Distribution_Amt || 0).toLocaleString(undefined, {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2,
        })}`}
      </Text>
    ),
    "Distribution Percent": (
      <Text
        justifyContent={slideFromRight ? "right" : "center"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {/* {`$${item.Distribution_Amt}`} */}
        {`${parseFloat(item.Distribution_Per || 0).toLocaleString(undefined, {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2,
        })} %`}
      </Text>
    ),
    "Total Return": (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        <Badge ms={1} colorScheme="green" me={1}>
          $
        </Badge>
        {/* {`$${formatCurrency(item.Total_Return) || 0}`} */}
        {`${parseFloat(item.Total_Return || 0).toLocaleString(undefined, {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2,
        })}`}
      </Text>
    ),
    "Total return on Investment": (
      <Text
        justifyContent={slideFromRight ? "right" : "center"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {item.Total_Return_On_Investment || 0} %
      </Text>
    ),
  }));

  const handleClose = () => {
    onClose();
    setIsFinalCalculateLoading(false);
    setIsCalcualtedData(false);
  };

  return (
    <Modal size={"xl"} isOpen={isOpen} onClose={handleClose}>
      <ModalOverlay />
      <ModalContent maxW={1000}>
        <ModalHeader fontSize={"md"}>Cancel Transaction</ModalHeader>
        <ModalCloseButton />
        <ModalBody>
          <NormalData
            emptyMessage={`We don't have any Sponers `}
            tableHeadRow={tableHeadRow}
            data={extractedArray}
          />
        </ModalBody>
        {!isMaker() && (
          <ModalFooter pt={0}>
            <Box display={"flex"} justifyContent={"center"} gap={2}>
              <Button
                rounded={"sm"}
                size={"xs"}
                textTransform={"inherit"}
                fontWeight={500}
                px={3}
                py={2}
                onClick={() => {
                  setActionId(id); // Use the `id` variable from params
                  onConfirmOpen();
                }}
                colorScheme="forestGreen"
                variant={"solid"}
                cursor={"pointer"}
              >
                Approve
              </Button>
              <Button
                rounded={"sm"}
                size={"xs"}
                textTransform={"inherit"}
                fontWeight={500}
                px={3}
                py={2}
                onClick={() => {
                  setActionId(id); // Use the `id` variable from params
                  onRejectOpen();
                }}
              >
                Reject
              </Button>
            </Box>
          </ModalFooter>
        )}
      </ModalContent>
      <ApprovedCancelTransaction
        isOpen={isConfirmOpen}
        onClose={onConfirmClose}
        onBigModalClose={onClose}
        id={cancleId}
      />
      <RequestRejectModal
        isOpen={isRejectOpen}
        onClose={onRejectClose}
        onBigModalClose={onClose}
        id={cancleId}
      />
    </Modal>
  );
};

export default ViewCancel;
