import {
  Avatar,
  Badge,
  Box,
  Button,
  HStack,
  Input,
  Text,
  Tooltip,
  useBoolean,
  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 { useGetDeleteHistoryQuery } from "../../Services/delete.request.service";
import { TABLE_PAGINATION } from "../../Constants/Paginations";
import InitiateReversalPopup from "../../Components/Popups/InitiateReversalPopups";
import ToastBox from "../../Components/ToastBox";
import { useCreateAccountDeletionReversalRequestMutation } from "../../Services/reversal.account.deletion.service";
import { isMaker } from "../../Constants/Constants";
// import { formatDate } from "../../Components/Functions/UTCConvertor";

const DeletionHistory = () => {
  const toast = useToast();
  const { slideFromRight, setDeleteHistory } = useContext(GlobalStateContext);
  const [deleteAlert, setDeleteAlert] = useState(false);
  const [actionId, setActionId] = useState(false);
  const [mouseEntered, setMouseEntered] = useState(false);
  const [mouseEnteredId, setMouseEnteredId] = useState("");

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

  const [reversalId, setReversalId] = useState();
  const {
    isOpen: isOpenInRev,
    onOpen: onOpenInRev,
    onClose: onCloseInRev,
  } = useDisclosure();
  const [isReversalLoading, setIsReversalLoading] = useBoolean();

  const [createAccountDeletionReversalRequest] =
    useCreateAccountDeletionReversalRequestMutation();

  // 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: deleteHistory,
    isLoading,
    refetch,
  } = useGetDeleteHistoryQuery(
    {
      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
    }
  );

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

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

  // ====================================================[Table Setup]================================================================
  const tableHeadRow = [
    "Sr No.",
    "Request On",
    "Client ID",
    "First Name",
    "Last Name",
    "Country",
    "Phone Number",
    "Status",
    isMaker() && "Reversal Action",
  ];

  const extractedArray = deleteHistory?.data?.rows?.map((item, index) => ({
    id: item?.id,
    "Sr No.": (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"gray.800"}
        className="d-flex align-items-center web-text-small"
        fontWeight={"500"}
      >
        {index + 1}.
      </Text>
    ),
    "Request On": (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"gray.600"}
        className="d-flex align-items-center web-text-small"
        fontWeight={"500"}
      >
        {formatDate(item.Requested_on)}
      </Text>
    ),
    "Client ID": (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"gray.600"}
        className="d-flex align-items-center  web-text-small"
        fontWeight={"500"}
      >
        {item.clientId}
      </Text>
    ),
    "First Name": (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"gray.800"}
        className="d-flex align-items-center web-text-small"
        fontWeight={"500"}
      >
        {item.firstName}
        {/* {formatDate(item.charge)} */}
      </Text>
    ),
    "Last Name": (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"gray.800"}
        className="d-flex align-items-center web-text-small"
        fontWeight={"500"}
      >
        {item.lastName}
      </Text>
    ),
    Country: (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"gray.600"}
        className="d-flex align-items-center web-text-small"
        fontWeight={"500"}
      >
        {item.country}
      </Text>
    ),
    "Phone Number": (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"gray.600"}
        className="d-flex align-items-center web-text-small"
        fontWeight={"500"}
      >
        {item.phoneNumber}
      </Text>
    ),
    Status: (
      <Text
        justifyContent={slideFromRight ? "right" : "center"}
        as={"span"}
        color={item?.deletionStatus === "Approved" ? "red.500" : "blue.500"}
        className="d-flex align-items-center web-text-small"
        fontWeight={"600"}
      >
        {item.deletionStatus}
      </Text>
    ),
    "Reversal Action": (
      <Box w={"120px"} isTruncated={true} cursor={"pointer"}>
        {item.deletionStatus === "Approved" ? (
          <Text
            as={"span"}
            color={!item.isReversal ? "green.500" : "#FFBB00"}
            fontWeight={700}
          >
            {!item.isReversal ? (
              <Button
                onClick={() => {
                  onOpenInRev(); // Call the function
                  setReversalId(item.id);
                }}
                colorScheme="teal"
                size="xs"
                variant="outline"
              >
                Initiate Reversal
              </Button>
            ) : (
              "Under process"
            )}
          </Text>
        ) : (
          ""
        )}
      </Box>
    ),
  }));

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

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

  const handleApproved = async (data) => {
    setIsReversalLoading.on(); // Start loading
    try {
      const { error, data: responseData } =
        await createAccountDeletionReversalRequest({
          id: reversalId,
          data,
        });

      if (error) {
        throw error; // Explicitly handle the error
      }

      // Success: Perform necessary actions
      refetch();
      toast({
        render: () => (
          <ToastBox message={responseData?.message || "Action successful!"} />
        ),
      });
      onCloseInRev();
    } catch (error) {
      // Handle errors
      toast({
        render: () => (
          <ToastBox
            message={
              error?.data?.message || "Something went wrong. Please try again."
            }
            status="error"
          />
        ),
      });
      console.error("Error:", error);
    } finally {
      setIsReversalLoading.off(); // Ensure loading is toggled off
    }
  };

  return (
    <Box {...OPACITY_ON_LOAD} overflowY={"scroll"} height={"100vh"} pb={38}>
      <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 totalItems={10} />
          </HStack> */}
        </HStack>
      </Box>

      <NormalTable
        emptyMessage={`We don't have any Sponers `}
        tableHeadRow={tableHeadRow}
        data={extractedArray}
        isLoading={isLoading}
        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}
      />
      <InitiateReversalPopup
        onClose={onCloseInRev}
        isOpen={isOpenInRev}
        handelApproved={handleApproved}
        isLoading={isReversalLoading}
      />
    </Box>
  );
};

export default DeletionHistory;
