import {
  Avatar,
  Badge,
  Box,
  Button,
  HStack,
  Input,
  Text,
  Tooltip,
  useDisclosure,
  useToast,
} from "@chakra-ui/react";
import React, { useContext, useEffect, useState } from "react";
import { OPACITY_ON_LOAD } from "../../../Layout/animations";
import NormalTable from "../../../Components/DataTable/NormalTable";
import Pagination from "../../../Components/Pagination";
import GlobalStateContext from "../../../Contexts/GlobalStateContext";
import CustomAlertDialog from "../../../Components/CustomAlertDialog";
import { formatDate } from "../../../Components/Functions/UTCConvertor";
import { CheckIcon, CloseIcon } from "@chakra-ui/icons";
import ConfirmModal from "./ConfirmModal";
import RejectModal from "./RejectModal";
import { TABLE_PAGINATION } from "../../../Constants/Paginations";
import { useGetDepositHistoryQuery } from "../../../Services/deposit.request.service";
import { useGetDrawalHistoryQuery } from "../../../Services/drawal.request.service";
// import { useGetDrawalHistoryQuery } from "../../../Services/drawal.request.service";
// import { formatDate } from "../../Components/Functions/UTCConvertor";

const ViewHistory = () => {
  const toast = useToast();
  const { slideFromRight, viewHistory, setViewHistory } =
    useContext(GlobalStateContext);
  const [isLoading, setIsLoading] = useState(true);
  const [deleteAlert, setDeleteAlert] = useState(false);
  const [actionId, setActionId] = useState(false);
  const [mouseEntered, setMouseEntered] = useState(false);
  const [mouseEnteredId, setMouseEnteredId] = useState("");
  // const {
  //   isOpen: isConfirmOpen,
  //   onOpen: onConfirmOpen,
  //   onClose: onConfirmClose,
  // } = useDisclosure();
  // const {
  //   isOpen: isRejectOpen,
  //   onOpen: onRejectOpen,
  //   onClose: onRejectClose,
  // } = useDisclosure();


  const formatDate = (date) => {
    return new Date(date).toLocaleDateString('en-GB', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
    });
  };

  


  // =========================== [Use State] ============================= 
  const [pageSize, setPageSize] = useState(TABLE_PAGINATION?.size);
  const [currentPage, setCurrentPage] = useState(TABLE_PAGINATION?.page);
  const [searchTerm, setSearchTerm] = useState("");
  const [debouncedSearchTerm, setDebouncedSearchTerm] = useState("");

  // 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,
    error,
    isLoading: drawalHistoryLoading,
    refetch
  } = useGetDrawalHistoryQuery({
    page: debouncedSearchTerm ? undefined : currentPage,  // Omit pagination for search
    size: debouncedSearchTerm ? undefined : pageSize,     // Omit pagination for search
    search: debouncedSearchTerm,
  },
  {
    skip: debouncedSearchTerm === "" && searchTerm !== "", // Skip if search is empty and it's not the initial request
  });


 // Use useEffect to refetch data when the component mounts
 useEffect(() => {
  refetch();
}, [refetch]);

  // console.log(data?.data?.rows);

 

  // ====================================================[Table Filter]================================================================
  const filteredData = data?.data?.rows.filter((item) => {
    // Filter by name (case insensitive)
    const name = item.firstName;
    const searchLower = searchTerm.toLowerCase();
    const nameMatches = name.toLowerCase().includes(searchLower);

    // Filter by status
    // const status = item.status;
    // const statusLower = status ? "active" : "inactive";

    // const statusMatches =
    //   statusFilter === "all" ||
    //   (statusFilter === "active" && status === true) ||
    //   (statusFilter === "inactive" && status === false);

    return nameMatches;
  });

  // ====================================================[Table Setup]================================================================
  const tableHeadRow = [
    // "Sr.no",
    "Date",
    "Client ID",
    "First Name",
    "Last Name",
    "Country",
    "Phone Number",
    // "Currency",
    "Withdrawal Amount",
    // "Withdrawal Amount",
    "Status",
  ];

  const extractedArray = filteredData?.map((item, index) => ({
    // id: item?.id,
    "Sr.no": (
      <Text
        w={"auto"}
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {index + 1}
      </Text>
    ),
    Date: (
      <Text
        w={"60px"}
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {formatDate(item?.createdAt)}
      </Text>
    ),
    "Client ID": (
      <Text
        w={"60px"}
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {item.clientReference_id}
      </Text>
    ),
    "First Name": (
      <Box isTruncated={true} >
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
          {item.firstName}
        </Text>
      </Box>
    ),
    "Last Name": (
      <Box w={"70px"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item.lastName}
        </Text>
      </Box>
    ),
    Country: (
      <Box  isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item.countryName}
        </Text>
      </Box>
    ),
    "Phone Number": (
      <Box isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item.mobileNumber}
        </Text>
      </Box>
    ),
    Currency: (
      <Box  isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
         <Badge ms={1} colorScheme="green">
            {item.currencyCode}
          </Badge>
        </Text>
      </Box>
    ),
    // "Withdrawal Amount": (
    //   <Box  isTruncated={true}>
    //     <Text as={"span"} color={"teal.900"}>
    //     <Badge ms={1} colorScheme="green" me={1}>$</Badge>{parseFloat(item?.USDAmount||0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
    //     </Text>
    //   </Box>
    // ),
    "Withdrawal Amount": (
      <Box isTruncated={true} display={'flex'} justifyContent={'end'}>
        <Text as={"span"} color={"teal.900"}>
        {parseFloat(item?.investorAmount||0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}<Badge ms={1} colorScheme="green">{item?.currencyCode}</Badge>
        </Text>
      </Box>
    ),
    Status: (
      <Box w={"70px"} isTruncated={true}>
        <Text
          // onClick={() => {
          //   setActionId(item.id);
          //   if (item.status === "Approved") {
          //     onConfirmOpen();
          //   } else {
          //     onRejectOpen();
          //   }
          // }}
          as={"span"}
          color={item.transactionStatus === "Approved" ? "green" : "red"}
        >
          {item.transactionStatus}
        </Text>
      </Box>
    ),
  }));

  const handleDelete = () => {
    const updatedSponsors = sponser.filter(
      (sponsor) => sponsor.id !== actionId
    );

    setTimeout(() => {
      setSponser(updatedSponsors);
      setDeleteAlert(false);
      setIsLoading(false);
    }, 100);
    setIsLoading(true);
  };

  return (
    <Box {...OPACITY_ON_LOAD} overflowY={"scroll"} height={"100vh"} pb={38}>
      {/* <ConfirmModal
        isOpen={isConfirmOpen}
        onClose={onConfirmClose}
        // firstField={firstField}
      />
      <RejectModal
        isOpen={isRejectOpen}
        onClose={onRejectClose}
      /> */}
      <Box bg="white.500">
        <HStack
          display={"flex"}
          justifyContent={"space-between"}
          ps={1}
          pe={1}
          pb={4}
          pt={4}
          spacing="24px"
        >
          <Input
            type="search"
            width={300}
            placeholder="Search..."
            size="sm"
            rounded="sm"
            focusBorderColor="green.500"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
          <HStack display={"flex"} alignItems={"center"}>
            <Pagination
              isLoading={drawalHistoryLoading}
              pageSize={pageSize}
              setPageSize={setPageSize}
              currentPage={currentPage}
              setCurrentPage={setCurrentPage}
              totalItems={data?.data?.totalItems}
            />
          </HStack>
        </HStack>
      </Box>

      <NormalTable
        emptyMessage={`We don't have any Sponers `}
        tableHeadRow={tableHeadRow}
        data={extractedArray}
        isLoading={drawalHistoryLoading}
        viewActionId={actionId}
        setViewActionId={setActionId}
        // totalPages={10}

        setMouseEnteredId={setMouseEnteredId}
        setMouseEntered={setMouseEntered}
      />

      <CustomAlertDialog
        onClose={() => setDeleteAlert(false)}
        isOpen={deleteAlert}
        message={"Are you sure you want to delete sponers?"}
        alertHandler={handleDelete}
        isLoading={isLoading}
      />
    </Box>
  );
};

export default ViewHistory;
