import {
  Avatar,
  Badge,
  Box,
  Button,
  HStack,
  Input,
  Link,
  Text,
  Tooltip,
  useBoolean,
  useDisclosure,
  useToast,
} from "@chakra-ui/react";
import React, { useContext, useEffect, useState } from "react";
import { CheckIcon, CloseIcon, ExternalLinkIcon } from "@chakra-ui/icons";
import Pagination from "../../../Components/Pagination";
import GlobalStateContext from "../../../Contexts/GlobalStateContext";
import CustomAlertDialog from "../../../Components/CustomAlertDialog";
import DrawalRequestReject from "../../WithDrawal/DrawalRequest/DrawalRequestReject";
import NormalTable from "../../../Components/DataTable/NormalTable";
import DrawalRequestApprove from "../../WithDrawal/DrawalRequest/DrawalRequestApprove";
import { generateSerialNumber, isMaker } from "../../../Constants/Constants";
import {
  useGetApproveHistoryQuery,
  useGetFawateerForMakerRequestQuery,
  useGetFawateerRequestQuery,
} from "../../../Services/fawateer.request.service";
import { TABLE_PAGINATION } from "../../../Constants/Paginations";
import { OPACITY_ON_LOAD } from "../../../Layout/animations";
import InitiateReversalPopup from "../../../Components/Popups/InitiateReversalPopups";
import ToastBox from "../../../Components/ToastBox";
import { useCreateFawateerReversalRequestMutation } from "../../../Services/reversal.fawateer.deposit.service";

