import {
  Badge,
  Box,
  Button,
  HStack,
  Link,
  Text,
  Tooltip,
  useDisclosure,
  useToast,
} from "@chakra-ui/react";
import React, { useContext, useEffect, useRef, useState } from "react";
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,
  EditIcon,
  ExternalLinkIcon,
} from "@chakra-ui/icons";
import IOArtifactsAdd from "../IOArtifactsAdd";
import IOArtifactsVideo from "./IOArtifactsVideo";
import SetDisplayOrder from "./SetDisplayOrderKeyMerits";
import { useParams } from "react-router-dom";
import {
  useDeleteImageArtifactsMutation,
  useDeleteVideoArtifactsMutation,
  useGetIOByIdQuery,
} from "../../../Services/io.service";
import { getFileNameFromPath } from "../../../Constants/Constants";
import ImageViewer from "../../../Components/ImageViewer";
import ToastBox from "../../../Components/ToastBox";
import SetDisplayOrderIOArtifactsImages from "./SetDisplayOrderIOArtifactsImages";
import SetDisplayOrderIOArtifactsVideo from "./SetDisplayOrderIOArtifactsVideo";

const IOArtifacts = ({ enableNextTab, index, data }) => {
  const toast = useToast()
  const params = useParams();
  const id = params?.id;

  const {
    data: IObyID,
    isLoading: IObyIDisLoading,
    error: IObyIDerror,
  } = useGetIOByIdQuery(id, { skip: !id });

  const { iOArtifacts, setIOArtifacts, slideFromRight } =
    useContext(GlobalStateContext);
  const { iOArtifactsTwo, setIOArtifactsTwo } = useContext(GlobalStateContext);
  const firstField = useRef();
  const secondField = useRef();
  const [searchTerm, setSearchTerm] = useState("");
  const [searchTermTwo, setSearchTermTwo] = useState("");
  const [isLoading, setIsLoading] = useState(true);
  const [isLoadingBtn, setIsLoadingBtn] = useState(false);
  const [deleteAlertImage, setDeleteAlertImage] = useState(false);
  const [deleteAlertVideo, setDeleteAlertVideo] = useState(false);
  const [actionId, setActionId] = useState(false);
  const [mouseEntered, setMouseEntered] = useState(false);
  const [mouseEnteredId, setMouseEnteredId] = useState("");
  const [imageSrc, setImageSrc] = useState(false);

  const { isOpen, onOpen, onClose } = useDisclosure();
  const [deleteVideoArtifacts] = useDeleteVideoArtifactsMutation();
  const [deleteImageArtifacts] = useDeleteImageArtifactsMutation();

  const {
    isOpen: isOpenVideo,
    onOpen: onOpenVideo,
    onClose: onCloseVideo,
  } = useDisclosure();

  const {
    isOpen: isOpenImageViewer,
    onOpen: onOpenImageViewer,
    onClose: onCloseImageViewer,
  } = useDisclosure();

  useEffect(() => {
    // Simulate loading
    const timer = setTimeout(() => {
      setIsLoading(false);
    }, 1500);

    // Cleanup the timer on component unmount
    return () => clearTimeout(timer);
  }, []);

  const handleUpdateStatus = debounce((id) => {
    setIOArtifacts((prevIOArtifacts) =>
      prevIOArtifacts.map((iOArtifacts) =>
        iOArtifacts.id === id
          ? { ...iOArtifacts, status: !iOArtifacts.status }
          : iOArtifacts
      )
    );
    setIOArtifactsTwo((prevIOArtifactsTwo) =>
      prevIOArtifactsTwo.map((iOArtifactsTwo) =>
        iOArtifactsTwo.id === id
          ? { ...iOArtifactsTwo, status: !iOArtifactsTwo.status }
          : iOArtifactsTwo
      )
    );
    toast({
      render: () => <ToastBox message={"Status changed successfully.!"} />,
    });
  }, 300);

  const handleDeleteVideo = async (id) => {
    setIsLoadingBtn(true);
    try {
      const res = await deleteVideoArtifacts(id);
      if (res?.data?.statusCode === 200) {
        setDeleteAlertVideo(false);
        setIsLoadingBtn(false);
        toast({
          render: () => <ToastBox message={res?.data?.message} status="success" />,
        });
      }
    } catch (error) {
      console.log(error);
    }
  };

  const handleDeleteImage = async (id) => {
    setIsLoadingBtn(true);
    try {
      const res = await deleteImageArtifacts(id);
      console.log(res);
      
      if (res?.data?.statusCode === 200) {
        setDeleteAlertImage(false);
        setIsLoadingBtn(false);
        toast({
          render: () => <ToastBox message={res?.data?.message} status="success" />,
        });

      }
    } catch (error) {
      console.log(error);
    }
  };

  const tableHeadRow = ["Sr.no", "File Name", "View image", "Action"];

console.log(IObyID?.data?.artifactsImage);
  // console.log(filteredData);
  const sortedDataImage = [...(IObyID?.data?.artifactsImage || [])]?.sort(
    (a, b) => a?.displayOrder - b?.displayOrder
  );


  const extractedArray = sortedDataImage?.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>
    ),
    "File Name": (
      <Box isTruncated={true}>
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
          {item.artifactName}
        </Text>
      </Box>
    ),
    "View image": (
      <Text
        color={"green.500"}
        justifyContent={slideFromRight ? "right" : "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>
    ),
    Action: (
      <Box display={"flex"} justifyContent={"center"} gap={3}>
        <Tooltip
          rounded={"sm"}
          fontSize={"xs"}
          label="Edit"
          bg="#fff"
          color={"blue.500"}
          placement="top"
        >
          <Button
            _hover={{ color: "blue.500" }}
            color="blue.400"
            rounded={"sm"}
            size={"xs"}
            onClick={() => {
              setActionId(item?.id);
              onOpen();
            }}
          >
            <EditIcon />
          </Button>
        </Tooltip>
        <Tooltip
          rounded={"sm"}
          fontSize={"xs"}
          label="Delete"
          bg="#fff"
          color={"red.500"}
          placement="top"
        >
          <Button
            onClick={() => {
              setActionId(item?.id);
              setDeleteAlertImage(true);
            }}
            _hover={{ color: "red.500" }}
            color="red.300"
            rounded={"sm"}
            size={"xs"}
          >
            <DeleteIcon />
          </Button>
        </Tooltip>
      </Box>
    ),
  }));


  console.log(IObyID?.data?.artifactsVideo);
