import {
  Badge,
  Box,
  Button,
  Container,
  Heading,
  HStack,
  Icon,
  Image,
  Input,
  InputGroup,
  Select,
  Stack,
  Text,
  useColorMode,
  VStack,
} from "@chakra-ui/react";
import React, { useContext, useEffect, useState } from "react";
import GlobalStateContext from "../Contexts/GlobalStateContext";
import NormalTable from "../components/DataTable/NormalTable";
import bannerImage from "../assets/images/bannerImg.png";
import { useNavigate, useParams } from "react-router-dom";
import Pagination from "../components/Pagination";
import { useGetSubnetAllQuery, useGetSubnetCountQuery } from "../Services/api.service";
import { BiSearch, BiSearchAlt } from "react-icons/bi";
import { MdArrowRight } from "react-icons/md";
import Search from '../assets/images/search.png'
import FullScreenLoaader from "../components/FullScreenLoaader/FullScreenLoaader";

const SubnetId = () => {
  const { subnetId } = useContext(GlobalStateContext);
  // const [isLoading, setIsLoading] = useState(false);
  const { colorMode } = useColorMode();
  const navigate = useNavigate();


  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 [ searchTerm, setSearchTerm] = useState()
  const [debouncedSearchTerm, setDebouncedSearchTerm] = useState("");



  const{
    data: subNetCount,
    isLoading: isSubnetTransLoading
  } = useGetSubnetCountQuery()

    // Debounce the search term to avoid making a request on every keystroke
    useEffect(() => {
      const handler = setTimeout(() => {
        setDebouncedSearchTerm(searchTerm);
      }, 500); // Adjust delay as needed
      return () => {
        clearTimeout(handler);
      };
    }, [searchTerm]);
  


  const {
    data,
    isLoading,
    refetch,
    isFetching
  } = useGetSubnetAllQuery({
    pageNumber: currentPage,
    pageSize: pageSize,
    searchTerm: debouncedSearchTerm
  })




  


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

  // ===============================[ Table Header ]
  const tableHeadRow = [
    "Sr. no",
    "Subnet ID",
    "Network Name",
  ];

  // const extractedArray = reportsHistory.map((item)=>({ }))
  const extractedArray = data?.data?.items.map((item, index) => ({
    "Sr. no": (
      <Text as={"span"} display={"flex"} gap={2} alignItems={"center"}>
        {index + 1}
      </Text>
    ),
    "Subnet ID": (
      <>
        <Box color={colorMode === "light"? "#230A79" : "#B09AFF"}  onClick={() =>
          navigate(`/subnet-id-overview/${item?.networkId}`)}>
        {item?.networkId}
        </Box>
        <HStack fontSize={"xs"} mt={1} w={"280px"} justifyContent={"space-between"}>
          {/* <Text display={"flex"} alignItems={"center"}>TVL<MdArrowRight /> {Number(item?.tvl).toFixed(3)} ($ Mn)</Text>  */}
          <Text display={"flex"} alignItems={"center"}>TVL<MdArrowRight /> {item?.tvl} ($ Mn)</Text> 
          <Text  display={"flex"} alignItems={"center"}>Count<MdArrowRight />{item?.transctionsCount}</Text>
        </HStack>
      </>
     ),
    "Network Name": item?.networkName,
  }));


  return (
    <Box
      bg={colorMode === "light" ? "#f5f5f7" : "none"}
      p={"6rem 0 4rem 0"}
      backgroundImage={colorMode !== "light" ? `url(${bannerImage})` : "none"}
      position={"relative"}
      backgroundSize="cover"
      backgroundRepeat="no-repeat"
      minH={"100vh"}
      overflowX={"hidden"}
    >
      <Container
        maxW="6xl"
        color="white"
        display={{ base: "block", md: "flex" }}
        justifyContent={"space-between"}
        mb={5}
        
      >
        <Text
          fontSize={"md"}
          fontWeight={500}
          color={colorMode === "light" ? "#000" : "#fff"}
          mb={{ base: "10px", md: "0px" }}
        >
          Subnet Overview {useParams?.id}
        </Text>
        {/* <Text
          to=""
          style={{ fontSize: "14px" }}
          color={colorMode === "light" ? "#000" : "#fff"}
          display={"flex"}
          gap={"3"}
        >
          View total number of records
          <Select width={"70px"} rounded="md" size="xs">
            <option value="option1">10</option>
            <option value="option2">20</option>
            <option value="option3">30</option>
          </Select>
        </Text> */}
      </Container>
      <VStack
        pt={{ base: colorMode === "light" ? 10 : 10, md: 10 }}
        mb={{ base: 8, md: 14 }}
      >
        <Container maxW="2xl" position={"relative"}>
          <Box w={"100%"} display={"flex"} alignItems={"center"}>
            <InputGroup
              width={"100%"}
              boxShadow={"sm"}
              size="sm"
              bg={colorMode === "light" ? "light.100" : "#393939"}
              rounded={"lg"}
            >
              <Input
                roundedLeft={8}
                w={"76%"}
                borderColor={colorMode === "light" ? "#CED4DA" : "#565252"}
                // h={"42px"}
                type="search"
                placeholder="Search by Subnet ID"
                onChange={(e) => setSearchTerm(e.target.value)}
                _hover={{
                  borderColor: "#7f8c8d",
                }}
                _placeholder={{ color: "#737C82" }}
                _focusVisible={{
                  borderColor: colorMode === "light" ? "#230A79" : "#7f8c8d",
                }}
                size={'sm'}
              />
              <Button
                zIndex={99}
                // h={"42px"}
                w={{ base: "205px", md: "24%" }}
                fontWeight={400}
                roundedBottomRight={8}
                roundedTopRight={8}
                fontSize={"sm"}
                rounded={0}
                border="none"
                bg={colorMode === "light" ? "#230A79" : "#565252"}
                _hover={{
                  opacity: 0.9,
                  bg: colorMode !== "light" && "#333248",
                }}
                _focus={{
                  opacity: 1,
                  outline: "none",
                  bg: colorMode === "light" ? "#4023A6" : "#565252",
                }}
                _active={{
                  opacity: 0.9,
                  outline: "none",
                  bg: colorMode === "light" ? "#4023A6" : "#565252",
                }}
                color={"#fff"}
                gap={3}
                display={'flex'}
                alignItems={'center'}
                size={'sm'}
              >
                <BiSearchAlt fontSize={"20px"} />
                Search
              </Button>
            </InputGroup>
          </Box>
        </Container>
      </VStack>

      
      {isFetching?<FullScreenLoaader half={true}/>: extractedArray?.length === 0 ? <Box p={"4rem 0"} >
       <Container maxW="6xl">
          <HStack justifyContent={"center"} mt={10}>
            <Image w={"40px"} src={Search}/>
            <Text as={"span"} color={"#787878"}>No records found</Text>
          </HStack>
       </Container>
    </Box>: <Container maxW="6xl">
        <NormalTable
            emptyMessage={`We don't have any Sponers `}
            tableHeadRow={tableHeadRow}
            data={extractedArray}
            isLoading={isSubnetTransLoading}
        />
      <Pagination
        pageSize={pageSize}
        setPageSize={setPageSize}
        totalItems={totalItems}
        isLoading={isSubnetTransLoading}
        setCurrentPage={setCurrentPage}
        currentPage={currentPage}
      />
      </Container>}
    </Box>
  );
};

export default SubnetId;
