import {
  Avatar,
  Badge,
  Box,
  Button,
  HStack,
  Input,
  Table,
  Tag,
  Tbody,
  Text,
  Th,
  Tr,
  useDisclosure,
  useToast,
} from "@chakra-ui/react";
import React, { useContext, useEffect, useRef, 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";
import { AddIcon } from "@chakra-ui/icons";
import AddCashDetails from "./AddCashDetails";
import { LuFileSpreadsheet } from "react-icons/lu";
import { exportToExcel, exportToExcelNew } from "../../../Constants/Constants";

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

const IOCashDetailsOld = () => {
  const toast = useToast();
  const firstField = useRef();
  const { isOpen, onOpen, onClose } = useDisclosure();
  const { caseDetails, setCaseDetails, IODetails } =
    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",
    });
  };

  // Calculate totals
  const totalAmount = caseDetails.reduce(
    (acc, caseDetail) => acc + caseDetail.amount,
    0
  );

  // Table setup
  const tableHeadRow = [
    "Date",
    "Transaction type",
    "Amount",
    "Comments",
    "Update by ",
    "Update On",
  ];

  const handleUpdateStatus = debounce((id) => {
    setCaseDetails((prevSponser) =>
      prevSponser.map((sponsor) =>
        sponsor.id === id ? { ...sponsor, status: !sponsor.status } : sponsor
      )
    );
    toast({
      render: () => <ToastBox message={"Status changed succesfully.!"} />,
    });
  }, 300);

  // Table filter
  const filteredData = IODetails?.ioCashHistory
    ?.filter((item) => {
      const name = item.transactionType;
      const searchLower = searchTerm.toLowerCase();
      const nameMatches = name.toLowerCase().includes(searchLower);
      return nameMatches;
    })
    .sort((b, a) => new Date(a.createdAt) - new Date(b.createdAt));

  const extractedArray = filteredData?.map((item, index) => ({
    id: item?.id,
    Date: (
      <Text
        justifyContent={"center"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {formatDate(item?.transactionDate)}
      </Text>
    ),
    "Transaction type": (
      <Text
        justifyContent={"center"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {item?.transactionType}
      </Text>
    ),
    Amount: (
      <Text
        justifyContent={"left"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        <Badge ms={1} colorScheme="green" me={1}>
          $
        </Badge>
        {/* {parseFloat(item.transactionAmount || 0).toLocaleString()} */}
        {`${parseFloat(item.transactionAmount || 0).toLocaleString(undefined, {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2,
        })}`}
      </Text>
    ),
    Comments: (
      <Text
        justifyContent={"center"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {item.comments}
      </Text>
    ),
    "Update by ": (
      <Text
        justifyContent={"center"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        gap={2}
        className="d-flex align-items-center web-text-small"
      >
        <Avatar
          size="sm"
          name={item.creator?.firstName}
          src={item.creator?.profilePhoto}
        />
        {item.creator?.firstName}
      </Text>
    ),
    "Update On": (
      <Text
        justifyContent={"center"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {formatDate(item.updatedAt)}
      </Text>
    ),
  }));

  const customHeaders = [
    { label: "Date", key: "transactionDate" },
    { label: "Transaction type", key: "transactionType" },
    { label: "Amount", key: "transactionAmount" },
    { label: "Comments", key: "comments" },
    // { label: "Update by", key: "creator" },
    // { label: "Update On", key: "updateOn" },
    // Add more headers as needed
  ];

  const ioCashExporteDetails = IODetails?.ioCashHistory?.map((item, index) => ({
    Date: item?.transactionDate,
    "Transaction type": item?.transactionType,
    Amount: parseFloat(item?.transactionAmount) || 0,
    Comments: item?.comments,
  }));

  console.log(ioCashExporteDetails);

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

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

  const Total = () => {
    return (
      <Table size="sm">
        <Tbody backgroundColor="gray.50">
          <Tr>
            <Th
              textAlign={"center"}
              p={3}
              width="80px"
              color={"#004118"}
              whiteSpace="normal"
              wordBreak="normal"
              overflowWrap="normal"
            >
              Total
            </Th>
            <Th
              textAlign={"center"}
              p={3}
              width="210px"
              color={"#004118"}
              whiteSpace="normal"
              wordBreak="normal"
              overflowWrap="normal"
            >
              {" "}
            </Th>
            <Th
              textAlign={"center"}
              p={3}
              width="80px"
              color={"#004118"}
              whiteSpace="normal"
              wordBreak="normal"
              overflowWrap="normal"
            >
              {/* {totalAmount} */}
              {"5000"}
            </Th>
            <Th
              textAlign={"center"}
              p={3}
              width="160px"
              color={"#004118"}
              whiteSpace="normal"
              wordBreak="normal"
              overflowWrap="normal"
            >
              {" "}
            </Th>
            <Th
              textAlign={"center"}
              p={3}
              width="100px"
              color={"#004118"}
              whiteSpace="normal"
              wordBreak="normal"
              overflowWrap="normal"
            >
              {" "}
            </Th>
            <Th
              textAlign={"center"}
              p={3}
              width="100px"
              color={"#004118"}
              whiteSpace="normal"
              wordBreak="normal"
              overflowWrap="normal"
            >
              {" "}
            </Th>
          </Tr>
        </Tbody>
      </Table>
    );
  };

  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 display={"flex"} alignItems={"center"}>
            <Button
              onClick={() =>
                exportToExcelNew(ioCashExporteDetails, "IO Cash History")
              }
              leftIcon={<LuFileSpreadsheet />}
              colorScheme="forestGreen"
              size={"sm"}
              variant={"outline"}
              rounded={"sm"}
              fontSize={"xs"}
              isDisabled={ioCashExporteDetails?.length === 0}
            >
              Export xls
            </Button>

            {IODetails?.isInvestedAmount ? (
              <Button
                onClick={onOpen}
                leftIcon={<AddIcon />}
                colorScheme="forestGreen"
                size={"sm"}
                rounded={"sm"}
                fontSize={"xs"}
              >
                Add IO Cash
              </Button>
            ) : null}
          </HStack>
        </HStack>
      </Box>

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

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

      <AddCashDetails
        isOpen={isOpen}
        onClose={onClose}
        firstField={firstField}
      />
    </Box>
  );
};

export default IOCashDetailsOld;
