import { CheckIcon, CloseIcon } from "@chakra-ui/icons";
import {
  Box,
  Button,
  HStack,
  Input,
  Text,
  Tooltip,
  useBoolean,
  useDisclosure,
  useToast,
} from "@chakra-ui/react";
import React, { useContext, useEffect, useState } from "react";
import CustomAlertDialog from "../../Components/CustomAlertDialog";
import NormalTable from "../../Components/DataTable/NormalTable";
import { TABLE_PAGINATION } from "../../Constants/Paginations";
import GlobalStateContext from "../../Contexts/GlobalStateContext";
import { OPACITY_ON_LOAD } from "../../Layout/animations";
import {
  useApproveAccountDeletionRequestMutation,
  useGetAccountDeletionMasterQuery,
  useRejectAccountDeletionRequestMutation,
} from "../../Services/reversal.account.deletion.service";
import ConfirmModal from "./ConfirmModal";
import RejectModal from "./RejectModal";
import RejectReversalPopups from "../../Components/Popups/RejectReversalPopups";
import ToastBox from "../../Components/ToastBox";
import ConfirmReversalPopups from "../../Components/Popups/ConfirmReversalPopups";
// import { formatDate } from "../../Components/Functions/UTCConvertor";

const ReversalAccountDeletion = () => {
  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 [isReversalLoading, setIsReversalLoading] = useBoolean();

  const {
    isOpen: isConfirmOpen,
    onOpen: onConfirmOpen,
    onClose: onConfirmClose,
  } = useDisclosure();
  const {
    isOpen: isRejectOpen,
    onOpen: onRejectOpen,
    onClose: onRejectClose,
  } = useDisclosure();

  const [rejectAccountDeletionRequest] = useRejectAccountDeletionRequestMutation();

  const [approveAccountDeletionRequest] = useApproveAccountDeletionRequestMutation();

  // 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,
  } = useGetAccountDeletionMasterQuery(
    {
      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 Date",
    "Client ID",
    "First Name",
    "Last Name",
    "Phone Number",
    "Country",
    "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 Date": (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"gray.600"}
        className="d-flex align-items-center web-text-small"
        fontWeight={"500"}
      >
        {formatDate(item.isReversalDate)}
      </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?.iamPrincipal?.investor_details?.clientReference_id}
      </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?.iamPrincipal?.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?.iamPrincipal?.lastName}
      </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?.iamPrincipal?.ISDcode + " " + item?.iamPrincipal?.mobileNumber}
      </Text>
    ),
    Country: (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"gray.600"}
        className="d-flex align-items-center web-text-small"
        fontWeight={"500"}
      >
        {item?.iamPrincipal?.investor_details?.country?.countryName}
      </Text>
    ),
    Action: (
      <Box display={"flex"} justifyContent={"center"} gap={2}>
        <Tooltip
          rounded={"sm"}
          fontSize={"xs"}
          label="Approve"
          bg="#fff"
          color={"green.500"}
          placement="left-start"
        >
          <Button
            rounded={"sm"}
            size={"xs"}
            textTransform={"inherit"}
            fontWeight={500}
            px={2}
            py={1}
            onClick={() => {
              setActionId(item.id);
              onConfirmOpen();
            }}
            colorScheme="green"
            variant={"solid"}
            cursor={"pointer"}
          >
            <CheckIcon fontSize={"12px"} />
          </Button>
        </Tooltip>
        <Tooltip
          rounded={"sm"}
          fontSize={"xs"}
          label="Reject"
          bg="#fff"
          color={"red.500"}
          placement="left-start"
        >
          <Button
            colorScheme="red"
            // color="red.500"
            rounded={"sm"}
            size={"xs"}
            textTransform={"inherit"}
            fontWeight={500}
            px={2}
            onClick={() => {
              setActionId(item.id);
              onRejectOpen();
            }}
            py={1}
            // variant={"solid"}
          >
            <CloseIcon fontSize={"10px"} />
          </Button>
        </Tooltip>
      </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 rejectAccountDeletionRequest({
        id: actionId,
        data,
      });

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

      // Success: Perform necessary actions
      refetch();
      toast({
        render: () => (
          <ToastBox message={responseData?.message || "Action successful!"} />
        ),
      });
      onRejectClose();
    } 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
    }
  };

  const handleConfirm = async (data) => {
    
    setIsReversalLoading.on(); // Start loading
    try {
      const { error, data: responseData } = await approveAccountDeletionRequest({
        id: actionId,
        data,
      });

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

      // Success: Perform necessary actions
      refetch();
      toast({
        render: () => (
          <ToastBox message={responseData?.message || "Action successful!"} />
        ),
      });
      onRejectClose();
    } 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}
      />
      <ConfirmReversalPopups
        isOpen={isConfirmOpen}
        onClose={onConfirmClose}
        handleConfirm={handleConfirm}
        isLoading={isReversalLoading}
      />
      <RejectReversalPopups
        isOpen={isRejectOpen}
        onClose={onRejectClose}
        handelApproved={handleApproved}
        isLoading={isReversalLoading}
      />
    </Box>
  );
};

export default ReversalAccountDeletion;
