import {
  Avatar,
  Badge,
  Box,
  Button,
  HStack,
  Input,
  Menu,
  MenuButton,
  MenuItem,
  MenuList,
  Portal,
  Select,
  Switch,
  Table,
  Tag,
  Tbody,
  Text,
  Th,
  Tooltip,
  Tr,
  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 ToastBox from "../../../Components/ToastBox";
import { debounce } from "../../Master/Sponser/AddSponser";

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

const Transaction = () => {
  const toast = useToast();
  const { transaction, setTransaction, slideFromRight, InvestorWallet } =
    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);
  }, []);

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

  console.log(transaction);

  // ====================================================[Table Filter]================================================================
  const filteredData = transaction?.filter((item) => {
    // Filter by name (case insensitive)
    console.log(item?.investorTransaction?.transactionName);

    const name = item?.investorTransaction?.transactionName;
    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;
  });

  console.log(filteredData);

  // ====================================================[Table Setup]================================================================
  const tableHeadRow = [
    // "Sr N/O",
    "Date",
    "Transaction",
    "Amount",
    // "Currency",
    // "TO USD",
    // "From USD",
    // "USD amount",
    "IO Name",
    "Payment Method",
  ];
  const extractedArray = filteredData?.map((item) => ({
    id: item?.id,
    "Sr N/O": (
      <Text
        w={"100px"}
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"gray.600"}
        className="d-flex align-items-center fw-bold web-text-small"
      >
        {item.id}
      </Text>
    ),
    Date: (
      <Box w={"80px"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {formatDate(item.transactionDate)}
        </Text>
      </Box>
    ),
    Transaction: (
      <Box w={"80px"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item.investorTransaction?.transactionName}
        </Text>
      </Box>
    ),
    Currency: (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item.investorCurrency}
        </Text>
      </Box>
    ),
    Amount: (
      <Box w={100} display={"flex"} justifyContent={"right"}>
        <Text
          as={"span"}
          w={"100%"}
          color={"teal.900"}
          display={"flex"}
          justifyContent={"end"}
        >
          {/* <Badge ms={1} colorScheme="green" me={1}>$</Badge> */}
          {parseFloat(item?.investorAmount || 0).toLocaleString(undefined, {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
          })}
          <Badge ms={1} colorScheme="green">
            {item?.investorCurrency}
          </Badge>
        </Text>
      </Box>
    ),
    "From USD": (
      <Text as={"span"} color={"teal.900"}>
        {item.USDToInvCur_Rate}
      </Text>
    ),
    "TO USD": (
      <Text as={"span"} color={"teal.900"}>
        {item.invCurToUSD_Rate}
      </Text>
    ),
    // "USD amount": (
    //   <Box w={100} display={"flex"} justifyContent={"left"}>
    //     {item?.invCurToUSD_Rate === "0.0000" && (
    //       <Text as={"span"} w={"100%"} color={"teal.900"}>
    //         <Badge ms={1} colorScheme="green" me={1}>
    //           $
    //         </Badge>
    //         {parseFloat(item?.USDAmount || 0).toLocaleString(undefined, {
    //           minimumFractionDigits: 2,
    //           maximumFractionDigits: 2,
    //         })}
    //       </Text>
    //     )}
    //   </Box>
    // ),
    "IO Name": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item.io && item.io?.investmentNameEnglish}
        </Text>
      </Box>
    ),
    "Payment Method": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item.paymentMethod && item.paymentMethod?.paymentMethodName}
        </Text>
      </Box>
    ),
  }));

  const totalRow = {
    // id: "total", // or any unique ID
    // "Sr N/O": (
    //   <Text w={'100px'} color={"gray.600"} fontWeight={"bold"}>Total</Text>
    // ),
    Date: (
      <Text
        as={"span"}
        textAlign={"start"}
        w={"100%"}
        color={"teal.900"}
        fontWeight={"bold"}
      >
        <Badge ms={1} colorScheme="gray">
          Total
        </Badge>
      </Text>
    ),
    Transaction: null,
    // "Currency": null,
    Amount: InvestorWallet?.currencyCode_InCur && (
      <Box w={100} display={"flex"} justifyContent={"end"}>
        <Text
          as={"span"}
          textAlign={"right"}
          w={"100%"}
          color={"teal.900"}
          fontWeight={600}
        >
          {/* <Badge ms={1} colorScheme="green" me={1}>$</Badge> */}
          {parseFloat(
            InvestorWallet?.WalletBalance_InInvCur || 0
          ).toLocaleString(undefined, {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
          })}
          <Badge ms={1} colorScheme="green">
            {InvestorWallet?.currencyCode_InCur}
          </Badge>
        </Text>
      </Box>
    ),
    // "TO USD": null,
    // "From USD": null,
    "USD amount": null,
    "IO Name": null,
    "Payment Method": null,
  };

  extractedArray?.push(totalRow);

  const handleDelete = () => {
    const updatedInvestorDetails = InvestorDetails.filter(
      (sponsor) => sponsor.id !== actionId
    );

    setTimeout(() => {
      setInvestorDetails(updatedInvestorDetails);
      setDeleteAlert(false);
      setIsLoading(false);
    }, 100);
    setIsLoading(true);
  };

  return (
    <Box {...OPACITY_ON_LOAD} 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}
        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 Transaction;
