import {
  Box,
  Button,
  Drawer,
  DrawerBody,
  DrawerCloseButton,
  DrawerContent,
  DrawerFooter,
  DrawerHeader,
  DrawerOverlay,
  FormControl,
  FormErrorMessage,
  FormHelperText,
  FormLabel,
  Input,
  Stack,
  useToast,
} from "@chakra-ui/react";
import * as yup from "yup";
import React, { useState, useEffect } from "react";
import { useForm, Controller } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import CustomAlertDialog from "../../../Components/CustomAlertDialog";
import { v4 as uuidv4 } from "uuid";
import { useCreateVideoArtifactsMutation, useUpdateVideoArtifactsMutation } from "../../../Services/io.service";
import { useParams } from "react-router-dom";
import ToastBox from "../../../Components/ToastBox";

const investmentVideoSchema = yup.object().shape({
  artifactName: yup.string().required("Artifact name is required")
  .max(50, "Approve Comment cannot be more than 50 characters"),
  artifactStreamingURL: yup.string()
    .required("Artifact streaming URL is required")
    .url("Invalid URL format"),
});

const IOArtifactsAdd = ({ isOpen, onClose, firstField, actionId, setActionId, data }) => {
  const params = useParams()
  const id = params?.id
  const [file, setFile] = useState("");
  const [fileName, setFileName] = useState("");
  const [isLoading, setIsLoading] = useState(false)
  const [alert, setAlert] = useState(false);
  const toast = useToast();


  const found = data?.find((item) => item?.id === actionId);
  console.log(actionId);


  const [createArtifactsVideo] = useCreateVideoArtifactsMutation()
  const [updateVideoArtifacts] = useUpdateVideoArtifactsMutation()
  // const {
  //   data
  // } = useGetArtifactsQuery(id)

  const {
    control,
    handleSubmit,
    watch,
    reset,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(investmentVideoSchema),
  });



  // useEffect to reset the form when `found` changes
  useEffect(() => {
    if (found && actionId) {
      reset({
        artifactName: found?.artifactName,
        artifactStreamingURL: found?.artifactStreamingURL,
      });
    }
  }, [found, reset]);


  const onSubmit = async (data) => {
    setIsLoading(true)



    try {


      if (found) {
        const res = await updateVideoArtifacts({ data, id: found?.id })
        if (res?.data?.statusCode === 200) {
          toast({
            render: () => <ToastBox message={res?.data?.message} />,
          });
          setAlert(false);
          setIsLoading(false)
          handleClose();
        }
      } else {

        const res = await createArtifactsVideo({ data, id })
        if (res?.data?.statusCode === 200) {
          toast({
            render: () => <ToastBox message={res?.data?.message} />,
          });
          setAlert(false);
          setIsLoading(false)
          setActionId(false);
          handleClose();
        }

      }


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

    }

  };



  const handleConfirm = () => {
    handleSubmit(onSubmit)();
  };

  const handleSave = () => {
    handleSubmit(onSubmit)();
  };

  const handleClose = () => {
    onClose()
    reset()
    setActionId(false);
    reset({
      artifactName: "",
      artifactStreamingURL: "",
    });
  }

  return (
    <>
      <Drawer
        size={"md"}
        isOpen={isOpen}
        placement="right"
        initialFocusRef={firstField}
        onClose={handleClose}
      >
        <DrawerOverlay />
        <DrawerContent>
          <DrawerCloseButton />
          <DrawerHeader fontSize={"sm"}>IO Artifacts Video</DrawerHeader>

          <DrawerBody>
            <Stack spacing={4}>
              <FormControl isInvalid={errors.artifactName} isRequired>
                <FormLabel fontSize={"sm"}>Artifact Name</FormLabel>
                <Controller
                  name="artifactName"
                  control={control}
                  render={({ field }) => (
                    <Input {...field} fontSize={"sm"} type="text" size={"sm"} maxLength={50}  />
                  )}
                />
                <FormErrorMessage fontSize={"xs"} fontWeight={500}>
                  {errors.artifactName?.message}
                </FormErrorMessage>
                <FormHelperText fontSize="xs" color="gray.500">
                    <Box as="span" me={1}>Maximum length should be 50 characters. You have entered </Box>
                    {watch("artifactName")?.length || 0} characters.
                  </FormHelperText>
              </FormControl>

              <FormControl isInvalid={errors.artifactStreamingURL} isRequired>
                <FormLabel fontSize={"sm"}>Artifact Streaming URL</FormLabel>
                <Controller
                  name="artifactStreamingURL"
                  control={control}
                  render={({ field }) => (
                    <Input {...field} fontSize={"sm"} type="url" size={"sm"} />
                  )}
                />
                <FormErrorMessage fontSize={"xs"} fontWeight={500}>
                  {errors.artifactStreamingURL?.message}
                </FormErrorMessage>
              </FormControl>
            </Stack>
          </DrawerBody>

          <DrawerFooter>
            <Button
              variant="outline"
              colorScheme={"forestGreen"}
              rounded={"sm"}
              size={"sm"}
              mr={3}
              onClick={handleClose}
            >
              Cancel
            </Button>

            <Button
              colorScheme={"forestGreen"}
              rounded={"sm"}
              size={"sm"}
              onClick={() => setAlert(true)}
            >
              Save
            </Button>
          </DrawerFooter>
        </DrawerContent>
      </Drawer>


      <CustomAlertDialog
        isOpen={alert}
        onClose={() => setAlert(false)}
        alertHandler={handleSave}
        message={"Are you sure you want to add this artifact?"}
        isLoading={isLoading}
      />
    </>
  );
};

export default IOArtifactsAdd;