// console.log(filteredData);
const sortedDataVideo = [...(IObyID?.data?.artifactsVideo || [])]?.sort(
  (a, b) => a?.displayOrder - b?.displayOrder
);





  const tableHeadRowTwo = [
    "Sr.no",
    "File Name",
    "Video streaming URL",
    "Action",
  ];

  const extractedArrayTwo = sortedDataVideo?.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>
      ),
      "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={slideFromRight ? "right" : "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>
      ),
      Action: (
        <Box display={"flex"} justifyContent={"center"} gap={3}>
          <Tooltip
            rounded={"sm"}
            fontSize={"xs"}
            label="Edit"
            bg="#fff"
            color={"blue.500"}
            placement="top"
          >
            <Button
              _hover={{ color: "blue.500" }}
              color="blue.400"
              rounded={"sm"}
              size={"xs"}
              onClick={() => {
                setActionId(item?.id);
                onOpenVideo();
              }}
            >
              <EditIcon />
            </Button>
          </Tooltip>
          <Tooltip
            rounded={"sm"}
            fontSize={"xs"}
            label="Delete"
            bg="#fff"
            color={"red.500"}
            placement="top"
          >
            <Button
              onClick={() => {
                setActionId(item?.id);
                setDeleteAlertVideo(true);
              }}
              _hover={{ color: "red.500" }}
              color="red.300"
              rounded={"sm"}
              size={"xs"}
            >
              <DeleteIcon />
            </Button>
          </Tooltip>
        </Box>
      ),
    })
  );

  return (
    <Box>
      <Box display={"flex"} justifyContent={"space-between"} mb={4}>
        <Box fontSize={"sm"} fontWeight={500}>
          Manage IO Images
        </Box>
        <HStack>
 

          {IObyID?.data?.artifactsImage?.length !== 0 &&<SetDisplayOrderIOArtifactsImages data={sortedDataImage} />}
          <Button
            leftIcon={<AddIcon />}
            onClick={onOpen}
            size={"sm"}
            fontSize={"xs"}
            rounded={"sm"}
            colorScheme={"forestGreen"}
          >
            Add Images
          </Button>
        </HStack>
        <IOArtifactsAdd
          isOpen={isOpen}
          onClose={onClose}
          firstField={firstField}
          actionId={actionId}
          setActionId={setActionId}
          data={IObyID?.data?.artifactsImage}
        />
      </Box>
      <DataTable
        emptyMessage={`We don't have any Sponers `}
        tableHeadRow={tableHeadRow}
        data={extractedArray}
        isLoading={isLoading}
        viewActionId={actionId}
        setViewActionId={setActionId}
        setMouseEnteredId={setMouseEnteredId}
        setMouseEntered={setMouseEntered}
      />
      <Box display={"flex"} justifyContent={"space-between"} mb={4}>
        <Box fontSize={"sm"} fontWeight={500}>
          Manage IO videos
        </Box>
        <HStack>
          {IObyID?.data?.artifactsVideo?.length !== 0 &&<SetDisplayOrderIOArtifactsVideo data={sortedDataVideo} />}
          <Button
            leftIcon={<AddIcon />}
            onClick={onOpenVideo}
            size={"sm"}
            fontSize={"xs"}
            rounded={"sm"}
            colorScheme={"forestGreen"}
          >
            Add Videos
          </Button>
        </HStack>
        <IOArtifactsVideo
          isOpen={isOpenVideo}
          onClose={onCloseVideo}
          secondField={secondField}
          actionId={actionId}
          setActionId={setActionId}
          data={IObyID?.data?.artifactsVideo}
        />
      </Box>
      <DataTable
        emptyMessage={`We don't have any Sponers `}
        tableHeadRow={tableHeadRowTwo}
        data={extractedArrayTwo}
        isLoading={isLoading}
        viewActionId={actionId}
        setViewActionId={setActionId}
        setMouseEnteredId={setMouseEnteredId}
        setMouseEntered={setMouseEntered}
      />
      <CustomAlertDialog
        onClose={() => setDeleteAlertImage(false)}
        isOpen={deleteAlertImage}
        message={"Are you sure you want to delete this image?"}
        alertHandler={() => handleDeleteImage(actionId)}
        isLoading={isLoadingBtn}
      />
      <CustomAlertDialog
        onClose={() => setDeleteAlertVideo(false)}
        isOpen={deleteAlertVideo}
        message={"Are you sure you want to delete this video?"}
        alertHandler={() => handleDeleteVideo(actionId)}
        isLoading={isLoadingBtn}
      />

      <ImageViewer
        isOpen={isOpenImageViewer}
        onClose={onCloseImageViewer}
        onOpen={onOpenImageViewer}
        src={imageSrc}
      />
    </Box>
  );
};

export default IOArtifacts;
