import {
    Alert,
    AlertIcon,
    Box,
    Button,
    FormControl,
    FormErrorMessage,
    FormLabel,
    HStack,
    Input,
    Modal,
    ModalBody,
    ModalCloseButton,
    ModalContent,
    ModalFooter,
    ModalHeader,
    ModalOverlay,
    Switch,
    Table,
    Tbody,
    Text,
    Textarea,
    Th,
    Tr,
    useDisclosure,
    useToast,
  } from "@chakra-ui/react";
  import NormalData from "../../../../Components/DataTable/NormalTable";
  import { useContext, useState } from "react";
  import { AddIcon } from "@chakra-ui/icons";
  import {
    useExitIOTransactionMutation,
    useGetDistributedToInvestorMutation,
    useGetDistributionInvestorMutation,
    useUpdateExitToInvestorMutation,
  } from "../../../../Services/io.service";
  import { useParams } from "react-router-dom";
  import { useEffect } from "react";
  import { Controller, 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 ApprovedExit from "./ApprovedExit";
import RequestRejectModal from "./RequestRejectModal";
  
  const ViewExit = ({ isOpen, onClose ,id:investerId}) => {
    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 {
      isOpen: isConfirmOpen,
      onOpen: onConfirmOpen,
      onClose: onConfirmClose,
    } = useDisclosure();
    const {
      isOpen: isRejectOpen,
      onOpen: onRejectOpen,
      onClose: onRejectClose,
    } = useDisclosure();
  
  
    const {
      control,
      handleSubmit,
      formState: { errors },
      reset,
    } = useForm({
      resolver: yupResolver(),
    });
  
    // useEffect(() => {
    //   console.log("hiit     useEffectc");
    //   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 = [
      "Sr No.",
      "Client Id",
      "First name",
      "Last Name",
      "Amount",
      "Holding (%)",
      "Exit Amt($)",
    ];

    
  
    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={100} isTruncated={true}>
          <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
            {item?.clientId}
          </Text>
        </Box>
      ),
      "First name": (
        <Box minW={24} 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>
      ),
      "Exit 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>
      ),
    }));
  
    const onSubmit = async (data) => {
      setIsCalculateLoading(true);
  
      try {
        const res = await getDistributionInvestment({ id, data });
        console.log(res?.data?.data);
  
        if (res?.error?.status === 401) {
          toast({
            render: () => (
              <ToastBox message={res?.error?.data?.message} status={"error"} />
            ),
          });
          setIsCalculateLoading(false);
          setIsCalcualtedData(false);
        } else if (res?.data?.statusCode === 200) {
          setCalculatedDate(res?.data?.data);
          toast({
            render: () => <ToastBox message={res?.data?.message} />,
          });
          setIsCalculateLoading(false);
          setIsCalcualtedData(true);
        }
      } catch (error) {}
    };
  
    const handleClose = () => {
      onClose();
      setIsFinalCalculateLoading(false);
      setIsCalcualtedData(false);
    };
    
    console.log(id);
    

    return (
      <Modal size={"xl"} isOpen={isOpen} onClose={handleClose} >
        <ModalOverlay />
        <ModalContent maxW={1000}>
          <ModalHeader fontSize={"md"}>Exit Transaction</ModalHeader>
          <ModalCloseButton />
          <ModalBody>
            {/* <Text as="label" mb="5px" fontSize="sm" fontWeight={500}>
              Amount to Distribute
            </Text> */}
            <HStack onSubmit={handleSubmit(onSubmit)} as={"form"} mb={4} alignItems={'center'}>
              {/* <Input placeholder="$00.00" size={"sm"} className="col" /> */}
              {/* <FormControl isInvalid={errors.amount} isRequired>*/}
                <Text textAlign={"right"} fontSize={"sm"}>
                  Exit Amount :
                </Text> 
              <Text
                textAlign={"start"}
                bg={"green.100"}
                p={2}
                rounded={"md"}
                fontSize={"sm"}
                pt={1}
                pb={1}
                fontWeight={600}
              >
                ${" "}
                {parseFloat(IODetails?.ioMVNAV || 0).toLocaleString(undefined, {
                  minimumFractionDigits: 2,
                  maximumFractionDigits: 2,
                })}
              </Text>
  
              {/* </FormControl> */}
            </HStack>
  
            {/* {calcualtedData && ( */}
            <NormalData
              emptyMessage={`We don't have any Sponers `}
              tableHeadRow={tableHeadRow}
              data={extractedArray}
              // total={<Total />}
              // isLoading={isLoading}
            />
            {/* ) } */}
          </ModalBody>
          {localStorage?.getItem("role") !== "Maker" && <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>
        <ApprovedExit
            isOpen={isConfirmOpen}
            onClose={onConfirmClose}
            onBigModalClose={onClose}
            id={investerId}
        />
        <RequestRejectModal
            isOpen={isRejectOpen}
            onClose={onRejectClose}
            onBigModalClose={onClose}
            id={investerId}
        />
      </Modal>
    ); 
  };
  
  export default ViewExit;
  