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 DeletionRequestApprove from "./DeletionRequestApprove";
import { useGetDeleteRequestQuery } from "../../Services/delete.request.service";
// import { formatDate } from "../../Components/Functions/UTCConvertor";

const DeletionRequest = () => {
  const toast = useToast();
  const { slideFromRight, deleteRequest, setDeleteRequest } =
    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 formatDate = (date) => {
    return new Date(date).toLocaleDateString("en-GB", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
    });
  };

  const {
    data,
    isLoading: DeletionLoading
  } = useGetDeleteRequestQuery()


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

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

  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.",
    "Requested on",
    "Client ID",
    "First name",
    "Last name",
    "Country",
    "Phone number",
    "Status",
    "Action"
  ];

  const extractedArray = filteredData?.map((item, index) => ({
    id: item?.id,
    "Sr No.": (
      <Text
        justifyContent={"left"}
        as={"span"}
        color={"gray.800"}
        className="d-flex align-items-center web-text-small"
        fontWeight={'500'}
      >
        {index + 1}.
      </Text>
    ),
    "Requested on": (
      <Text
        justifyContent={"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={"left"}
        as={"span"}
        color={"gray.600"}
        className="d-flex align-items-center  web-text-small"
        fontWeight={'500'}
      >
        {item?.clientId}
      </Text>
    ),
    "First name": (
      <Text
        justifyContent={"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={"left"}
        as={"span"}
        color={"gray.800"}
        className="d-flex align-items-center web-text-small"
        fontWeight={'500'}
      >
        {item?.lastName}
      </Text>
    ),
    Country: (
      <Text
        justifyContent={"left"}
        as={"span"}
        color={"gray.600"}
        className="d-flex align-items-center web-text-small"
        fontWeight={'500'}
      >
        {item?.country}
      </Text>
    ),

    "Phone number": (
      <Text
        justifyContent={"left"}
        as={"span"}
        color={"gray.600"}
        className="d-flex align-items-center web-text-small"
        fontWeight={'500'}
      >
        {item?.phoneNumber}
      </Text>
    ),
    Status:(<Box w={"auto"} display={'flex'} alignItems={'center'} isTruncated={true}>
        <Text
        as={'span'}
          fontWeight={"700"}
          textTransform={"none"}
          color={item.kycStatus ? "blue.500" : "red.500"}
          // px={2}
          py={0.5}
          variant={'solid'}

        >
          {item.KYCStatus ? "Completed" : "Not complete"}
        </Text>
      </Box>),

    Action: (
      <Box display={"flex"} justifyContent={"center"} gap={2}>
          <Button
            // colorScheme="forestGreen"
            // color="green.500"
            rounded={"sm"}
            size={"xs"}
            textTransform={"inherit"}
            fontWeight={500}
            px={2}
            py={1}
            onClick={() => {
              setActionId(item.id);
              onConfirmOpen();
            }}
            colorScheme="green"
            variant={"outline"}
            cursor={"pointer"}
          >
            Review
          </Button>
      </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}>
      <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={DeletionLoading}
        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}
      />


<DeletionRequestApprove
        data={deleteRequest}
        isOpen={isConfirmOpen}
        onClose={onConfirmClose}
        id={actionId}
      // firstField={firstField}
      />


{/* <DepositRequestReject
        isOpen={isRejectOpen}
        onClose={onRejectClose}
        id={actionId} 
      /> */}
    </Box>
  );
};

export default DeletionRequest;
