import {
  Box,
  Button,
  Container,
  Divider,
  Heading,
  HStack,
  Icon,
  Image,
  Text,
  Tooltip,
  useColorMode,
  useToast,
  VStack,
} from "@chakra-ui/react";
import React, { useContext, useEffect, useState } from "react";
import { MdContentCopy, MdOutlineErrorOutline } from "react-icons/md";
import { Link, useNavigate, useParams } from "react-router-dom";
import RelatedTransactions from "../../components/RelatedTransactions/RelatedTransactions";
import bannerImage from "../../assets/images/bannerImg.png";
import ToastBox from "../../components/ToastBox";
import GlobalStateContext from "../../Contexts/GlobalStateContext";
import TransactionTable from "./TransactionTable";
import { useGetTransByIdQuery } from "../../Services/api.service";
// import rbtLogoOutline from "../../src/assets/images/rubix-filled.svg";
import rbtLogoOutline from "../../assets/images/rubix-filled.svg";
import rbtLogoDark from "../../assets/images/RBTNewLogo.png";
import { formatUTCToDDMMYYHHMMSS } from "../../Constants/Constants";
import NormalTable from "../../components/DataTable/NormalTable";
import FullScreenLoaader from "../../components/FullScreenLoaader/FullScreenLoaader";

const TransactionDetails = () => {
  const navigate = useNavigate();
  const params = useParams();
  const { colorMode } = useColorMode();

  const { data, 
    isLoading, 
    isFetching,
    refetch, errors } = useGetTransByIdQuery(params?.id);

  // Scroll to top when component mounts or params change
  useEffect(() => {
    window.scrollTo({ top: 0, behavior: "smooth" }); // Scroll to top smoothly when params change
  }, [params]);
  const { transactions } = useContext(GlobalStateContext);
  const filteredData = transactions?.find(
    (item) => item?.description === params?.id
  );
  const toast = useToast();

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

  const [dataArray, setDataArray] = useState(null);

  useEffect(() => {
    if (data?.data?.pledgeInfo?.pledgeDetails) {
      const dataArrayOfObject = Object?.entries(
        data?.data?.pledgeInfo?.pledgeDetails
      )?.map(([id, linkedIds]) => ({ id, linkedIds }));
      setDataArray(dataArrayOfObject);
    }
  }, [data]);
  

  // ===============================[ Table Header ]
  const tableHeadRow = [
    // "Sr. no",
    "Quorum List",
  ];

  // const extractedArray = reportsHistory.map((item)=>({ }))
  const extractedArray = data?.data?.quorumList?.map((item, index) => ({
    "Sr. no": (
      <Text w={18} as={"span"} display={"flex"} gap={2} alignItems={"center"}>
        {index + 1}
      </Text>
    ),
    "Quorum List": (
      <Box
        color={colorMode === "light" ? "#230A79" : "#B09AFF"}
        onClick={() => navigate(`/subnet-id-overview/${row["Subnet Id"]}`)}
      >
        {item}
      </Box>
    ),
  }));


  const [ isLoadingURL, setIsLoading ] = useState(false)

  const handleGenrateShortURL = async () => {

    setIsLoading(true)
    const fullUrl = window.location.href;
    try {
      const response = await fetch(`${import.meta.env.VITE_BASE_URL}ShortUrl/create`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(fullUrl), // Sending searchTerm as a JSON string
      });
  
      if (!response.ok) {
        throw new Error('Failed to generate short URL');
      }
  
      const result = await response.json();
      copyToClipboard(result?.shortUrl)
      // You can handle the result here, e.g., by updating a state with the short URL
    } catch (error) {
      console.error("Error generating short URL:", error);
    }
  };


  return (
    <>
      {isFetching?<FullScreenLoaader/>:<Box
        bg={colorMode === "light" ? "#f5f5f7" : "none"}
        backgroundImage={colorMode !== "light" ? `url(${bannerImage})` : "none"}
        backgroundSize="cover"
        backgroundRepeat="no-repeat"
        pb={"5rem"}
      >
        <Container maxW="6xl" pt={"6rem"}>
          <HStack justifyContent={"space-between"} alignItems={"center"} mb={3}>
            <Text
              mb={5}
              fontSize={"md"}
              fontWeight={500}
              as={"span"}
              color={colorMode === "light" ? "#000" : "#fff"}
            >
              {data?.data?.transactionType === "SC"
                ? "Smart Contract Info"
                : "Transaction Info"}
            </Text>
            <Button fontWeight={400} color={"#fff"} border={"none"} bg={colorMode === "light" ? "#230A79" : "#312F35"} _hover={{bg: colorMode === "light" ? "#4023A6" : "#312F35"}} _focus={{outline:"none"}}
              display={'flex'} gap={2} alignItems={'center'} rounded={'sm'} size={"sm"} isLoading={isLoadingURL} onClick={handleGenrateShortURL}>
              <MdContentCopy/> Copy short url
            </Button>
          </HStack>
          <Box
            boxShadow={colorMode === "light" && "md"}
            bg={colorMode === "light" ? "#ECEBF2" : "#1D1D1D"}
            p={4}
            mb={5}
            rounded={6}
          >
            <Text color={colorMode === "light" ? "#0F0F0F" : "#E8E8E8"} fontSize={"sm"}>
              Transaction ID
            </Text>
            <HStack fontSize={"sm"}>
              <HStack
                isTruncated
                color={colorMode === "light" ? "gray.400" : "gray.100"}
              >
                <Text
                  whiteSpace={"nowrap"} // Prevent the text from wrapping
                  textOverflow={"ellipsis"}
                  isTruncated
                  overflow={"hidden"}
                  cursor={"pointer"}
                >
                  {data?.data?.transactionId}
                </Text>
                <Text
                  _hover={{ bg: "gray.50" }}
                  transition={"0.5s"}
                  rounded={"sm"}
                  p={1}
                  as={"span"}
                  ml={1}
                  cursor={"pointer"}
                >
                  <MdContentCopy
                    onClick={() => copyToClipboard(data?.data?.transactionId)}
                  />
                </Text>
              </HStack>
            </HStack>

            <Divider mt={4} mb={5} />

            <Text
              fontSize={"md"}
              mb={2}
              color={colorMode === "light" ? "#230A79" : "#fff"}
            >
              Token Information
            </Text>

            {data?.data?.scTokenHash && (
              <Box
                fontSize={"sm"}
                gap={4}
                mb={2}
                // display={{ base: "block", md: "flex" }}
              >
                <Text color={colorMode === "light" ? "#0F0F0F" : "#E8E8E8"}>
                  Token Hash :
                </Text>
                <HStack
                  color={colorMode === "light" ? "#230A79" : "#B09AFF"}
                  textDecoration={"underline"}
                >
                  <Text
                    whiteSpace={"nowrap"} // Prevent the text from wrapping
                    textOverflow={"ellipsis"}
                    isTruncated
                    cursor={"pointer"}
                  >
                    {data?.data?.scTokenHash}
                  </Text>
                  <Text
                    _hover={{ bg: "gray.50" }}
                    transition={"0.5s"}
                    rounded={"sm"}
                    p={1}
                    as={"span"}
                    ml={1}
                    cursor={"pointer"}
                  >
                    <MdContentCopy
                      onClick={() => copyToClipboard(data?.data?.scTokenHash)}
                    />
                  </Text>
                </HStack>
              </Box>
            )}
            {data?.data?.blockHash && (
              <Box
                fontSize={"sm"}
                gap={4}
                mb={4}
                // display={{ base: "block", md: "flex" }}
              >
                <Text color={colorMode === "light" ? "#0F0F0F" : "#E8E8E8"}>
                  Block ID :
                </Text>
                <Text
                  display={"flex"}
                  alignItems={"center"}
                  color={colorMode === "light" ? "#230A79" : "#B09AFF"}
                  textDecoration={"underline"}
                >
                  <Text
                    whiteSpace={"nowrap"} // Prevent the text from wrapping
                    textOverflow={"ellipsis"}
                    isTruncated
                    fontSize={'sm'}
                  >
                    {data?.data?.blockHash}
                  </Text>
                  <Text
                    _hover={{ bg: "gray.50" }}
                    transition={"0.5s"}
                    rounded={"sm"}
                    p={1}
                    as={"span"}
                    ml={1}
                    cursor={"pointer"}
                  >
                    <MdContentCopy
                      onClick={() => copyToClipboard(data?.data?.blockHash)}
                    />
                  </Text>
                </Text>
              </Box>
            )}

            {data?.data?.transactionType === "SC" && (
              <Box
                fontSize={"sm"}
                gap={4}
                mb={2}
                display={{ base: "block", md: "flex" }}
              >
                <Text color={colorMode === "light" ? "#0F0F0F" : "#E8E8E8"}>
                  Block number:
                </Text>
                <HStack
                  color={colorMode === "light" ? "#230A79" : "#B09AFF"}
                  textDecoration={"underline"}
                >
                  <Text
                    whiteSpace={"nowrap"} // Prevent the text from wrapping
                    textOverflow={"ellipsis"}
                    isTruncated
                    cursor={"pointer"}
                    
                  >
                    {data?.data?.blockNumber}
                    {/* hello */}
                  </Text>
                  <Text
                    _hover={{ bg: "gray.50" }}
                    transition={"0.5s"}
                    rounded={"sm"}
                    p={1}
                    as={"span"}
                    ml={1}
                    cursor={"pointer"}
                  >
                    <MdContentCopy
                      onClick={() => copyToClipboard(data?.data?.blockNumber)}
                    />
                  </Text>
                </HStack>
              </Box>
            )}

{data?.data?.transactionType==="RBT" &&<Box>
                  <Text
                    mb={0}
                    color={colorMode === "light" ? "#0F0F0F" : "#E8E8E8"}
                  >
                    Token List:
                  </Text>
                  {data?.data?.tokenList?.map(({value,tokenId })=>
                  <Text
                  display={"flex"}
                  alignItems={"center"}
                  color={colorMode === "light" ? "#230A79" : "#B09AFF"}
                  textDecoration={"underline"}
                >
                  <Text
                    whiteSpace={"nowrap"} // Prevent the text from wrapping
                    textOverflow={"ellipsis"}
                    isTruncated

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

                  
                  
                  
                  )}
                </Box>}
          </Box>

          <Box
            boxShadow={colorMode === "light" && "md"}
            bg={colorMode === "light" ? "#ECEBF2" : "#1D1D1D"}
            p={4}
            mb={extractedArray && 5}
            rounded={6}
          >
            {/* {data?.data?.netWorkType && (
              <>
                <Text
                  color={colorMode === "light" ? "#000" : "#fff"}
                  fontSize={"sm"}
                >
                  {data?.data?.netWorkType}
                </Text>
                <HStack
                  fontSize={"sm"}
                  pb={3}
                  color={colorMode === "light" ? "#230A79" : "#B09AFF"}
                >
                  <Text
                    fontWeight={"inherit"}
                    whiteSpace={"nowrap"} // Prevent the text from wrapping
                    textOverflow={"ellipsis"}
                    isTruncated
                    cursor={"pointer"}
                  >
                    {data?.data?.subNetworkId}
                  </Text>
                  <Text
                    _hover={{ bg: "gray.50" }}
                    transition={"0.5s"}
                    rounded={"sm"}
                    p={1}
                    as={"span"}
                    ml={1}
                    cursor={"pointer"}
                  >
                    <MdContentCopy
                      onClick={() => copyToClipboard(data?.data?.netWorkType)}
                    />Token List:
                  </Text>
                </HStack>
              </>
            )} */}
            {data?.data?.sender && (
              <>
                <Text
                  color={colorMode === "light" ? "#000" : "#fff"}
                  fontSize={"sm"}
                >
                  Sender
                </Text>
                <HStack
                  fontSize={"sm"}
                  pb={3}
                  color={colorMode === "light" ? "#230A79" : "#B09AFF"}
                >
                  <Text
                    onClick={() => navigate(`/did-info/${data?.data?.sender}`)}
                    fontWeight={"inherit"}
                    whiteSpace={"nowrap"} // Prevent the text from wrapping
                    textOverflow={"ellipsis"}
                    isTruncated
                    cursor={"pointer"}
                  >
                    {data?.data?.sender}
                  </Text>
                  <Text
                    _hover={{ bg: "gray.50" }}
                    transition={"0.5s"}
                    rounded={"sm"}
                    p={1}
                    as={"span"}
                    ml={1}
                    cursor={"pointer"}
                  >
                    <MdContentCopy
                      onClick={() => copyToClipboard(data?.data?.receiver)}
                    />
                  </Text>
                </HStack>
              </>
            )}
            {data?.data?.receiver && (
              <>
                <Text
                  color={colorMode === "light" ? "#000" : "#fff"}
                  fontSize={"sm"}
                >
                  Receiver
                </Text>
                <HStack
                  fontSize={"sm"}
                  pb={3}
                  color={colorMode === "light" ? "#230A79" : "#B09AFF"}
                >
                  <Text
                    onClick={() =>
                      navigate(`/did-info/${data?.data?.receiver}`)
                    }
                    fontWeight={"inherit"}
                    whiteSpace={"nowrap"} // Prevent the text from wrapping
                    textOverflow={"ellipsis"}
                    isTruncated
                    cursor={"pointer"}
                  >
                    {data?.data?.receiver}
                  </Text>
                  <Text
                    _hover={{ bg: "gray.50" }}
                    transition={"0.5s"}
                    rounded={"sm"}
                    p={1}
                    as={"span"}
                    ml={1}
                    cursor={"pointer"}
                  >
                    <MdContentCopy
                      onClick={() => copyToClipboard(data?.data?.receiver)}
                    />
                  </Text>
                </HStack>
              </>
            )}

            {data?.data?.creator && (
              <Box
                fontSize={"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"}
                  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/${data?.data?.creator}`)}
                  >
                    {data?.data?.creator}
                  </Text>
                  <Text
                    _hover={{ bg: "gray.50" }}
                    transition={"0.5s"}
                    rounded={"sm"}
                    p={1}
                    as={"span"}
                    ml={1}
                    cursor={"pointer"}
                  >
                    <MdContentCopy
                      onClick={() => copyToClipboard(data?.data?.creator)}
                    />
                  </Text>
                </HStack>
              </Box>
            )}

            {data?.data?.executor && (
              <Box
                fontSize={"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" }}
                >
                  <Text
                    cursor={"pointer"}
                    // maxW={{ base: "55%", md: "100%" }}
                    whiteSpace={"nowrap"} // Prevent the text from wrapping
                    textOverflow={"ellipsis"}
                    isTruncated
                    onClick={() =>
                      navigate(`/did-info/${data?.data?.executor}`)
                    }
                  >
                    {data?.data?.executor}
                  </Text>
                  <Text
                    _hover={{ bg: "gray.50" }}
                    transition={"0.5s"}
                    rounded={"sm"}
                    p={1}
                    as={"span"}
                    ml={1}
                    cursor={"pointer"}
                  >
                    <MdContentCopy
                      onClick={() => copyToClipboard(data?.data?.executor)}
                    />
                  </Text>
                </HStack>
              </Box>
            )}

            {data?.data?.deployer && (
              <Box
                fontSize={"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"}
                  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/${data?.data?.deployer}`)
                    }
                  >
                    {data?.data?.deployer}
                  </Text>
                  <Text
                    _hover={{ bg: "gray.50" }}
                    transition={"0.5s"}
                    rounded={"sm"}
                    p={1}
                    as={"span"}
                    ml={1}
                    cursor={"pointer"}
                  >
                    <MdContentCopy
                      onClick={() => copyToClipboard(data?.data?.deployer)}
                    />
                  </Text>
                </HStack>
              </Box>
            )}
          </Box>

          <Box
            boxShadow={colorMode === "light" && "md"}
            bg={colorMode === "light" ? "#ECEBF2" : "#1D1D1D"}
            p={4}
            mb={5}
            rounded={6}
          >
            <HStack fontSize={"sm"} gap={{ base: "4rem", md: "8rem" }} mb={2}>
              {data?.data?.amount && (
                <Box>
                  <Text>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} />
                    {data?.data?.amount}
                  </Text>
                </Box>
              )}

              {data?.data?.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} />
                    {data?.data?.pledgeAmount}
                  </Text>
                </Box>
              )}
              {data?.data?.timestamp && (
                <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>Timestamp</Text>
                  <Text color={"#555"}>
                    {formatUTCToDDMMYYHHMMSS(data?.data?.timestamp)}
                  </Text>
                </Box>
              )}
            </HStack>

            <VStack w={'100%'} alignItems={'flex-start'} isTruncated> 

            {data?.data?.transactionType==="SC" &&<Box>
                  <Text
                    mb={2}
                    color={colorMode === "light" ? "#7B7B7B" : "#E8E8E8"}
                  >
                    Token List:
                  </Text>
                  {data?.data?.tokenList?.map(({value,tokenId })=>
                  <Text
                  display={"flex"}
                  alignItems={"center"}
                  color={colorMode === "light" ? "#230A79" : "#B09AFF"}
                  textDecoration={"underline"}
                >
                  <Text
                      whiteSpace={"nowrap"} // Prevent the text from wrapping
                    textOverflow={"ellipsis"}
                    isTruncated
                    fontSize={'sm'}
                  >
                    {tokenId}
                  </Text>
                  <Text
                    _hover={{ bg: "gray.50" }}
                    transition={"0.5s"}
                    rounded={"sm"}
                    p={1}
                    as={"span"}
                    ml={1}
                    cursor={"pointer"}
                  >
                    <MdContentCopy
                      onClick={() => copyToClipboard(tokenId)}
                    />
                  </Text>
                </Text>

                  
                  
                  
                  )}
                </Box>}

            </VStack>
          </Box>

          {extractedArray && (
            <NormalTable
              tableHeadRow={tableHeadRow}
              data={extractedArray}
              isLoading={isLoading}
            />
          )}

          {dataArray && <TransactionTable data={dataArray} />}
        </Container>
      </Box>}
      <RelatedTransactions />
    </>
  );
};

export default TransactionDetails;