const ApproveHistoryMaker = () => {
  const toast = useToast();
  const { slideFromRight, approveHistory, setApproveHistory } =
    useContext(GlobalStateContext);
  const [searchTerm, setSearchTerm] = useState("");
  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 [debouncedSearchTerm, setDebouncedSearchTerm] = useState("");

  const [pageSize, setPageSize] = useState(TABLE_PAGINATION?.size);
  const [currentPage, setCurrentPage] = useState(TABLE_PAGINATION?.page);

  const [createFawateerReversalRequest] =
    useCreateFawateerReversalRequestMutation();

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

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

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

  const {
    data,
    isLoading: drawalRequestLoading,
    error,
    refetch,
  } = useGetFawateerForMakerRequestQuery(
    {
      page: debouncedSearchTerm ? undefined : currentPage, // Omit pagination for search
      size: debouncedSearchTerm ? undefined : pageSize, // Omit pagination for search
      searchTerm: debouncedSearchTerm,
    },
    {
      skip: debouncedSearchTerm === "" && searchTerm !== "", // Skip if search is empty and it's not the initial request
    }
  );

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedSearchTerm(searchTerm);
    }, 500); // Adjust delay as needed
    return () => {
      clearTimeout(handler);
    };
  }, [searchTerm]);

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

  useEffect(() => {
    // Simulate loading
    const timer = setTimeout(() => {
      setIsLoading(false);
    }, 1500);

    // Cleanup the timer on component unmount
    return () => clearTimeout(timer);
  }, []);

  // ====================================================[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",
    "Client ID",
    "First Name",
    "Last Name",
    "E-mail ID",
    "Phone Number",
    "Deposit Date",
    "Deposit Amount (BHD)",
    "Support Image",
    "Status",
    isMaker() && "Reversal Action",
  ];

  const extractedArray = data?.data?.rows?.map((item, idx) => ({
    // 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"
      >
        {generateSerialNumber(idx, currentPage, pageSize)}
      </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} w={"80px"}>
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
          {item.firstName}
        </Text>
      </Box>
    ),
    "Last Name": (
      <Box w={"50px"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item.lastName}
        </Text>
      </Box>
    ),
    "E-mail ID": (
      <Box isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item.emailAddress}
        </Text>
      </Box>
    ),
    "Phone Number": (
      <Box w={"100px"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item.mobileNumber}
        </Text>
      </Box>
    ),
    "Deposit Date": (
      <Box w={"100px"} isTruncated={true} display={"flex"}>
        <Text as={"span"} color={"teal.900"}>
          {formatDate(item?.transaction_date)}
        </Text>
      </Box>
    ),
    "Deposit Amount (BHD)": (
      <Box w={"130px"} isTruncated={true} display={"flex"}>
        <Text as={"span"} color={"teal.900"}>
          {/* {item.investorAmount} */}
          {parseFloat(item?.transaction_amount || 0).toLocaleString(undefined, {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
          })}
          {/* <Badge ms={1} colorScheme="green">{item?.transaction_amount}</Badge>   */}
        </Text>
      </Box>
    ),
    "Support Image": (
      <Text
        color={"green.500"}
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {item?.spportFile_path && (
          <Badge
            px={2}
            py={0.5}
            textTransform={"inherit"}
            fontWeight={500}
            colorScheme={"forestGreen"}
          >
            <Link
              href={import.meta.env.VITE_IMAGE_URL + item?.spportFile_path}
              isExternal
              display={"flex"}
              alignItems={"center"}
            >
              <Box me={"1px"} as="span" cursor={"pointer"}>
                View
              </Box>
              <ExternalLinkIcon />
            </Link>
          </Badge>
        )}
      </Text>
    ),
    Status: (
      <Box isTruncated={true} display={"flex"}>
        <Badge
          my={1}
          fontWeight={500}
          px={2}
          py={"2px"}
          rounded={4}
          colorScheme={
            item?.transactionStatus === "Approved"
              ? "green"
              : item?.transactionStatus === "Pending"
              ? "yellow"
              : item?.transactionStatus === "Reject"
              ? "red"
              : "gray" // default border color if status doesn't match any condition
          }
        >
          {item.transactionStatus}
        </Badge>
      </Box>
    ),
    "Reversal Action": (
      <Box w={"120px"} isTruncated={true} cursor={"pointer"}>
        {item.transactionStatus === "Approved" ? (
          <Text
            as={"span"}
            color={!item.isReversal ? "green.500" : "#FFBB00"}
            fontWeight={700}
          >
            {!item.isReversal ? (
              <Button
                onClick={() => {
                  onOpenInRev(); // Call the function
                  // setReversalId(item.transaction_xid);
                  setReversalId(item.id);
                }}
                colorScheme="teal"
                size="xs"
                variant="outline"
              >
                Initiate Reversal
              </Button>
            ) : (
              "Under process"
            )}
          </Text>
        ) : (
          ""
        )}
      </Box>
    ),
  }));

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

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

  const handleApproved = async (data) => {
    setIsReversalLoading.on(); // Start loading
    try {
      const { error, data: responseData } = await createFawateerReversalRequest(
        {
          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)}
          />

          <Pagination
            isLoading={drawalRequestLoading}
            pageSize={pageSize}
            setPageSize={setPageSize}
            currentPage={currentPage}
            setCurrentPage={setCurrentPage}
            totalItems={data?.data?.totalItems}
          />
        </HStack>
      </Box>

      <NormalTable
        isLoading={drawalRequestLoading}
        emptyMessage={`We don't have any Sponers `}
        tableHeadRow={tableHeadRow}
        data={extractedArray}
        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}
      />
      <DrawalRequestApprove
        // data={data?.data?.rows}
        isOpen={isConfirmOpen}
        onClose={onConfirmClose}
        id={actionId}
        // firstField={firstField}
      />
      <DrawalRequestReject
        isOpen={isRejectOpen}
        onClose={onRejectClose}
        id={actionId}
      />

      <InitiateReversalPopup
        onClose={onCloseInRev}
        isOpen={isOpenInRev}
        handelApproved={handleApproved}
        isLoading={isReversalLoading}
      />
    </Box>
  );
};

export default ApproveHistoryMaker;
