import {
  Box,
  Button,
  Drawer,
  DrawerBody,
  DrawerCloseButton,
  DrawerContent,
  DrawerFooter,
  DrawerHeader,
  DrawerOverlay,
  FormControl,
  FormHelperText,
  FormLabel,
  Input,
  Text,
  useToast,
} from "@chakra-ui/react";
import * as yup from "yup";
import React, { useContext, useState } from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import CustomAlertDialog from "../../Components/CustomAlertDialog";
import { v4 as uuidv4 } from "uuid";
import { useNavigate, useParams } from "react-router-dom";
import { GrDocumentPdf } from "react-icons/gr";
import { FaRegFileAlt } from "react-icons/fa";
import { TbFileTypeDocx } from "react-icons/tb";
import { AiOutlineFileGif } from "react-icons/ai";
import GlobalStateContext from "../../Contexts/GlobalStateContext";
import InvestmentDocument from "./CreateIO/InvestmentDocument";
import { useCreateInvestmentDocumentsMutation } from "../../Services/io.service";
import ToastBox from "../../Components/ToastBox";

export const bytesToMB = (bytes) => {
  if (bytes === 0) return "0 MB";
  const bytesInMB = 1024 * 1024;
  return (bytes / bytesInMB).toFixed(2) + " MB";
};

export const getFileIcon = (type) => {
  switch (type) {
    case "application/pdf":
      return <GrDocumentPdf />;
    case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
    case "application/msword":
      return <TbFileTypeDocx fontSize={"20px"} />;
    case "image/jpeg":
    case "image/png":
    case "image/gif":
      return <AiOutlineFileGif fontSize={25} />;
    default:
      return <FaRegFileAlt />;
  }
};

export const investmentDocSchema = yup.object().shape({
  document: yup.mixed().required("Document is required"),
  // .test("fileSize", "File size should be less than 2MB", value => {
  //   console.log("File size:", value ? value.size : "No file");
  //   return value && value.size <= 2 * 1024 * 1024; // 2MB in bytes
  // })
  fileName: yup.string().required("File name is required"),
  documentNameArabic: yup.string().required("File name Arabic is required")
});

const InvestmentDocuments = ({
  isOpen,
  onClose,
  firstField,
  create,
  setCreate,
}) => {
  const toast = useToast();
  const params = useParams();

  const [file, setFile] = useState(null);
  const [alert, setAlert] = useState(false);
  const [formData, setFormData] = useState(null);
  const [isLoading, setIsLoading] = useState(false);

  // =====================[ variables ]
  const id = params?.id;

  // =====================[ RTK Api calls ]
  const [createInvestmentDocument] = useCreateInvestmentDocumentsMutation();

  const navigate = useNavigate();

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

  const onSubmit = async (data) => {
    if (Object.keys(errors).length === 0) {
      const formData = new FormData();
      formData.append("documentName", data.fileName);
      formData.append("documentNameArabic", data.documentNameArabic);
      formData.append("document", data?.document[0]);
      setFormData(formData);
      setAlert(true);
    }
  };

  const handleConfirm = async () => {
    setIsLoading(true);
    try {
      const res = await createInvestmentDocument({ data: formData, id });

      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"}
            />
          ),
        });
        console.log(error);
        onClose();
        setIsLoading(false);
        setFile(null);
        reset();
      }
    }

    setAlert(false);
  };

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

  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 handleClose = () => {
    onClose();
    setAlert(false);
    reset();
    setFile(null);
  };

  return (
    <>
      <Drawer
      size={"md"}
        isOpen={isOpen}
        placement="right"
        initialFocusRef={firstField}
        onClose={onClose}
      >
        <DrawerOverlay />
        <DrawerContent>
          <DrawerCloseButton />
          <DrawerHeader fontSize="sm">Add Details</DrawerHeader>
          <Box as="form" onSubmit={handleSubmit(onSubmit)}>
            <DrawerBody>
              <FormControl mb={4} isRequired>
                <FormLabel fontSize="sm">File Name</FormLabel>
                <Input
                  name="fileName"
                  {...register("fileName")}
                  fontSize="sm"
                  type="text"
                  size="sm"
                />
                {errors.fileName && (
                  <Text mt={1} fontSize="xs" fontWeight={500} color="red">
                    {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} isRequired>
                <FormLabel fontSize="sm">Document</FormLabel>
                <Input
                  name="document"
                  {...register("document")}
                  fontSize="sm"
                  className="form-control"
                  type="file"
                  size="sm"
                  onChange={handleFileChange}
                  accept=".pdf, .doc, .docx"
                />
                {errors.document && (
                  <Text mt={1} fontSize="xs" fontWeight={500} color="red">
                    {errors.document.message}
                  </Text>
                )}

              <FormHelperText mt={1} fontSize="xs" fontWeight={500} color="gray.500">File size should be max 2mb</FormHelperText>
              </FormControl>
              {file && (
                <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={handleClose}
              >
                Cancel
              </Button>
              <Button
                colorScheme="forestGreen"
                rounded="sm"
                size="sm"
                type="submit"
              >
                Save
              </Button>
            </DrawerFooter>
          </Box>
        </DrawerContent>
      </Drawer>
      <CustomAlertDialog
        isOpen={alert}
        onClose={() => setAlert(false)}
        alertHandler={handleConfirm}
        isLoading={isLoading}
        message="Are you sure you want to add this document?"
      />
    </>
  );
};

export default InvestmentDocuments;
