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 { useSetDisplayOrderMutation } from "../../../Services/io.service";
import ToastBox from "../../../Components/ToastBox";

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

  const tableHeadRow = ["", "Title", "Icon"];

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

  // 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 w={"20px"} isTruncated={true}>
            <DragHandleIcon />
          </Box>
        ),
        Title: (
          <Box w={"300px"} isTruncated={true}>
            <Text
              justifyContent={"left"}
              as={"span"}
              color={"teal.900"}
              fontWeight={"500"}
              className="d-flex align-items-center web-text-small"
            >
              {item?.meritsHeader}
            </Text>
          </Box>
        ),
        Icon: item?.icon?.iconFilePath && (
          <Box
          display={"flex"}
          justifyContent={"center"}
          alignItems={"center"}>
          <Image
            rounded={"md"}
            display={"flex"}
            p={1}
            justifyContent={"center"}
            alignItems={"center"}
            src={import.meta.env.VITE_IMAGE_URL + item?.icon?.iconFilePath}
            w={8}
            h={8}
          /></Box>
        ),
      }));
      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 SetDisplayOrderKeyMerits;
