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

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

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

  const tableHeadRow = ["", "File Name", "Video streaming URL"];

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

  // 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>
        ),
        "Video streaming URL": (
          <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={item?.artifactStreamingURL} isExternal>
              <Box as="span">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 SetDisplayOrderIOArtifactsVideo;
