import {
  Avatar,
  Badge,
  Box,
  Button,
  HStack,
  Input,
  Text,
  Tooltip,
  useToast,
} from "@chakra-ui/react";
import React, { useContext, useEffect, useState } from "react";
import { OPACITY_ON_LOAD } from "../../Layout/animations";
import DataTable from "../../Components/DataTable/DataTable";
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 { formatDate } from "../../Components/Functions/UTCConvertor";

const PendingRequest = () => {
  const toast = useToast();
  const { slideFromRight, pendingRequest, setPendingRequest } =
    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("");

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

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

  // ====================================================[Table Filter]================================================================
  const filteredData = pendingRequest.filter((item) => {
    // Filter by name (case insensitive)
    const name = item.clientId;
    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",
    "Amount in Investor currency",
    "Action",
  ];

  const [extractedArray, setExtractedArray] = useState(
    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"
        >
          {item.date}
        </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.clientId}
        </Text>
      ),
      "First Name": (
        <Box isTruncated={true} w={'50px'}>
          <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>
      ),
      Country: (
        <Box w={"70px"} isTruncated={true}>
          <Text as={"span"} color={"teal.900"}>
            {item.country}
          </Text>
        </Box>
      ),
      "Phone Number": (
        <Box w={"70px"} isTruncated={true}>
          <Text as={"span"} color={"teal.900"}>
            {item.phoneNumber}
          </Text>
        </Box>
      ),
      Currency: (
        <Box w={"50px"} isTruncated={true}>
          <Text as={"span"} color={"teal.900"}>
            <Badge px={2} py={1}>{item.currency}</Badge>
          </Text>
        </Box>
      ),
      "Withdrawal Amount": (
        <Box w={"50px"} isTruncated={true}>
          <Text as={"span"} color={"teal.900"}>
            {item.withDrawalAmount}
          </Text>
        </Box>
      ),
      "Amount in Investor currency": (
        <Box w={"70px"} isTruncated={true}>
          <Text as={"span"} color={"teal.900"}>
            {item.amountcurrency}
          </Text>
        </Box>
      ),
      Action: (
        <Box display={"flex"} justifyContent={"space-around"} gap={2}>
          <Tooltip
            rounded={"sm"}
            fontSize={"xs"}
            label="Approve"
            bg="#fff"
            color={"green.500"}
            placement="left-start"
          >
            <Badge
              colorScheme="green"
              color="green.500"
              rounded={"sm"}
              size={"xs"}
              textTransform={"inherit"}
              fontWeight={500}
              px={2}
              py={1}
            >
              <CheckIcon fontSize={'12px'} />
            </Badge>
          </Tooltip>
          <Tooltip
            rounded={"sm"}
            fontSize={"xs"}
            label="Reject"
            bg="#fff"
            color={"red.500"}
            placement="left-start"
          >
            <Badge
              colorScheme="red"
              color="red.500"
              rounded={"sm"}
              size={"xs"}
              textTransform={"inherit"}
              fontWeight={500}
              px={2}
              py={1}
            >
              <CloseIcon fontSize={'10px'} />
            </Badge>
          </Tooltip>
        </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>

      <DataTable
        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}
      />
    </Box>
  );
};

export default PendingRequest;
