import {
  Box,
  Button,
  Container,
  Divider,
  Heading,
  HStack,
  Image,
  Text,
  useColorMode,
  useToast,
} from "@chakra-ui/react";
import React, { useEffect, useState } from "react";
import { MdContentCopy } 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 { useGetDidByIdQuery } from "../Services/api.service";
import rbtLogoOutline from "../assets/images/rubix-filled.svg";
import Search from '../assets/images/search.png'
import FullScreenLoaader from "../components/FullScreenLoaader/FullScreenLoaader";
import { OPACITY_ON_LOAD } from "../Layout/animations";
import rbtLogoDark from "../assets/images/RBTNewLogo.png";

const DidInfo = () => {

  const [ isLoadingURL, setIsLoading ] = useState(false)

  useEffect(() => {
    window.scrollTo({ top: 0, behavior: "smooth" }); // Scroll to top smoothly when params change
  }, []);
  const { colorMode } = useColorMode();
  const params = useParams();
  const navigate = useNavigate();

  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 {
    data,
    isLoading,
  } = useGetDidByIdQuery(params?.id)
  console.log(data?.message);


  const handleGenrateShortURL = async () => {

    setIsLoading(true)
    const fullUrl = window.location.href;
    try {
      const response = await fetch('https://rexplorerapi.azurewebsites.net/api/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 (
    isLoading?
    <FullScreenLoaader />:
    <Box
    bg={colorMode === "light" ? "#f5f5f7" : "none"}
    {...OPACITY_ON_LOAD}
      minH={"100vh"}
      display={"flex"}
      justifyContent={"space-between"}
      flexDirection={"column"}
    >
      <Box
        backgroundImage={colorMode !== "light" ? `url(${bannerImage})` : "none"}
        backgroundSize="cover"
        backgroundRepeat="no-repeat"
        pb={"8rem"}
      >
        <Container maxW="6xl" pt={"6rem"}>
          <Box display={"flex"} justifyContent={"space-between"} alignItems={"center"} mb={8}>
            <Text
              fontSize={"md"}
              fontWeight={500}
              color={colorMode === "light" ? "#000" : "#fff"}
            >
              DID 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>
          </Box>

          {data?.data ? 
          <Box
            boxShadow={colorMode === "light" && "md"}
            bg={colorMode === "light" ? "#ECEBF2" : "#1D1D1D"}
            p={4}
            mb={5}
            rounded={6}
          >
            <Text 
            color={colorMode === "light" ? "#000" : "#969696"} fontSize={"sm"}>
              DID
            </Text>
            <HStack fontSize={"sm"} >
              <HStack
                fontWeight={"inherit"}
                whiteSpace={"nowrap"} // Prevent the text from wrapping
                textOverflow={"ellipsis"}
                isTruncated
                cursor={"pointer"}
                color={colorMode === "light" ? "#230A79" : "#B09AFF"}
              >
                <Text
                 isTruncated
                ><Link style={{ fontWeight: "inherit" }}>{data?.data?.userDID}</Link></Text>
                <Text as={"span"} ml={5} cursor={"pointer"}>
                  <MdContentCopy
                    onClick={() => copyToClipboard(data?.data?.userDID)}
                  />
                </Text>
              </HStack>
            </HStack>
            <Divider mt={4} mb={5} />
            <Text
              color={colorMode === "light" ? "#000" : "#969696"}
              fontSize={"sm"}
            >
              Balance
            </Text>
            <HStack
              fontSize={"sm"}
              pb={3}
              color={colorMode === "light" ? "#230A79" : "#B09AFF"}
            >
              <Text 
                display={"flex"}
                gap={2}
                alignItems={"center"} >
                // <Image w={4} src={colorMode === "light" ? rbtLogoDark :rbtLogoOutline} /> 
                <Image w={4} src={rbtLogoDark} />
                {data?.data?.balance}
              </Text>
              <Text as={"span"} ml={5} cursor={"pointer"}>
                {/* <MdContentCopy
                  onClick={() => copyToClipboard(transaction.sender)}
                /> */}
              </Text>
            </HStack>
          </Box>:
          <HStack h={'35vh'} justifyContent={"center"} mt={10}>
            <Image w={"40px"} src={Search}/>
            <Text as={"span"} color={"#787878"}>{data?.message}</Text>
          </HStack>}



        </Container>
      </Box>
      <RelatedTransactions />
    </Box>
  );
};

export default DidInfo;
