import {
  Button,
  Divider,
  Image,
  Menu,
  MenuButton,
  MenuItem,
  MenuList,
  Modal,
  ModalBody,
  ModalCloseButton,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalOverlay,
  Portal,
  Text,
  useDisclosure,
  MenuItemOption,
  MenuGroup,
  MenuOptionGroup,
  MenuDivider,
  Badge,
  Box,
  Icon,
  HStack,
  useToast,
} from "@chakra-ui/react";
import header from "../../../assets/IOheader.png";
import { HiDotsVertical } from "react-icons/hi";
import { Link, useParams } from "react-router-dom";
import AmountInvested from "./HeaderModal/AmountInvested";
import FeesExpenses from "./HeaderModal/FeesExpenses";
import DistributionSponsor from "./HeaderModal/DistributionSponsor";
import DistributionInvestor from "./HeaderModal/DistributionInvestor";
import UpdateIONav from "./HeaderModal/UpdateIONav";
import UpdateIOStatus from "./HeaderModal/UpdateIOStatus";
import { useContext, useRef } from "react";
import GlobalStateContext from "../../../Contexts/GlobalStateContext";
import Exit from "./HeaderModal/Exit";
import Cancle from "./HeaderModal/Cancle";
import { AddIcon } from "@chakra-ui/icons";
import { GrGallery } from "react-icons/gr";
import Loader01 from "../../../Components/Loaders/Loader01";
import { useUpdateTransactionMutation } from "../../../Services/io.service";
import ToastBox from "../../../Components/ToastBox";
import { encryptString } from "../../../Constants/Constants";
// import { formatCurrency } from "../../../Components/CurrencyInput";
// import { removeTrailingZeros } from "../../../Constants/Constants";

