import {
  Box,
  Button,
  Modal,
  ModalBody,
  ModalCloseButton,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalOverlay,
  Text,
  useDisclosure,
  useToast,
} from "@chakra-ui/react";
import NormalData from "../../../../Components/DataTable/NormalTable";
import { useContext, useState } from "react";
import { useGetDistributionInvestorMutation } 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 GlobalStateContext from "../../../../Contexts/GlobalStateContext";
import ApproveDistrubationModal from "./ApproveDistrubationModal";
import RequestRejectModal from "./RequestRejectModal";
import { encryptString, isMaker } from "../../../../Constants/Constants";

const ViewDistributionInvestor = ({ isOpen, onClose, id: exitId, amount }) => {
  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 { IODetails } = useContext(GlobalStateContext);
  const [actionId, setActionId] = useState(false);

  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 {
    isOpen: isConfirmOpen,
    onOpen: onConfirmOpen,
    onClose: onConfirmClose,
  } = useDisclosure();
  const {
    isOpen: isRejectOpen,
    onOpen: onRejectOpen,
    onClose: onRejectClose,
  } = useDisclosure();

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

  useEffect(() => {
    if (id && IODetails) {
      handleCalculate(id, {
        amount: Math.abs(amount),
      });
    }
    reset({
      amount: amount,
    });
  }, [IODetails, id, amount]);

  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(false);
      }
    } catch (error) {}
  };

  const [getDistributionInvestment] = useGetDistributionInvestorMutation();

  // ====================================================[Table Setup]================================================================
  const tableHeadRow = [
    "Sr No.",
    "Client Id",
    "First name",
    "Last Name",
    "Amount",
    "Holding (%)",
    "Distribution Amt($)",
    "Yeild (%)",
  ];

  const extractedArray = calcualtedData?.data?.map((item, index) => ({
    id: item?.id,
    "Sr No.": (
      <Box
        w={9}
        display={"flex"}
        alignItems={"center"}
        isTruncated={true}
        h={25}
      >
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
          {index + 1}
        </Text>
      </Box>
    ),
    "Client Id": (
      <Box w={90} isTruncated={true}>
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
          {item?.clientId}
        </Text>
      </Box>
    ),
    "First name": (
      <Box w={90} isTruncated={true}>
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
          {item?.firstName}
        </Text>
      </Box>
    ),
    "Last Name": (
      <Box minW={24} isTruncated={true}>
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
          {item?.lastName}
        </Text>
      </Box>
    ),
    Amount: (
      <Box minW={24} isTruncated={true}>
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
          {item?.amount?.toLocaleString(undefined, {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
          })}
        </Text>
      </Box>
    ),
    "Holding (%)": (
      <Box minW={24} isTruncated={true}>
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
          {item?.investor_holidings?.toLocaleString(undefined, {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
          })}
          %
        </Text>
      </Box>
    ),
    "Distribution Amt($)": (
      <Box minW={24} isTruncated={true}>
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
          {item?.distribution_amt?.toLocaleString(undefined, {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
          })}
        </Text>
      </Box>
    ),
    "Yeild (%)": (
      <Box minW={24} isTruncated={true}>
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
          {item?.distribution_per?.toLocaleString(undefined, {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
          })}
          %
        </Text>
      </Box>
    ),
  }));

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

  return (
    <Modal size={"xl"} isOpen={isOpen} onClose={handleClose}>
      <ModalOverlay />
      <ModalContent maxW={1000}>
        <ModalHeader fontSize={"md"}>
          Distribution To Investor Transaction
        </ModalHeader>
        <ModalCloseButton />
        <ModalBody>
          <NormalData
            emptyMessage={`We don't have any Sponers `}
            tableHeadRow={tableHeadRow}
            data={extractedArray}
          />
        </ModalBody>
        {/* ...(localStorage?.getItem("role") !== "Maker" ? ["Status"] : []), */}
        {!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>
      <ApproveDistrubationModal
        isOpen={isConfirmOpen}
        onClose={onConfirmClose}
        onBigModalClose={handleClose}
        id={exitId}
      />
      <RequestRejectModal
        isOpen={isRejectOpen}
        onClose={onRejectClose}
        onBigModalClose={handleClose}
        id={exitId}
      />
    </Modal>
  );
};

export default ViewDistributionInvestor;
