import {
  Box,
  Button,
  Input,
  Text,
  Tooltip,
  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,
  DeleteIcon,
  DownloadIcon,
  EditIcon,
  ViewIcon,
} from "@chakra-ui/icons";

const IOArtifacts = () => {
  const { iOArtifacts, setIOArtifacts, slideFromRight } =
    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 = [
    "Sr.no", 
    "Type", 
    "File Name", 
    "Document", 
    "Action"
  ];

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

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

    return nameMatches;
  });

  const handleDelete = () => {
    const updatedIOArtifacts = iOArtifacts.filter(
      (iOArtifacts) => iOArtifacts.id !== actionId
    );

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

  const extractedArray = filteredData?.map((item, index) => ({
    "Sr.no": (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {index + 1}
      </Text>
    ),
    Type: (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {item.type}
      </Text>
    ),
    "File Name": (
      <Box isTruncated={true}>
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
          {item.fileName}
        </Text>
      </Box>
    ),
    "Document": (
      <Text
        color={"green.500"}
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {item.document}
      </Text>
    ),
    Action: (
      <Box display={"flex"} justifyContent={"space-evenly"}>
        <Tooltip
          rounded={"sm"}
          fontSize={"xs"}
          label="View"
          bg="#fff"
          color={"green.500"}
          placement="top"
        >
          <Button
            _hover={{ color: "green.500" }}
            // transition={"0.5s all"}
            onClick={() => {
              navigate(`view-investment/${item.id}`);
            }}
            color="green.300"
            rounded={"sm"}
            size={"xs"}
          >
            <ViewIcon />
          </Button>
        </Tooltip>
        <Tooltip
          rounded={"sm"}
          fontSize={"xs"}
          label="Edit"
          bg="#fff"
          color={"blue.500"}
          placement="top"
        >
          <Button
            _hover={{ color: "blue.500" }}
            // transition={"0.5s all"}
            color="blue.400"
            rounded={"sm"}
            size={"xs"}
          >
            <EditIcon />
          </Button>
        </Tooltip>
        <Tooltip
          rounded={"sm"}
          fontSize={"xs"}
          label="Delete"
          bg="#fff"
          color={"red.500"}
          placement="top"
        >
          <Button
            onClick={() => {
              setActionId(item?.id);
              setDeleteAlert(true);
            }}
            _hover={{ color: "red.500" }}
            // transition={"0.5s all"}
            color="red.300"
            rounded={"sm"}
            size={"xs"}
          >
            <DeleteIcon />
          </Button>
        </Tooltip>
      </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 IOArtifacts;
