import React, { useState, useEffect } from "react";
import {
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalFooter,
  ModalBody,
  ModalCloseButton,
  useDisclosure,
  Button,
  Box,
  Text,
  Image,
  HStack,
  useToast,
} from "@chakra-ui/react";

import { AddIcon, DragHandleIcon } from "@chakra-ui/icons";
import DataTable from "../../../Components/DataTable/DataTable";
import { useSetDisplayOrderIODocumentsMutation } from "../../../Services/io.service";
import ToastBox from "../../../Components/ToastBox";
import { GrDocumentPdf } from "react-icons/gr";
import { TbFileTypeDocx } from "react-icons/tb";

const SetDisplayOrderIODocuments = ({ data,  }) => {
  const toast = useToast();
  const { isOpen, onOpen, onClose } = useDisclosure();
  const [isLoading, setIsLoading] = useState(false);

  const tableHeadRow = ["", "Type", "File name"];

  const [extractedArray, setExtractedArray] = useState([]);
  const [displayOrder, setDisplayOrder] = useState(null);
  const [resetDisplayOrder] = useSetDisplayOrderIODocumentsMutation();

  // Update state when `data` prop changes
  useEffect(() => {
    if (data) {
      const formattedData = data.map((item, index) => ({
        id: item?.id,
        displayOrder: index + 1, // Add displayOrder property
        "": (
          <Box maxW={"20px"} isTruncated={true}>
            <DragHandleIcon />
          </Box>
        ),
        Type: (
          <Text
        justifyContent={"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": (
        <Text as="span" color="teal.900" fontWeight="500">
          {item.documentName}
        </Text>
        ),
      }));
      setExtractedArray(formattedData);
    }
  }, [data]);

  // Log the updated order in the desired format whenever `extractedArray` changes
  useEffect(() => {
    const displayOrderArray = extractedArray.map((item, index) => ({
      id: item.id,
      displayOrder: index + 1,
    }));
    setDisplayOrder(displayOrderArray);
  }, [extractedArray]);

  const handleSetOrder = async () => {
    setIsLoading(true);
    const data = {
      displayOrder: displayOrder,
    };

    try {
      const res = await resetDisplayOrder({ data });
      console.log(res?.data?.statusCode);
      if (res?.data?.statusCode === 200) {
        toast({
          render: () => <ToastBox message={res?.data?.message} />,
        });
        onClose();
      }

      setIsLoading(false);
    } catch (error) {
      console.log(res);
      setIsLoading(false);
    }
  };

  return (
    <>
      <Button
        leftIcon={<AddIcon />}
        size={"sm"}
        fontSize={"xs"}
        rounded={"sm"}
        variant={"outline"}
        colorScheme="forestGreen"
        onClick={onOpen}
      >
        Set Display Order
      </Button>

      <Modal isCentered size={"xl"} isOpen={isOpen} onClose={onClose}>
        <ModalOverlay />
        <ModalContent>
          <ModalHeader fontSize={"lg"}>Set Display Order</ModalHeader>
          <ModalCloseButton />
          <ModalBody>
            <DataTable
              emptyMessage={`We don't have any Sponsors`}
              tableHeadRow={tableHeadRow}
              data={extractedArray}
              setData={setExtractedArray}
              isDraggable={true}
            />
          </ModalBody>

          <ModalFooter>
            <Button
              size={"sm"}
              fontSize={"xs"}
              rounded={"sm"}
              variant={"outline"}
              colorScheme="forestGreen"
              mr={3}
              onClick={onClose}
            >
              Reset order
            </Button>
            <Button
              size={"sm"}
              fontSize={"xs"}
              rounded={"sm"}
              colorScheme="forestGreen"
              variant="solid"
              onClick={handleSetOrder}
              isLoading={isLoading}
            >
              Set order
            </Button>
          </ModalFooter>
        </ModalContent>
      </Modal>
    </>
  );
};

export default SetDisplayOrderIODocuments;
