import {
  Box,
  Button,
  HStack,
  Input,
  Text,
  Tooltip,
  useDisclosure,
  useToast,
} from "@chakra-ui/react";
import React, { useContext, useEffect, useRef, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
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 {
  AddIcon,
  DeleteIcon,
  DownloadIcon,
  EditIcon,
  ViewIcon,
} from "@chakra-ui/icons";
import { GrDocumentPdf } from "react-icons/gr";
import { AiOutlineFileGif, AiOutlineFileWord } from "react-icons/ai";
import InvestmentView from "../ViewIO/InvestmentView";
import InvestmentEdit from "../EditIO/InvestmentEdit";
import {
  useDeleteIODocsMutation,
  useGetInvestmentDocumentsQuery,
} from "../../../Services/io.service";
import ToastBox from "../../../Components/ToastBox";
import { getFileNameFromPath } from "../../../Constants/Constants";
import { TbFileTypeDocx } from "react-icons/tb";
import SetDisplayOrder from "./SetDisplayOrderKeyMerits";
import SetDisplayOrderIODocuments from "./SetDisplayOrderIODocuments";

const downloadFile = (filePath, fileName) => {

  fetch(import.meta.env.VITE_IMAGE_URL+filePath)
    .then((response) => {
      if (!response.ok) {
        throw new Error("Network response was not ok");
      }
      return response.blob();
    })
    .then((blob) => {
      // Create a new Blob object with the correct MIME type
      const fileBlob = new Blob([blob], { type: blob.type });

      // Create a URL for the Blob object
      const url = window.URL.createObjectURL(fileBlob);

      // Create a link element to trigger the download
      const link = document.createElement("a");
      link.href = url;

      // Set the download attribute with the specified file name
      link.setAttribute("download", fileName);

      // Append the link to the document and trigger the download
      document.body.appendChild(link);
      link.click();

      // Clean up by revoking the URL and removing the link element
      window.URL.revokeObjectURL(url);
      document.body.removeChild(link);
    })
    .catch((error) => {
      console.error("There was a problem with the file download:", error);
    });
};

const InvestmentDocument = ({ control, errors, enableNextTab, index, }) => {
  const params = useParams();
  const id = params?.id;
  const { slideFromRight, create, setCreate, IODetails } = useContext(GlobalStateContext);
  const firstField = useRef();
  const secondField = useRef();
  const thirdField = useRef();
  const [searchTerm, setSearchTerm] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [deleteAlert, setDeleteAlert] = useState(false);
  const [mouseEntered, setMouseEntered] = useState(false);
  const [mouseEnteredId, setMouseEnteredId] = useState("");
  const { isOpen, onOpen, onClose } = useDisclosure();
  const {
    isOpen: isViewOpen,
    onOpen: onViewOpen,
    onClose: onViewClose,
  } = useDisclosure();
  const {
    isOpen: isEditOpen,
    onOpen: onEditOpen,
    onClose: onEditClose,
  } = useDisclosure();
  const [actionId, setActionId] = useState(null);
  const navigate = useNavigate();
  const toast = useToast();

  const [deleteIODocs] = useDeleteIODocsMutation();

  // const {
  //   data,
  //   error,
  //   isLoading: isIODocLoading,
  // } = useGetInvestmentDocumentsQuery(id, {
  //   skip: !id,
  // });

  


  

  const tableHeadRow = ["Sr.no", "Type", "File Name", "Document", "Action"];

  const handleUpdateStatus = debounce((id) => {
    setCreate((prevCreate) =>
      prevCreate.map((create) =>
        create.id === id ? { ...create, status: !create.status } : create
      )
    );
    toast({
      render: () => (
        <Box color="white" p={3} bg="green.500">
          Status changed successfully!
        </Box>
      ),
    });
  }, 300);

  const filteredData = IODetails?.documents?.filter((item) =>
    item?.documentName?.toLowerCase().includes(searchTerm.toLowerCase())
  );

    const sortedData = filteredData?.sort(
      (a, b) => a.displayOrder - b.displayOrder
    );

  const handleView = (id) => {
    setActionId(id);
    onViewOpen();
  };

  const handleEdit = (id) => {
    setActionId(id);
    onEditOpen();
  };

  const handleDelete = async () => {
    setIsLoading(true);
    try {
      const res = await deleteIODocs(actionId);
      if (res?.data?.statusCode === 200) {
        toast({
          render: () => <ToastBox message={res?.data?.message} />,
        });
        setIsLoading(false);
        setDeleteAlert(false);
      } else if (res?.error) {
        toast({
          render: () => (
            <ToastBox message={res?.error?.data?.message} status={"error"} />
          ),
        });
        setIsLoading(false);
        setDeleteAlert(false);
      }
    } catch (error) {
      console.log(error);
    }
  };

  const extractedArray = sortedData?.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"
        fontSize={"xl"}
      >
        {item.documentType === "application/pdf" ? (
          <GrDocumentPdf />
        ) : (
          <TbFileTypeDocx fontSize={21} />
        )}
      </Text>
    ),
    "File Name": (
      <Box w="200px" isTruncated>
        <Text as="span" color="teal.900" fontWeight="500">
          {item.documentName}
        </Text>
      </Box>
    ),
    Document: (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as="span"
        color="teal.900"
        fontWeight="500"
        className="d-flex align-items-center web-text-small"
      >
        {getFileNameFromPath(item?.documentPath)}
      </Text>
    ),
    Action: (
      <Box display="flex" justifyContent="center" gap={2}>
        {/* <Tooltip
          rounded="sm"
          fontSize="xs"
          label="View"
          bg="#fff"
          color="green.500"
          placement="top"
        >
          <Button
            _hover={{ color: "green.500" }}
            onClick={() => handleView(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" }}
            onClick={() => handleEdit(item.id)}
            color="blue.400"
            rounded="sm"
            size="xs"
          >
            <EditIcon />
          </Button>
        </Tooltip>
        <Tooltip
          rounded="sm"
          fontSize="xs"
          label="Download"
          bg="#fff"
          color="blue.500"
          placement="top"
        >
          <Button
            _hover={{ color: "blue.500" }}
            color="blue.400"
            rounded="sm"
            size="xs"
            onClick={() => downloadFile(item?.documentPath, item?.documentName)}
          >
            <DownloadIcon />
          </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" }}
            color="red.300"
            rounded="sm"
            size="xs"
          >
            <DeleteIcon />
          </Button>
        </Tooltip>
      </Box>
    ),
  }));

  return (
    <Box>
      <Box display="flex" justifyContent="end" mb={4} gap={2}>
        

        {filteredData?.length !== 0 &&<SetDisplayOrderIODocuments data={filteredData} />}
        <Button
          leftIcon={<AddIcon />}
          onClick={onOpen}
          size="sm"
          fontSize="xs"
          rounded="sm"
          colorScheme="forestGreen"
        >
          Add Document
        </Button>
        <InvestmentDocuments
          create={create}
          setCreate={setCreate}
          isOpen={isOpen}
          onClose={onClose}
          firstField={firstField}
        />
        <InvestmentView
          id={actionId}
          isOpen={isViewOpen}
          onClose={onViewClose}
          secondField={secondField}
        />
        <InvestmentEdit
          data={IODetails?.documents}
          id={actionId}
          isOpen={isEditOpen}
          onClose={onEditClose}
          thirdField={thirdField}
        />
      </Box>
      <DataTable
        emptyMessage="We don't have any Documents"
        tableHeadRow={tableHeadRow}
        data={extractedArray}
        isLoading={false}
        viewActionId={actionId}
        setViewActionId={setActionId}
        setMouseEnteredId={setMouseEnteredId}
        setMouseEntered={setMouseEntered}
      />
      {/* <HStack justifyContent="flex-end">
        <Button
          ps={8}
          pe={8}
          colorScheme="forestGreen"
          variant={'outline'}
          size="sm"
          rounded="sm"
          onClick={() => enableNextTab(index)}
        >
          Next
        </Button>
      </HStack> */}
      <CustomAlertDialog
        onClose={() => setDeleteAlert(false)}
        isOpen={deleteAlert}
        message="Are you sure you want to delete the Investment?"
        alertHandler={handleDelete}
        isLoading={isLoading}
      />
    </Box>
  );
};

export default InvestmentDocument;
