import {
  Box,
  Container,
  Grid,
  GridItem,
  Heading,
  HStack,
  Icon,
  Image,
  Select,
  Text,
  Tooltip,
  useColorMode,
  useToast,
  VStack,
} from "@chakra-ui/react";
import React, { useContext, useEffect, useState } from "react";
import bannerImage from "../assets/images/bannerImg.png";
import GlobalStateContext from "../Contexts/GlobalStateContext";
import Pagination from "../components/Pagination";
import { MdContentCopy, MdOutlineErrorOutline } from "react-icons/md";
import ToastBox from "../components/ToastBox";
import { Link, useNavigate } from "react-router-dom";
import {
  useGetMainNetCountQuery,
  useGetMainNetQuery,
} from "../Services/api.service";
import { formatRelativeDate, formatUTCToDDMMYYHHMMSS } from "../Constants/Constants";
import rbtLogoOutline from "../assets/images/rubix-filled.svg";
import FullScreenLoaader from "../components/FullScreenLoaader/FullScreenLoaader";
import { OPACITY_ON_LOAD } from "../Layout/animations";
import { HiOutlineRefresh } from "react-icons/hi";
import rbtLogoDark from "../assets/images/RBTNewLogo.png";
import { rotate } from "../components/LatestTransactions/LatestTransactions";
import SplashScreen from "./SplashScreen";

