import { ViewIcon } from "@chakra-ui/icons";
import {
  Badge,
  Box,
  Button,
  HStack,
  Input,
  Text,
  useDisclosure,
  useToast,
} from "@chakra-ui/react";
import React, { useContext, useEffect, useRef, useState } from "react";
import CustomAlertDialog from "../../../../Components/CustomAlertDialog";
import NormalTable from "../../../../Components/DataTable/NormalTable";
import { isMaker } from "../../../../Constants/Constants";
import GlobalStateContext from "../../../../Contexts/GlobalStateContext";
import { OPACITY_ON_LOAD } from "../../../../Layout/animations";
import RequestApproveModal from "./RequestApproveModal";
import RequestRejectModal from "./RequestRejectModal";
import ViewAmountInvested from "./ViewAmountInvested";
import ViewCancel from "./ViewCancel";
import ViewDistributionInvestor from "./ViewDistributionInvestor";
import ViewExit from "./ViewExit";

const formatDate = (date) => new Date(date).toLocaleDateString();

const Pending = () => {
  const toast = useToast();
  const firstField = useRef();
  const { isOpen, onOpen, onClose } = useDisclosure();
  const { IODetails, iOTransaction, setIOTransaction } =
    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 [distributedAmt, setDistributedAmt] = useState();

  const {
    isOpen: isConfirmOpen,
    onOpen: onConfirmOpen,
    onClose: onConfirmClose,
  } = useDisclosure();
  const {
    isOpen: isRejectOpen,
    onOpen: onRejectOpen,
    onClose: onRejectClose,
  } = useDisclosure();
  const {
    isOpen: isInvestmentOpen,
    onOpen: onInvestmentOpen,
    onClose: onInvestmentClose,
  } = useDisclosure();
  const {
    isOpen: isDistInvestorOpen,
    onOpen: onDistInvestorOpen,
    onClose: onDistInvestorClose,
  } = useDisclosure();
  const {
    isOpen: isExitOpen,
    onOpen: onExitOpen,
    onClose: onExitClose,
  } = useDisclosure();
  const {
    isOpen: isCancelOpen,
    onOpen: onCancelOpen,
    onClose: onCancelClose,
  } = useDisclosure();

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

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

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

  // Table filter
  // const filteredData = IODetails?.ioTransactionRecords?.Pending?.filter((item) => {
  //   // Filter by name (case insensitive)
  //   const name = item.transactionName;
  //   const searchLower = searchTerm?.toLowerCase();
  //   const nameMatches = name?.toLowerCase().includes(searchLower);
  //   return nameMatches;
  // });

  const tableHeadRow = [
    "Sr No.",
    "Transaction Date",
    "Transaction Name",
    "Amount",
    "Created By",
    "Created On",
    "Approved By",
    "Approved On",
    "Actions",
  ];

  const extractedArray = IODetails?.ioTransactionRecords?.Pending?.map(
    (item, index) => ({
      id: item?.id,
      "Sr No.": (
        <Text as={"span"} color={"gray.800"} fontWeight={"500"}>
          {index + 1}.
        </Text>
      ),
      "Transaction Date": (
        <Text as={"span"} color={"gray.600"} fontWeight={"500"}>
          {formatDate(item?.transactionDate)}
        </Text>
      ),
      "Transaction Name": (
        <Text as={"span"} color={"gray.600"} fontWeight={"500"}>
          {item?.transactionType}
        </Text>
      ),
      Amount: (
        <Text as={"span"} color={"gray.600"} fontWeight={"500"}>
          <Badge ms={1} colorScheme="green" me={1}>
            $
          </Badge>
          {parseFloat(item?.transactionAmount || 0).toLocaleString(undefined, {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
          })}
        </Text>
      ),
      // Amount:(
      //   <div>
      //     <ViewDistributionInvestor amount={item?.transactionAmount} />
      //   </div>
      // ),
      "Created By": (
        <Text
          textTransform={"capitalize"}
          w={"100px"}
          as={"span"}
          color={"gray.800"}
          fontWeight={"500"}
        >
          {item?.creator?.firstName}
        </Text>
      ),
      "Created On": (
        <Text w={"100px"} as={"span"} color={"gray.800"} fontWeight={"500"}>
          {formatDate(item?.createdAt)}
        </Text>
      ),
      "Approved By": (
        <Text
          textTransform={"capitalize"}
          w={"100px"}
          as={"span"}
          color={"gray.800"}
          fontWeight={"500"}
        >
          {item?.modifier?.firstName}
        </Text>
      ),
      "Approved On": (
        <Text w={"100px"} as={"span"} color={"gray.800"} fontWeight={"500"}>
          {item?.modifier ? formatDate(item?.updatedAt) : "---"}
        </Text>
      ),
      Actions: (
        <Box display={"flex"} justifyContent={"center"} gap={2}>
          <Button
            colorScheme="forestGreen"
            rounded={"sm"}
            size={"xs"}
            px={2}
            py={1}
            fontWeight={500}
            onClick={() => {
              setActionId(item.id); // Set the action ID for all cases
              if (item?.transactionType === "Amount Invested") {
                onInvestmentOpen();
              } else if (item?.transactionType === "Distribution To Investor") {
                onDistInvestorOpen();
                setDistributedAmt(item?.transactionAmount);
              } else if (item?.transactionType === "Exit") {
                onExitOpen();
              } else if (item?.transactionType === "Cancel") {
                onCancelOpen();
              }
            }}
          >
            {isMaker() ? <ViewIcon me={"4px"} /> : null}{" "}
            {isMaker() ? "View" : "Approve / Reject"}
          </Button>
        </Box>
      ),
    })
  );

  

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

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

  return (
    <Box {...OPACITY_ON_LOAD} pb={0}>
      <Box bg="white.500">
        <HStack
          display={"flex"}
          justifyContent={"space-between"}
          pb={3}
          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>
      </Box>

      <NormalTable
        emptyMessage={`We don't have any Sponers`}
        tableHeadRow={tableHeadRow}
        data={extractedArray}
        isLoading={isLoading}
        viewActionId={actionId}
        setViewActionId={setActionId}
        setMouseEnteredId={setMouseEnteredId}
        setMouseEntered={setMouseEntered}
      />

      <CustomAlertDialog
        onClose={() => setDeleteAlert(false)}
        isOpen={deleteAlert}
        message={"Are you sure you want to delete sponers?"}
        alertHandler={handleDelete}
        isLoading={isLoading}
      />

      <ViewAmountInvested
        isOpen={isInvestmentOpen}
        onClose={onInvestmentClose}
        id={actionId}
      />
      <ViewDistributionInvestor
        isOpen={isDistInvestorOpen}
        onClose={onDistInvestorClose}
        id={actionId}
        amount={distributedAmt}
      />
      <ViewExit isOpen={isExitOpen} onClose={onExitClose} id={actionId} />
      <ViewCancel isOpen={isCancelOpen} onClose={onCancelClose} id={actionId} />
      <RequestApproveModal
        // data={data?.data?.rows}
        isOpen={isConfirmOpen}
        onClose={onConfirmClose}
        id={actionId}
        // firstField={firstField}
      />
      <RequestRejectModal
        isOpen={isRejectOpen}
        onClose={onRejectClose}
        id={actionId}
      />
    </Box>
  );
};

export default Pending;
