import {
  Box,
  Button,
  Drawer,
  DrawerBody,
  DrawerCloseButton,
  DrawerContent,
  DrawerFooter,
  DrawerHeader,
  DrawerOverlay,
  FormControl,
  FormErrorMessage,
  FormLabel,
  Icon,
  Image,
  Input,
  Stack,
  Text,
  useToast,
} from "@chakra-ui/react";
import * as yup from "yup";
import React, { useEffect, useRef, useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import CustomAlertDialog from "../../Components/CustomAlertDialog";
import {
  useCreateImageArtifactsMutation,
  useUpdateImageArtifactsMutation,
} from "../../Services/io.service";
import { useParams } from "react-router-dom";
import ToastBox from "../../Components/ToastBox";
import { bytesToMB } from "./InvestmentDocuments";
import { formatTimestampInGulfTimezone } from "../../Constants/Constants";
import { IoMdRemoveCircleOutline } from "react-icons/io";

const investmentImageSchema = yup.object().shape({
  artifactName: yup.string().required("Artifact image name is required"),
  artifactPathName: yup.mixed().required("Artifact image is required"),
});

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

  const [createImageArtifacts] = useCreateImageArtifactsMutation();
  const [updateImageArtifacts] = useUpdateImageArtifactsMutation();

  const found = data?.find((item) => item?.id === actionId);
  const fileInputRef = useRef(null);

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

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

  const onSubmit = async (data) => {
    console.log("hit");
    setIsLoading(true);
    const formData = new FormData();
    formData.append("artifactName", data.artifactName);

    file && formData.append("artifactPathName", file); // Assuming artifactPathName is an array of files
    try {
      if (found) {
        const res = await updateImageArtifacts({
          data: formData,
          id: found?.id,
        });

        if (res?.data?.statusCode === 200) {
          toast({
            render: () => <ToastBox message={res?.data?.message} />,
          });
          setFile(null);
          setIsLoading(false);
          setAlert(false);
          setPreview(null);
          onClose();
          reset({
            artifactName: "",
            artifactPathName: "",
          });
        } else {
          toast({
            render: () => (
              <ToastBox message={"Something went wronng"} error="error" />
            ),
          });
          setFile(null);
          setIsLoading(false);
          setAlert(false);
          setPreview(null);
          onClose();
          reset({
            artifactName: "",
            artifactPathName: "",
          });
        }

        if (res?.error) {
          toast({
            render: () => (
              <ToastBox message={res?.error?.data?.message} status={"error"} />
            ),
          });
          reset();
          setIsLoading(false);
        }
      } else {
        const res = await createImageArtifacts({ data: formData, id });
        if (res?.data?.statusCode === 200) {
          toast({
            render: () => <ToastBox message={res?.data?.message} />,
          });
          reset({
            artifactName: "",
            artifactPathName: "",
          });
          setFile(null);
          setIsLoading(false);
          setAlert(false);
          setPreview(null);
          onClose();
        }
      }
    } catch (error) {
      console.log(error);
    }

    // Close the form/modal
    // onClose();
  };

  const handleFileChange = (e) => {
    const file = e.target.files[0];
    setFile(file);
    setValue("artifactPathName", file);
    const reader = new FileReader();
    reader.onloadend = () => {
      setPreview(reader.result);
    };
    reader.readAsDataURL(file);
  };

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

  const handleClose = () => {
    setFile(null);
    setPreview(null);
    reset({
      artifactName: "",
      artifactPathName: "",
    });

    onClose();
    setActionId(false);
  };

  const handleRemove = () => {
    setFile(null);
    setPreview(null);
    // Reset the file input value
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };

  const handleAlertClose = () => {
    setAlert(false);
    setIsLoading(false);
  };

  return (
    <>
      <Drawer
        size={"md"}
        isOpen={isOpen}
        placement="right"
        initialFocusRef={firstField}
        onClose={handleClose}
      >
        <DrawerOverlay />
        <DrawerContent>
          <DrawerCloseButton />
          <DrawerHeader fontSize={"sm"}>IO Artifacts Image</DrawerHeader>
          <Box as="form">
            <DrawerBody>
              <Stack spacing={4}>
                <FormControl isInvalid={errors.artifactName}>
                  <FormLabel fontSize={"sm"}>Artifact Name</FormLabel>
                  <Controller
                    name="artifactName"
                    control={control}
                    render={({ field }) => (
                      <Input
                        {...field}
                        fontSize={"sm"}
                        type="text"
                        size={"sm"}
                      />
                    )}
                  />
                  <FormErrorMessage fontSize={"xs"} fontWeight={500}>
                    {errors.artifactName?.message}
                  </FormErrorMessage>
                </FormControl>

                <FormControl
                  isInvalid={
                    !preview &&
                    errors.artifactPathName?.message &&
                    errors.artifactPathName
                  }
                >
                  <FormLabel fontSize={"sm"}>Artifact Image</FormLabel>
                  <Input
                    type="file"
                    accept=".jpg,.jpeg,.png"
                    onChange={handleFileChange}
                    fontSize={"sm"}
                    size={"sm"}
                    className="form-control"
                    ref={fileInputRef} // Set the ref here
                  />
                  <FormErrorMessage fontSize={"xs"} fontWeight={500}>
                    {!preview &&
                      errors.artifactPathName?.message &&
                      errors.artifactPathName?.message}
                  </FormErrorMessage>
                  {preview && (
                    <>
                      <Image
                        rounded={"md"}
                        src={preview}
                        alt="Image Preview"
                        mt={3}
                        width={300}
                        height={150}
                        objectFit={"cover"}
                        backgroundSize={"cover"}
                      />
                      <Box
                        w={"100%"}
                        position={"relative"}
                        mt={2}
                        fontSize={"xs"}
                        display={"flex"}
                        flexDirection={"column"}
                        as="span"
                      >
                        <Text as={"span"}>Name: {file?.name}</Text>
                        <Text as={"span"} fontSize={"xs"}>
                          File size: {bytesToMB(file?.size)}
                        </Text>
                        <Text as={"span"} fontSize={"xs"}>
                          Last update:{" "}
                          {formatTimestampInGulfTimezone(file?.lastModified)}
                        </Text>
                        <Icon
                          onClick={() => handleRemove()}
                          _hover={{ bg: "gray.100" }}
                          transition={"all 0-5s"}
                          cursor={"pointer"}
                          position={"absolute"}
                          right={0}
                          p={1}
                          bottom={0}
                          rounded={"lg"}
                          boxSize={7}
                          as={IoMdRemoveCircleOutline}
                        />
                      </Box>
                    </>
                  )}
                  {found && !preview && (
                    <Image
                      rounded={"md"}
                      src={
                        import.meta.env.VITE_IMAGE_URL +
                        watch()?.artifactPathName
                      }
                      alt="Image Preview"
                      mt={2}
                    />
                  )}
                </FormControl>
              </Stack>
            </DrawerBody>

            <DrawerFooter mt={5}>
              <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)}
                // type="submit"
              >
                Save
              </Button>
            </DrawerFooter>
          </Box>
        </DrawerContent>
      </Drawer>
      <CustomAlertDialog
        isOpen={alert}
        onClose={handleAlertClose}
        alertHandler={handleSave}
        message={"Are you sure you want to add this artifact?"}
        isLoading={loading}
      />
    </>
  );
};

export default IOArtifactsAdd;
