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

import { AddIcon, DragHandleIcon, ExternalLinkIcon } from "@chakra-ui/icons";
import DataTable from "../../../Components/DataTable/DataTable";
import { useSetDisplayOrderIOArtifactsImageMutation } from "../../../Services/io.service";
import ToastBox from "../../../Components/ToastBox";

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

  const tableHeadRow = ["", "File Name", "View image"];

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

  // 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>
        ),
        "File Name": (
          <Box isTruncated={true}>
            <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
              {item.artifactName}
            </Text>
          </Box>
        ),
        
    "View image": (
      <Text
        color={"green.500"}
        justifyContent={"left"}
        as={"span"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        <Badge
          px={2}
          py={0.5}
          display={"flex"}
          alignItems={"center"}
          textTransform={"inherit"}
          fontWeight={500}
          colorScheme={"forestGreen"}
        >
          <Link
            href={import.meta.env.VITE_IMAGE_URL + item?.artifactPathName}
            isExternal
          >
            <Box
              // onClick={() => {
              //   setImageSrc(item?.artifactPathName);
              //   onOpenImageViewer();
              // }}
              as="span"
              cursor={"pointer"}
            >
              View
            </Box>{" "}
            <ExternalLinkIcon />
          </Link>
        </Badge>
      </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 SetDisplayOrderIOArtifactsImages;
