import {
  Box,
  Button,
  Drawer,
  DrawerBody,
  DrawerCloseButton,
  DrawerContent,
  DrawerFooter,
  DrawerHeader,
  DrawerOverlay,
  FormControl,
  FormLabel,
  Input,
  Text,
} 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 } 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";

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

export const investmentDocSchema = yup.object().shape({
  document: yup.mixed().required("Document is required"),
  fileName: yup.string().required("File name is required"),
});

const InvestmentDocuments = ({ id, isOpen, onClose, firstField, create, setCreate }) => {
  const [file, setFile] = useState(null);
  const [alert, setAlert] = useState(false);

  const navigate = useNavigate();

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

  // const onSubmit = (data) => {
  //   console.log(data);
  //   setFile(data.document[0]);
  //   // Additional code for handling form submission
  // };

  const onSubmit = (data) => {
    console.log(data);
    setFile(data.document[0]);

    const newDocument = {
      ...data,
      document: data.document[0].name, // Store the document name
      status: true,
      id: uuidv4(),
      createdAt: new Date().toISOString(),
      Type:getFileIcon(file.type)
    };

    setCreate((prevCreate) => [...prevCreate, newDocument]);
    navigate(" ");
  };

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

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

  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";
    }
  };

  return (
    <>
      <Drawer
        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}>
                <FormLabel fontSize="sm">File Name</FormLabel>
                <Input
                  name="fileName"
                  {...register("fileName")}
                  fontSize="sm"
                  type="text"
                  size="sm"
                />
                {errors.fileName && (
                  <Text fontSize="sm" color="red">
                    {errors.fileName.message}
                  </Text>
                )}
              </FormControl>
              <FormControl mb={4}>
                <FormLabel fontSize="sm">Document</FormLabel>
                <Input
                  name="document"
                  {...register("document")}
                  fontSize="sm"
                   className="form-control"
                  type="file"
                  size="sm"
                  onChange={handleFileChange}
                />
                {errors.document && (
                  <Text fontSize="sm" color="red">
                    {errors.document.message}
                  </Text>
                )}
              </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="green"
                rounded="sm"
                size="sm"
                mr={3}
                onClick={onClose}
              >
                Cancel
              </Button>
              <Button
                colorScheme="green"
                rounded="sm"
                size="sm"
                type="submit"
                onClick={onSubmit}
              >
                Save
              </Button>
            </DrawerFooter>
          </Box>
        </DrawerContent>
      </Drawer>
      <CustomAlertDialog
        isOpen={alert}
        onClose={() => setAlert(false)}
        message="Are you sure you want to add this document?"
      />
    </>
  );
};

export default InvestmentDocuments;