const ViewIOdataHeader = ({ data, isLoading }) => {
  const params = useParams() 
    const toast = useToast();
    const id = params?.id
  const { isOpen, onOpen, onClose } = useDisclosure();
  const btnRef = useRef();
  const { IODetails, isIOloading } = useContext(GlobalStateContext);

  const {
    isOpen: isInvestmentOpen,
    onOpen: onInvestmentOpen,
    onClose: onInvestmentClose,
  } = useDisclosure();
  const {
    isOpen: isFeesOpen,
    onOpen: onFeesOpen,
    onClose: onFeesClose,
  } = useDisclosure();
  const {
    isOpen: isDistSponsorOpen,
    onOpen: onDistSponsorOpen,
    onClose: onDistSponsorClose,
  } = useDisclosure();
  const {
    isOpen: isDistInvestorOpen,
    onOpen: onDistInvestorOpen,
    onClose: onDistInvestorClose,
  } = useDisclosure();
  const {
    isOpen: isUpdateNavOpen,
    onOpen: onUpdateNavOpen,
    onClose: onUpdateNavClose,
  } = useDisclosure();
  const {
    isOpen: isUpdateStatusOpen,
    onOpen: onUpdateStatusOpen,
    onClose: onUpdateStatusClose,
  } = useDisclosure();
  const {
    isOpen: isExitOpen,
    onOpen: onExitOpen,
    onClose: onExitClose,
  } = useDisclosure();
  const {
    isOpen: isCancleOpen,
    onOpen: onCancleOpen,
    onClose: onCancleClose,
  } = useDisclosure();
  const bg = {
    bg: "#fff",
  };
  const hover = {
    textDecoration: "underline",
    background: "#fff",
  };
  const style = {
    fontSize: "0.875rem",
    fontWeight: "400",
  };

  console.log(
    import.meta.env.VITE_IMAGE_URL +
      IODetails?.artifactsImage?.[0]?.artifactPathName
  );

  const [updateTransaction] = useUpdateTransactionMutation()

  const handleDistributionInvestors = async () =>{
    
    try {
       const res = await updateTransaction(id)
       
       if (res?.data) {
        //  toast({
        //    render: () => (
        //     <ToastBox status={"success"} message={res?.data?.message} />
        //    ),
        //  });
        //  setIsLoading(false);
        onDistInvestorOpen()
 
       } else if (res?.error) {
         toast({
           render: () => (
             <ToastBox status={"error"} message={res?.error?.data?.message} />
           ),
         });
        //  setIsLoading(false);
       }
    } catch (error) { 
     
    }
   }

   const handleExit = async () =>{
    
    try {
       const res = await updateTransaction(id)
       
       if (res?.data) {
        //  toast({
        //    render: () => (
        //     <ToastBox status={"success"} message={res?.data?.message} />
        //    ),
        //  });
        //  setIsLoading(false);
        onExitOpen()
 
       } else if (res?.error) {
         toast({
           render: () => (
             <ToastBox status={"error"} message={res?.error?.data?.message} />
           ),
         });
        //  setIsLoading(false);
       }
    } catch (error) { 
     
    }
   }

   const handleInvestment = async () =>{
    
    try {
       const res = await updateTransaction(id)
       
       if (res?.data) {
        //  toast({
        //    render: () => (
        //     <ToastBox status={"success"} message={res?.data?.message} />
        //    ),
        //  });
        //  setIsLoading(false);
        onInvestmentOpen()
 
       } else if (res?.error) {
         toast({
           render: () => (
             <ToastBox status={"error"} message={res?.error?.data?.message} />
           ),
         });
        //  setIsLoading(false);
       }
    } catch (error) { 
     
    }
   }
   

  const menu = [
    {
      id: 1,
      title: "Amount Invested",
      onClickFunction: handleInvestment,
    },
    // {
    //   id:2,
    //   title:"Fees & Expenses",
    //   onClickFunction:onFeesOpen
    // },
    // {
    //   id:3,
    //   title:"Distribution From Sponsors",
    //   onClickFunction:onDistSponsorOpen
    // },
    {
      id: 6,
      title: "Distribution To Investors",
      onClickFunction: handleDistributionInvestors,
    }, 
    {
      id: 5,
      title: "Update IO NAV",
      onClickFunction: onUpdateNavOpen,
    },
    {
      id: 8,
      title: "Exit",
      onClickFunction: handleExit,
    },
    {
      id: 9,
      title: "Cancel",
      onClickFunction: onCancleOpen,
    },
    {
      id: 10,
      title: "Update IO Status",
      onClickFunction: onUpdateStatusOpen,
    },
  ];

  // console.log(IODetails?.mainTranscation);

  // Extract titles from apiTransaction
  const apiTransactionTitles = IODetails?.mainTranscation?.map(
    (transaction) => transaction.id
  );
  // Filter menu items
  const filteredMenu = menu?.filter((item) =>
    apiTransactionTitles?.includes(item.id)
  );


  const balanceAmount = IODetails?.goalAmount - IODetails?.totalAmtInvestmentInUSD

  return IODetails?.investmentNameEnglish ? (
    <Box
      display={"flex"}
      alignItems={"center"}
      justifyContent={"space-between"}
      gap={8}
      bg={
        IODetails?.ioStatus?.statusAdmin === "Draft"
          ? "#EDF2F7"
          : IODetails?.ioStatus?.statusAdmin === "Processing"
          ? "#FEFBBF"
          : IODetails?.ioStatus?.statusAdmin === "Open"
          ? "#BEE2F8"
          : IODetails?.ioStatus?.statusAdmin === "Closed"
          ? "#C6F6D5"
          : IODetails?.ioStatus?.statusAdmin === "Exited"
          ? "#FED7D7"
          : IODetails?.ioStatus?.statusAdmin === "Cancelled"
          ? "#E9D8FD"
          : IODetails?.ioStatus?.statusAdmin === "DeActivate"
          ? "#E9D8FD"
          : null
      }
      rounded={"md"}
      // bgGradient='linear(to-r, #caf5d8, #f5e8ca)'
      // bgGradient='linear(to-r, #caf5d8, #d4a5a5)'
      // bgGradient='linear(to-r, #caf5d8, #d4a5a5)'
      // bgGradient='linear(to-r, #caf5d8, #b3e5fc)'
      // bgGradient='linear(to-r, #ffd54f, #caf5d8)'
      // bgGradient='linear(to-r, #caf5d8, #a8e6cf)'
      boxShadow={"md"}
      position={"relative"}
    >
      <HStack gap={4}>
        <Box h={100} w={200} p={1.5}>
          {/* <Image rounded={'md'} h={"100%"} src={ " https://tanami.betadelivery.com/" + IODetails?.ioName} alt={IODetails?.ioName}/> */}
          {IODetails?.artifactsImage?.[0]?.artifactPathName ? (
            <Image
              rounded={"md"}
              h={"100%"}
              w={"100%"}
              objectFit={"cover"}
              src={
                import.meta.env.VITE_IMAGE_URL +
                IODetails?.artifactsImage?.[0]?.artifactPathName
              }
              alt={IODetails?.ioName}
            />
          ) : (
            <Box
              w={"100%"}
              h={"100%"}
              display={"flex"}
              justifyContent={"center"}
              alignItems={"center"}
              bg={"#fff"}
              rounded={"md"}
            >
              <Icon color={"gray.700"} as={GrGallery} />
            </Box>
          )}
        </Box>

        <Box>

          <Box display={"flex"} gap={2} pb={1}>
            <Text
              as={"span"}
              fontSize={"xs"}
              color={"gray.500"}
              fontWeight={"500"}
              me={2}
            >
              IO Name :-
            </Text>
            <Text as={"span"} fontSize={"xs"} fontWeight={"500"}>
              {IODetails?.investmentNameEnglish
                ? IODetails?.investmentNameEnglish
                : "---"}
            </Text>
          </Box>

          <Box  display={"flex"} gap={2} pb={1}>
            <Text
              as={"span"}
              fontSize={"xs"}
              color={"gray.500"}
              fontWeight={"500"}
              me={2}
            >
              Sponsor Name :-
            </Text>
            <Text as={"span"} fontSize={"xs"} fontWeight={"500"}>
              {IODetails?.sponsor?.sponsorName
                ? IODetails?.sponsor?.sponsorName
                : "---"}
            </Text>
          </Box>

          <Box  display={"flex"}  gap={2} pb={1}>
            <Text
              as={"span"}
              fontSize={"xs"}
              color={"gray.500"}
              fontWeight={"500"}
              me={2}
            >
              IO ID :-
            </Text>
            <Text as={"span"} fontSize={"xs"} fontWeight={"500"}>
              {IODetails?.io_id
                ? IODetails?.io_id
                : "---"}
            </Text>
          </Box>
          
        </Box>
        
      </HStack>
       
      <Box gap={8} me={12} w={"220px"}>

        <Box display={"flex"} justifyContent={"space-between"} gap={2} pb={1}>
          <Text
            as={"span"}
            fontSize={"xs"}
            color={"gray.500"}
            fontWeight={"500"}
          >
            Goal Amount :-
          </Text>
          <Text as={"span"} fontSize={"xs"} fontWeight={"500"}>
            {/* {IODetails?.ioNAV ? formatCurrency(removeTrailingZeros(IODetails?.ioNAV)) : "00.00"} */}
            {parseFloat(IODetails?.goalAmount || 0).toLocaleString(undefined, {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            })}
          </Text>
        </Box>

        <Box display={"flex"} justifyContent={"space-between"} gap={2} pb={1}>
          <Text
            as={"span"}
            fontSize={"xs"}
            color={"gray.500"}
            fontWeight={"500"}
          >
            Amount Raised :-
          </Text>
          <Text as={"span"} fontSize={"xs"} fontWeight={"500"}>
            {/* {IODetails?.ioCash ? formatCurrency(removeTrailingZeros(IODetails?.ioCash)) : "00.00"} */}
            {parseFloat(IODetails?.totalAmtInvestmentInUSD || 0).toLocaleString(undefined, {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            })}
          </Text>
        </Box>

        <Box display={"flex"} justifyContent={"space-between"} gap={2}>
          <Text
            as={"span"}
            fontSize={"xs"}
            color={"gray.500"}
            fontWeight={"500"}
          >
            Balance :-
          </Text>
          <Text as={"span"} fontSize={"xs"} fontWeight={"500"}>
            {/* {IODetails?.ioMVNAV ? formatCurrency(removeTrailingZeros(IODetails?.ioMVNAV)) : "00.00"} */}
            {parseFloat(balanceAmount || 0).toLocaleString(undefined, {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            })}
          </Text>
        </Box>
      </Box>

      <Box gap={8} me={12} w={"180px"}>
        <Box display={"flex"} justifyContent={"space-between"} gap={2} pb={1}>
          <Text
            as={"span"}
            textAlign={"center"}
            fontSize={"xs"}
            color={"gray.500"}
            fontWeight={"500"}
          >
            IO Status :-
          </Text>
          <Badge
            rounded={"full"}
            pt={0}
            pb={0.5}
            textTransform={"none"}
            // variant={"solid"}
            colorScheme={
              IODetails?.ioStatus?.statusAdmin === "Draft"
                ? "gray"
                : IODetails?.ioStatus?.statusAdmin === "Processing"
                ? "yellow"
                : IODetails?.ioStatus?.statusAdmin === "Open"
                ? "blue"
                : IODetails?.ioStatus?.statusAdmin === "Closed"
                ? "green"
                : IODetails?.ioStatus?.statusAdmin === "Exited"
                ? "red"
                : IODetails?.ioStatus?.statusAdmin === "Cancelled"
                ? "purple"
                : "purple"
            }
          >
            {IODetails?.ioStatus?.statusAdmin
              ? IODetails?.ioStatus?.statusAdmin
              : "---"}
          </Badge>
        </Box>

        <Box display={"flex"} justifyContent={"space-between"} gap={2} pb={1}>
          <Text
            as={"span"}
            fontSize={"xs"}
            color={"gray.500"}
            fontWeight={"500"}
          >
            IO MV :-
          </Text>
          <Text as={"span"} fontSize={"xs"} fontWeight={"500"}>
            {/* {IODetails?.ioNAV ? formatCurrency(removeTrailingZeros(IODetails?.ioNAV)) : "00.00"} */}
            {parseFloat(IODetails?.ioNAV || 0).toLocaleString(undefined, {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            })}
          </Text>
        </Box>

        <Box display={"flex"} justifyContent={"space-between"} gap={2} pb={1}>
          <Text
            as={"span"}
            fontSize={"xs"}
            color={"gray.500"}
            fontWeight={"500"}
          >
            IO cash :-
          </Text>
          <Text as={"span"} fontSize={"xs"} fontWeight={"500"}>
            {/* {IODetails?.ioCash ? formatCurrency(removeTrailingZeros(IODetails?.ioCash)) : "00.00"} */}
            {parseFloat(IODetails?.ioCash || 0).toLocaleString(undefined, {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            })}
          </Text>
        </Box>

        <Box display={"flex"} justifyContent={"space-between"} gap={2}>
          <Text
            as={"span"}
            fontSize={"xs"}
            color={"gray.500"}
            fontWeight={"500"}
          >
            IO NAV :-
          </Text>
          <Text as={"span"} fontSize={"xs"} fontWeight={"500"}>
            {/* {IODetails?.ioMVNAV ? formatCurrency(removeTrailingZeros(IODetails?.ioMVNAV)) : "00.00"} */}
            {parseFloat(IODetails?.ioMVNAV || 0).toLocaleString(undefined, {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            })}
          </Text>
        </Box>
      </Box>

      <Box
        position={"absolute"}
        right={3}
        top={2}
        display={"flex"}
        alignItems={"start"}
        height={"95px"}
      >
        {localStorage?.getItem("role") === encryptString(import.meta.env.VITE_VITE_MAKER) && <Menu>
          <MenuButton 
            className="link p-1 rounded-1 "
            bg={"#fff"}
            _hover={{ backgroundColor: "#fff !important" }}
            onClick={onOpen}
            ref={btnRef}
          >
            <HiDotsVertical className="rubix-text-dark fs-6" />
          </MenuButton>
          <MenuList fontSize={"sm"}>
            <MenuItem
              _hover={{
                bg: "#fff",
              }}
              as={"span"}
              fontWeight={600}
              className="border-bottom"
            >
              Tansaction
            </MenuItem>

            {filteredMenu?.map(({ id, title, onClickFunction }) => (
              <MenuItem
                key={id}
                onClick={onClickFunction}
                className="border-bottom"
              >
                {title}
              </MenuItem>
            ))}
          </MenuList>
        </Menu>}

        {/* Modals */}
        <AmountInvested isOpen={isInvestmentOpen} onClose={onInvestmentClose} />
        <FeesExpenses isOpen={isFeesOpen} onClose={onFeesClose} />
        <Exit isOpen={isExitOpen} onClose={onExitClose} />
        <Cancle isOpen={isCancleOpen} onClose={onCancleClose} />
        <DistributionSponsor
          isOpen={isDistSponsorOpen}
          onClose={onDistSponsorClose}
        />
        <DistributionInvestor
          isOpen={isDistInvestorOpen}
          onClose={onDistInvestorClose}
        />

        <UpdateIONav isOpen={isUpdateNavOpen} onClose={onUpdateNavClose} />
        <UpdateIOStatus
          status={IODetails?.nextStatus}
          isOpen={isUpdateStatusOpen}
          onClose={onUpdateStatusClose}
        />
      </Box>
    </Box>
  ) : (
    <Box
      display={"flex"}
      alignItems={"center"}
      justifyContent={"center"}
      rounded={"md"}
      height={100}
      bg={"#fff"}
      // bgGradient='linear(to-r, #caf5d8, #f5e8ca)'
      // bgGradient='linear(to-r, #caf5d8, #d4a5a5)'
      // bgGradient='linear(to-r, #caf5d8, #d4a5a5)'
      // bgGradient='linear(to-r, #caf5d8, #b3e5fc)'
      // bgGradient='linear(to-r, #ffd54f, #caf5d8)'
      // bgGradient='linear(to-r, #caf5d8, #a8e6cf)'
      boxShadow={"md"}
    >
      {" "}
      <Loader01 />
    </Box>
  );
};

export default ViewIOdataHeader;
