import { Box, Button, Input, Text, useDisclosure } from "@chakra-ui/react";
import React, { useContext, useEffect, useRef, useState } from "react";
import InvestmentDocuments from "../InvestmentDocuments";
import DataTable from "../../../Components/DataTable/DataTable";
import CustomAlertDialog from "../../../Components/CustomAlertDialog";
import GlobalStateContext from "../../../Contexts/GlobalStateContext";
import { debounce } from "../../Master/Sponser/AddSponser";
import { formatDate } from "../../../Components/Functions/UTCConvertor";
import { AddIcon } from "@chakra-ui/icons";

const InvestmentDocument = ({ control, errors }) => {
    const { create, setCreate, sponser, setSponser, investment, setInvestment } =
      useContext(GlobalStateContext);
      const firstField = useRef();
    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 { isOpen, onOpen, onClose } = useDisclosure();

    useEffect(() => {
        // Simulate loading
        const timer = setTimeout(() => {
          setIsLoading(false);
        }, 1500);
    
        // Cleanup the timer on component unmount
        return () => clearTimeout(timer);
      }, []);


    
  const tableHeadRow = [
    "Sponser name",
    "Address",
    "Mobile no",
    "Created At",
    "Action",
  ];

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

  const filteredData = create?.filter((item) => {
    // Filter by name (case insensitive)
    const name = item.sponserName;
    const searchLower = searchTerm.toLowerCase();
    const nameMatches = name.toLowerCase().includes(searchLower);

    return nameMatches;
  });

  const handleDelete = () => {
    const updatedCreate = create.filter((create) => create.id !== actionId);

    setTimeout(() => {
      setSponser(updatedCreate);
      setDeleteAlert(false);
      setIsLoading(false);
    }, 100);
    setIsLoading(true);
  };

  const extractedArray = filteredData?.map((item) => ({
    id: item?.id,
    "Sponser name": (
      <Text
        justifyContent={"left"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
        h={7}
      >
        "{item.sponserName}"
      </Text>
    ),
    Address: (
      <Box w={350} isTruncated={true}>
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
          " {item.sponserAddress}"
        </Text>
      </Box>
    ),
    "Mobile no": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
          "{item.mobileNo}"
        </Text>
      </Box>
    ),

    "Created At": (
      <span className="d-flex justify-content-between align-items-center">
        <Text as={"span"} color={"gray.600"} fontWeight={"500"}>
          {formatDate(item.createdAt)}
        </Text>
      </span>
    ),
    Action: <Box display={"flex"} justifyContent={"space-between"}></Box>,
  }));


  return (
    <Box>
      <Box display={"flex"} justifyContent={"space-between"} mb={4}>
        <Input
          type="search"
          width={300}
          placeholder="Search..."
          size="sm"
          rounded="sm"
          focusBorderColor="green.500"
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
        />
        <Button
          leftIcon={<AddIcon />}
          onClick={onOpen}
          size={"xs"}
          // width={"44.5%"}
          fontSize={"xs"}
          rounded={"sm"}
          ps={3}
          pe={4}

          colorScheme="green"
        >
          Add
        </Button>
        <InvestmentDocuments
          isOpen={isOpen}
          onClose={onClose}
          firstField={firstField}
        />
      </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 InvestmentDocument;