const MainNet = () => {
  const { overview } = useContext(GlobalStateContext);
  const { colorMode } = useColorMode();
  const navigate = useNavigate();
  const toast = useToast();

  const [isRotating, setIsRotating] = useState(false);
  const [currentPage, setCurrentPage] = useState(1); // Tracks the current page
  const [pageSize, setPageSize] = useState(10); // Number of items per page
  const [totalItems, setTotalItems] = useState(null); // Total items in the dataset
  const [lastRefreshedTime, setLastRefreshedTime] = useState(new Date()); // Store the last refresh time
  const [relativeRefreshTime, setRelativeRefreshTime] = useState("Just now");

  const {
    data: transGetMainNetCount,
    isLoading: isTransGetMainNetCountLoading,
    refetch: transGetMainNetCountRefetch,
  } = useGetMainNetCountQuery();


  const {
    data: mainNetData,
    isLoading: isMainNetDataLoading,
    isFetching,
    refetch: mainNetRefetch,
  } = useGetMainNetQuery({
    pageNumber: currentPage,
    pageSize: pageSize,
  });

  
  

  useEffect(() => {
    setTotalItems(transGetMainNetCount?.data?.transactionCount);
  }, [transGetMainNetCount]);

  function copyToClipboard(text) {
    navigator.clipboard
      .writeText(text)
      .then(() => {
        toast({
          render: () => (
            <ToastBox status={"warn"} message={"Text copied to clipboard"} />
          ),
        });
      })
      .catch((err) => {
        console.error("Failed to copy text: ", err);
      });
  }



  useEffect(() => {
    // Update relative time every minute
    const intervalId = setInterval(() => {
      updateRelativeTime();
    }, 60000); // 60 seconds = 60000ms

    return () => clearInterval(intervalId); // Cleanup the interval on unmount
  }, [lastRefreshedTime]);


  const updateRelativeTime = () => {
    const now = new Date();
    const timeDiff = Math.floor((now - lastRefreshedTime) / 60000); // Difference in minutes

    if (timeDiff < 1) {
      setRelativeRefreshTime("Just now");
    } else if (timeDiff === 1) {
      setRelativeRefreshTime("1 minute ago");
    } else {
      setRelativeRefreshTime(`${timeDiff} minutes ago`);
    }
  };

  const handleRefreshClick = () => {
    setIsRotating(true); // Start rotation
    mainNetRefetch();
    setTimeout(() => {
      setIsRotating(false); // Stop rotation after 500ms
    }, 500);
    setLastRefreshedTime(new Date()); // Set the new refresh time
    setRelativeRefreshTime("Just now"); // Reset relative time to "Just now"
  };

  return isTransGetMainNetCountLoading || isMainNetDataLoading || isFetching ? (
    <FullScreenLoaader />
    // <SplashScreen/>
  ) : (
    <Box
      bg={colorMode === "light" ? "#ECEBF2" : "none"}
      minH={"100vh"}
      {...OPACITY_ON_LOAD}
      p={"6rem 0 4rem 0"}
      backgroundImage={colorMode !== "light" ? `url(${bannerImage})` : "none"}
      position={"relative"}
      backgroundSize="contain"
      backgroundRepeat="no-repeat"
    >
      <Container
        maxW="6xl"
        color="white"
        display={{ base: "block", md: "flex" }}
        justifyContent={"space-between"}
        mb={6}
      >
        <Text
          fontSize={"md"}
          fontWeight={500}
          color={colorMode === "light" ? "#000" : "#fff"}
          mb={{ base: "10px", md: "0px" }}
        >
          Main Net - Overview
        </Text>
        <HStack to="" style={{ fontSize: "14px" }} color={colorMode === "light" ? "#000" : "#fff"} display={"flex"} gap={"3"}>
          {/* <Text as={"span"}>Total Value Locked (TVL)</Text> <Text as={"span"}>{Number(mainNetData?.data?.tvl).toFixed(3)} RBT</Text> */}
          <Text as={"span"}>Total Value Locked (TVL)</Text> <Text as={"span"}>{mainNetData?.data?.tvl} $ Mn</Text>
        </HStack>
      </Container>
      <Box>
        <Container maxW="6xl">
          <Grid
        position={"relative"}
            templateColumns={{ base: "100% 0%", md: "10% 90%" }}
            gap={0}
            bg={colorMode === "light" ? "#230A79" : "#232127"}
            // bg={"#232127"}
            borderTopRightRadius={4}
            borderTopLeftRadius={4}
          >
            <GridItem ps={3} p={2} display={{ base: "none", md: "grid" }}>
              <Text color={"#fff"}>Sr. no</Text>
            </GridItem>
            <GridItem p={2}>
              <Text color={"#fff"}>Transactions</Text>
            </GridItem>

        <Box
          as="span"
          cursor={"pointer"}
          position={"absolute"}
          right={0}
          m={1.5}
          display={'flex'}
          alignItems={'center'}
          gap={2}
          onClick={handleRefreshClick} // Trigger the rotation when clicked
        >
          <Text as={'span'} fontSize={'xs'} color={colorMode==="light"?'#fff':"#ccc"}>Last refresh {relativeRefreshTime} </Text>
          <Icon
            bg={colorMode==="light"?'#fff':"#434147"}
            p={1.5}
            boxSize={7}
            rounded={"full"}
            as={HiOutlineRefresh}
            animation={
              isRotating || isMainNetDataLoading
                ? `${rotate} 1s linear infinite`
                : "none"
            }
          />
        </Box>
          </Grid>
          <Box boxShadow={"rgba(99, 99, 99, 0.2) 0px 2px 8px 0px;"}>
            {mainNetData?.data?.items?.map(
              (
                {
                  transactionId,
                  smartContract,
                  sender,
                  receiver,
                  contract,
                  timestamp,
                  amount,
                  transactionType,
                  subNetworkId,




              executor,
              deployer,
              creator,
              pledgeAmount,
              scTokenHash
                },
                index
              ) => (
            <Grid
              bg={
                index % 2 === 0
                  ? colorMode === "light"
                    ? "#ECEBF2"
                    : "#312F35"
                  : colorMode === "light"
                  ? "#fff"
                  : "#232127"
              }
              key={transactionId}
              templateColumns={{ base: "100% 0%", md: "10% 90%" }}
              gap={0}
            >
              <GridItem
                display={{ base: "none", md: "grid" }}
                p={4}
                color={colorMode === "light" ? "#000" : "#fff"}
              >
                {index + 1}.
              </GridItem>
              <GridItem p={4}>
                {/* <Box> */}
                <Text // This ensures the text is truncated with ellipsis when it overflows ss__298
                  display={"flex"}
                  fontSize={{ base: "xs", md: "sm" }}
                  mb={2}
                  color={colorMode === "light" ? "#230A79" : "#B09AFF"}
                >
                  <Text
                    maxW={{ base: "100%", md: "100%" }} // Set a max-width to control when the truncation happens
                    // overflow={'hidden'} // Ensure overflow is hidden
                    whiteSpace={"nowrap"} // Prevent the text from wrapping
                    textOverflow={"ellipsis"}
                    isTruncated
                    cursor={"pointer"}
                    onClick={() => navigate(`/transaction/${transactionId}`)}
                  >
                    {transactionId}
                  </Text>

                  <Text
                    _hover={{ bg: "gray.50" }}
                    transition={"0.5s"}
                    rounded={"sm"}
                    p={1}
                    as={"span"}
                    ml={1}
                    cursor={"pointer"}
                  >
                    <MdContentCopy
                      onClick={() => copyToClipboard(transactionId)}
                    />
                  </Text>
                </Text>

                {sender&&<HStack
                  fontSize={{ base: "xs", md: "sm" }}
                  gap={{ base: 2, md: 4 }}
                  mb={2}
                >
                  <Text color={colorMode === "light" ? "#0F0F0F" : "#E8E8E8"}>
                    Sender:
                  </Text>

                  <HStack
                    color={colorMode === "light" ? "#230A79" : "#B09AFF"}
                    textDecoration={"underline"}
                    w={"84%"}
                    // justifyContent={'space-between'}
                    fontSize={{ base: "xs", md: "sm" }}
                    isTruncated
                  >
                    <Text
                      cursor={"pointer"}
                      maxW={{ base: "90%", md: "100%" }} // Set a max-width to control when the truncation happens
                      // overflow={'hidden'} // Ensure overflow is hidden
                      whiteSpace={"nowrap"} // Prevent the text from wrapping
                      textOverflow={"ellipsis"}
                      isTruncated
                      onClick={() => navigate(`/did-info/${sender}`)}
                    >
                      {sender}
                    </Text>
                    <Text
                      _hover={{ bg: "gray.50" }}
                      transition={"0.5s"}
                      rounded={"sm"}
                      p={1}
                      as={"span"}
                      ml={1}
                      cursor={"pointer"}
                    >
                      <MdContentCopy onClick={() => copyToClipboard(sender)} />
                    </Text>
                  </HStack>
                </HStack>}
                {receiver&&<HStack
                  fontSize={{ base: "xs", md: "sm" }}
                  cursor={"pointer"}
                  gap={{ base: 2, md: 4 }}
                  mb={3}
                >
                  <Text color={colorMode === "light" ? "#0F0F0F" : "#E8E8E8"}>
                    Receiver:
                  </Text>
                  <HStack
                    color={colorMode === "light" ? "#230A79" : "#B09AFF"}
                    textDecoration={"underline"}
                    fontSize={{ base: "xs", md: "sm" }}
                    isTruncated
                  >
                    <Text
                      cursor={"pointer"}
                      maxW={{ base: "55%", md: "100%" }}
                      whiteSpace={"nowrap"} // Prevent the text from wrapping
                      textOverflow={"ellipsis"}
                      isTruncated
                      onClick={() => navigate(`/did-info/${receiver}`)}
                    >
                      {receiver}
                    </Text>
                    <Text
                      _hover={{ bg: "gray.50" }}
                      transition={"0.5s"}
                      rounded={"sm"}
                      p={1}
                      as={"span"}
                      ml={1}
                      cursor={"pointer"}
                    >
                      <MdContentCopy
                        onClick={() => copyToClipboard(receiver)}
                      />
                    </Text>
                  </HStack>
                </HStack>}



                {creator&&<HStack
                  fontSize={{ base: "xs", md: "sm" }}
                  cursor={"pointer"}
                  gap={{ base: 2, md: 4 }}
                  mb={3}
                >
                  <Text color={colorMode === "light" ? "#0F0F0F" : "#E8E8E8"}>
                    Creator:
                  </Text>
                  <HStack
                    color={colorMode === "light" ? "#230A79" : "#B09AFF"}
                    textDecoration={"underline"}
                    isTruncated
                    fontSize={{ base: "xs", md: "sm" }}
                  >
                    <Text
                      cursor={"pointer"}
                      maxW={{ base: "55%", md: "100%" }}
                      whiteSpace={"nowrap"} // Prevent the text from wrapping
                      textOverflow={"ellipsis"}
                      isTruncated
                      onClick={() => navigate(`/did-info/${creator}`)}
                    >
                      {creator}
                    </Text>
                    <Text
                      _hover={{ bg: "gray.50" }}
                      transition={"0.5s"}
                      rounded={"sm"}
                      p={1}
                      as={"span"}
                      ml={1}
                      cursor={"pointer"}
                    >
                      <MdContentCopy
                        onClick={() => copyToClipboard(creator)}
                      />
                    </Text>
                  </HStack>
                </HStack>}

                {executor&&<HStack
                  fontSize={{ base: "xs", md: "sm" }}
                  cursor={"pointer"}
                  gap={{ base: 2, md: 4 }}
                  mb={3}
                >
                  <Text color={colorMode === "light" ? "#0F0F0F" : "#E8E8E8"}>
                    Executor:
                  </Text>
                  <HStack
                    color={colorMode === "light" ? "#230A79" : "#B09AFF"}
                    textDecoration={"underline"}
                    fontSize={{ base: "xs", md: "sm" }}
                    isTruncated
                  >
                    <Text
                      cursor={"pointer"}
                      maxW={{ base: "55%", md: "100%" }}
                      whiteSpace={"nowrap"} // Prevent the text from wrapping
                      textOverflow={"ellipsis"}
                      isTruncated
                      onClick={() => navigate(`/did-info/${executor}`)}
                    >
                      {executor}
                    </Text>
                    <Text
                      _hover={{ bg: "gray.50" }}
                      transition={"0.5s"}
                      rounded={"sm"}
                      p={1}
                      as={"span"}
                      ml={1}
                      cursor={"pointer"}
                    >
                      <MdContentCopy
                        onClick={() => copyToClipboard(executor)}
                      />
                    </Text>
                  </HStack>
                </HStack>}


                {deployer&&<HStack
                  fontSize={{ base: "xs", md: "sm" }}
                  cursor={"pointer"}
                  gap={{ base: 2, md: 4 }}
                  mb={3}
                >
                  <Text color={colorMode === "light" ? "#0F0F0F" : "#E8E8E8"}>
                    Deployer:
                  </Text>
                  <HStack
                    color={colorMode === "light" ? "#230A79" : "#B09AFF"}
                    textDecoration={"underline"}
                    isTruncated
                    fontSize={{ base: "xs", md: "sm" }}
                  >
                    <Text
                      cursor={"pointer"}
                      maxW={{ base: "55%", md: "100%" }}
                      whiteSpace={"nowrap"} // Prevent the text from wrapping
                      textOverflow={"ellipsis"}
                      isTruncated
                      onClick={() => navigate(`/did-info/${deployer}`)}
                    >
                      {deployer}
                    </Text>
                    <Text
                      _hover={{ bg: "gray.50" }}
                      transition={"0.5s"}
                      rounded={"sm"}
                      p={1}
                      as={"span"}
                      ml={1}
                      cursor={"pointer"}
                    >
                      <MdContentCopy
                        onClick={() => copyToClipboard(deployer)}
                      />
                    </Text>
                  </HStack>
                </HStack>}




                <HStack
                  flexDirection={{ base: "column", md: "row" }}
                  justifyContent={{ base: "", md: scTokenHash?"space-between" :"flex-start" }}
                  gap={{base:4,md:scTokenHash ? 4:44}}
                  alignItems={{ base: "flex-start", md: "" }}
                  // flexWrap={'wrap'}

                  // w={"80%"}
                  w={{ base: "100%", md:scTokenHash?"90%": "80%" }}
                  fontSize={{ base: "xs", md: "sm" }}
                  mb={3}
                >
                  {scTokenHash && (
                    <Box>
                      <Text
                        mb={2}
                        // fontSize={{base:"xs", md:"sm" }}
                        color={colorMode === "light" ? "#7B7B7B" : "#E8E8E8"}
                      >
                        Smart Contract ID :
                      </Text>
                      <Text
                       width={{ base: "300px", md: "auto" }}
                       whiteSpace="nowrap"
                       overflow="hidden"
                       textOverflow="ellipsis"
                       isTruncated
                        color={colorMode === "light" ? "#230A79" : "#B09AFF"}
                        cursor={"pointer"}
                      >
                       {scTokenHash}
                      </Text>
                    </Box>
                  )}

                  <Box position={"relative"}>
                  <Tooltip 
                      p={2}
                      fontWeight={400}
                      lineHeight={"18px"}
                      boxShadow={"rgba(99, 99, 99, 0.2) 0px 2px 8px 0px"}
                      color={colorMode === "light" ? "#230A79" : "#230A79"}
                      fontStyle={"12px"}
                      rounded={"5px"}
                      bg={colorMode === "light" ? "#fff" : "#fff"}
                      label={"All timestamps are shown in UTC+00:00"}
                      placement='top-start'>
                      <Text p={0} display={{ base: "none", md: "block" }} position={"absolute"} top={"2px"} left={"-24px"}>
                        <Icon
                          cursor={"pointer"}
                          as={MdOutlineErrorOutline}
                          fontSize={"18px"}
                          color="#7B7B7B"
                        />
                      </Text>
                    </Tooltip>
                    <Text
                      mb={2}
                      color={colorMode === "light" ? "#7B7B7B" : "#E8E8E8"}
                    >
                      Date and Time Stamp :
                    </Text>
                    <Text color={colorMode === "light" ? "#230A79" : "#B09AFF"}>
                      {formatUTCToDDMMYYHHMMSS(timestamp)}
                    </Text>
                  </Box>

                  {amount&&<Box>
                    <Text
                      mb={2}
                      color={colorMode === "light" ? "#7B7B7B" : "#E8E8E8"}
                    >
                      Amount:
                    </Text>
                    <Text
                      display={"flex"}
                      gap={2}
                      alignItems={"center"}
                      color={colorMode === "light" ? "#230A79" : "#B09AFF"}
                    >
                      {/* <Image w={4} src={colorMode === "light" ? rbtLogoDark :rbtLogoOutline} /> */}
                      <Image w={4} src={rbtLogoDark} />
                      {amount}
                    </Text>
                  </Box>}

                  
                  {pledgeAmount&&<Box>
                    <Text
                      mb={2}
                      color={colorMode === "light" ? "#7B7B7B" : "#E8E8E8"}
                    >
                      Pledge Amount:
                    </Text>
                    <Text
                      display={"flex"}
                      gap={2}
                      alignItems={"center"}
                      color={colorMode === "light" ? "#230A79" : "#B09AFF"}
                    >
                      <Image w={4} src={colorMode === "light" ? rbtLogoDark :rbtLogoOutline} />
                      {pledgeAmount}
                    </Text>
                  </Box>}


                </HStack>

                <HStack
                  fontSize={"sm"}
                  alignItems={"flex-start"}
                  position={"relative"}
                >
                  <Tooltip 
                  p={2}
                   fontWeight={400}
                   lineHeight={"18px"}
                   boxShadow={"rgba(99, 99, 99, 0.2) 0px 2px 8px 0px"}
                  color={colorMode === "light" ? "#230A79" : "#230A79"}
                    fontStyle={"xs"}
                    rounded={"5px"}
                    bg={colorMode === "light" ? "#fff" : "#fff"}
                    label={transactionType === "RBT" ? "Native RBT transactions which is peer-to-peer." : "SC or Smart Contract are codes that executes the actions multiple parties or entities agree to."}
                    placement='top-start'>
                    <Text p={0} display={{ base: "none", md: "block" }} position={"absolute"} top={"2px"} left={"-24px"}>
                      <Icon
                        cursor={"pointer"}
                        as={MdOutlineErrorOutline}
                        fontSize={"18px"}
                        color="#7B7B7B"
                      />
                    </Text>
                  </Tooltip>
                  {/* <Icon
                    as={MdOutlineErrorOutline}
                    fontSize={"18px"}
                    display={{ base: "none", md: "block" }}
                    style={{
                      marginTop: "1px",
                      position: "absolute",
                      top: "2px",
                      left: "-24px",
                    }}
                    color="#7B7B7B"
                  /> */}

                  <VStack fontSize={{ base: "xs", md: "sm" }}>
                    <HStack w={"100%"} justifyContent={"flex-start"}>
                      <Text
                        color={colorMode === "light" ? "#7B7B7B" : "#E8E8E8"}
                      >
                        Transaction Type :
                      </Text>
                      <Text
                        color={colorMode === "light" ? "#230A79" : "#B09AFF"}
                      >
                        <Text>{transactionType}</Text>
                      </Text>
                    </HStack>

                    <HStack w={"100%"} justifyContent={"flex-start"}>
                      <Text
                        color={colorMode === "light" ? "#7B7B7B" : "#E8E8E8"}
                      >
                        {subNetworkId === "MainNet" ? "Main net" : "Subnet ID"}:
                      </Text>
                      <Text
                        color={colorMode === "light" ? "#230A79" : "#B09AFF"}
                      >
                        {subNetworkId === "MainNet" ?<Text>{subNetworkId}</Text>:<Link
                          to={`/subnet-id-overview/${subNetworkId}`}
                          style={{ fontWeight: "inherit" }}
                        >
                          {subNetworkId}
                        </Link>}
                      </Text>
                    </HStack>
                  </VStack>
                </HStack>
                {/* </Box> */}
              </GridItem>
            </Grid>
              )
            )}
          </Box>
          <Pagination
            pageSize={pageSize}
            setPageSize={setPageSize}
            totalItems={totalItems}
            isLoading={isMainNetDataLoading}
            setCurrentPage={setCurrentPage}
            currentPage={currentPage}
          />
        </Container>
      </Box>
    </Box>
  );
};

export default MainNet;
