import {
  Avatar,
  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";

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

const IOCashDetails = () => {
  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);
  }, []);

  // 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"
      >
        {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 ={"center"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
       {`$${parseFloat(item.transactionAmount||0).toLocaleString()}`}
      </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"
      >
        {item.updateOn}
      </Text>
    ),
  }));

  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)}
          />


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

        </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 IOCashDetails;
