import {
  Button,
  Drawer,
  DrawerBody,
  DrawerCloseButton,
  DrawerContent,
  DrawerFooter,
  DrawerHeader,
  FormControl,
  FormLabel,
  Input,
  Box,
  Text,
  useToast,
} from "@chakra-ui/react";
import React, { useContext, useEffect, useState } from "react";
import {
  bytesToMB,
  getFileIcon,
  investmentDocSchema,
} from "../InvestmentDocuments";
import { yupResolver } from "@hookform/resolvers/yup";
import { useForm } from "react-hook-form";
import GlobalStateContext from "../../../Contexts/GlobalStateContext";
import { getFileNameFromPath } from "../../../Constants/Constants";
import CustomAlertDialog from "../../../Components/CustomAlertDialog";
import { useUpdateInvestmentDocumentsMutation } from "../../../Services/io.service";
import ToastBox from "../../../Components/ToastBox";

const InvestmentEdit = ({ isOpen, onClose, thirdField, id, data }) => {
  const toast = useToast();
  const { create, setCreate } = useContext(GlobalStateContext);
  const [formData, setFormData] = useState(null);
  const [alert, setAlert] = useState(false);
  const [file, setFile] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const filteredObject = create?.find((item) => item?.id === id);

  const [updateInvestmentDocuments] = useUpdateInvestmentDocumentsMutation();

  // =====================[ variables ]
  const filterObject = data?.find((item) => item?.id === id);

  const getFileTitle = (type) => {
    switch (type) {
      case "application/pdf":
        return "PDF";
      case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
      case "application/msword":
        return "DOCX";
      case "image/jpeg":
      case "image/png":
      case "image/gif":
        return "JPG";
      default:
        return "HH";
    }
  };

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

  console.log(errors);
  

  // useEffect to reset the form when `found` changes
  useEffect(() => {
    if (filterObject) {
      reset({
        document: filterObject?.documentPath,
        fileName: filterObject?.documentName,
        documentNameArabic: filterObject?.documentNameArabic,
      });
    }
  }, [filterObject, reset]);

  useEffect(() => {
    if (filteredObject) {
      reset({
        fileName: filteredObject?.fileName,
        document: filteredObject?.document,
        documentNameArabic: filterObject?.documentNameArabic,
        Type: filteredObject?.Type,
      });
    }
  }, [id, create, reset]);

  const handleConfirm = async () => {
    setIsLoading(true);
    try {
      const res = await updateInvestmentDocuments({ data: formData, id });
      console.log(res);
      if (res?.error) {
        toast({
          render: () => (
            <ToastBox
              message={
                res?.error?.data?.message
                  ? res?.error?.data?.message
                  : "File size is too large"
              }
              status={"error"}
            />
          ),
        });
        setIsLoading(false);
      } else if (res?.data?.statusCode === 201) {
        toast({
          render: () => <ToastBox message={res?.data?.message} />,
        });

        onClose();
        setIsLoading(false);
        setFile(null);
        reset();
      }
    } catch (error) {
      console.log(error);
      if (error) {
        toast({
          render: () => (
            <ToastBox
              message={"Something went wrong please try again!"}
              status={"error"}
            />
          ),
        });
        onClose();
        setIsLoading(false);
        setFile(null);
        reset();
      }
    }

    setAlert(false);
  };

  const onSubmit = (data) => {
    console.log(data);
    // setValue('Type',data.Type[0]?.type)
    // const updatedCreate = create.map((item) =>
    //   item.id === id ? { ...item, ...data } : item
    // );
    // setCreate(updatedCreate);
    // onClose();

    console.log("sibmited");
    console.log(errors);
    if (Object.keys(errors).length === 0) {
      const formData = new FormData();
      formData.append("documentName", data.fileName);
      formData.append("documentNameArabic", data.documentNameArabic);
      typeof data?.document !== "string"
        ? formData.append("document", data?.document[0])
        : null;
      setFormData(formData);
      setAlert(true);
    }
  };

  const handleFileChange = (event) => {
    const selectedFile = event.target.files[0];
    setFile(selectedFile);
  };


  return (
    <Drawer
    size={"md"}
      isOpen={isOpen}
      placement="right"
      onClose={onClose}
      initialFocusRef={thirdField}
    >
      <DrawerContent>
        <DrawerCloseButton />
        <DrawerHeader fontSize={"md"}>Edit Document</DrawerHeader>
        <Box as="form" onSubmit={handleSubmit(onSubmit)}>
          <DrawerBody>
            <FormControl isRequired mb={4} isInvalid={errors.fileName}>
              <FormLabel fontSize="sm">File Name</FormLabel>
              <Input
                fontSize="sm"
                type="text"
                size="sm"
                {...register("fileName")}
              />
              {errors.fileName && (
                <Text color="red.500" fontSize="sm">
                  {errors.fileName.message}
                </Text>
              )}
            </FormControl>




            <FormControl mb={4} isRequired>
                <FormLabel fontSize="sm">File Name ( Arabic )</FormLabel>
                <Input
                  name="documentNameArabic"
                  {...register("documentNameArabic")}
                  fontSize="sm"
                  type="text"
                  size="sm"
                  textAlign={'right'}
                />
                {errors.documentNameArabic && (
                  <Text mt={1} fontSize="xs" fontWeight={500} color="red">
                    {errors.documentNameArabic.message}
                  </Text>
                )}
              </FormControl>
              
            <FormControl mb={4} isInvalid={errors.Type}>
              <FormLabel fontSize="sm">Document</FormLabel>
              <Input
                name="document"
                {...register("document")}
                fontSize="sm"
                className="form-control"
                type="file"
                size="sm"
                  accept=".pdf, .doc, .docx"
                onChange={handleFileChange}
              />
              {errors.document && (
                <Text color="red.500" fontSize="sm">
                  {errors.document.message}
                </Text>
              )}
            </FormControl>
            {filterObject !== null && file === null ? (
              <Box mt={4}>
                <Box display="flex" alignItems={"center"} mb={2}>
                  <Text as={"span"}>
                    {getFileIcon(filterObject?.documentType)}
                  </Text>
                  <Text
                    as={"span"}
                    fontSize="sm"
                    fontWeight={400}
                    ml={2}
                    mb={0}
                  >
                    {getFileNameFromPath(filterObject?.documentPath)}
                  </Text>
                </Box>
                {/* <Text fontSize="sm">{bytesToMB(file.size)}</Text> */}
              </Box>
            ) : (
              <Box mt={4}>
                <Box display="flex" mb={2}>
                  <Text>{getFileIcon(file.type)}</Text>
                  <Text fontSize="sm" ml={2} mb={0}>
                    {file.name}
                  </Text>
                </Box>
                <Text fontSize="sm">{bytesToMB(file.size)}</Text>
              </Box>
            )}
          </DrawerBody>
          <DrawerFooter>
            <Button
              variant="outline"
              colorScheme="forestGreen"
              rounded="sm"
              size="sm"
              mr={3}
              onClick={onClose}
            >
              Cancel
            </Button>
            <Button
              colorScheme="forestGreen"
              rounded="sm"
              size="sm"
              type="submit"
            >
              Save
            </Button>
          </DrawerFooter>
        </Box>
      </DrawerContent>

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

export default InvestmentEdit;
