import React, { useEffect, useRef, useState } from "react";
import style from "./uploadFile.module.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faCloudArrowUp } from "@fortawesome/free-solid-svg-icons";
import { faFile } from "@fortawesome/free-regular-svg-icons";
import {
  DeleteForeverOutlined,
  RemoveCircleOutline,
} from "@mui/icons-material";
import Image from "next/image";

const UploadFile = (props) => {
  const inputFile = useRef();
  const [file, setFile] = useState(props.multiple === true ? [] : {});
  const [latestFile, setLatestFile] = useState({ data: "", deleted: [] });
  const [deleted, setDeleted] = useState([]);
  const [error, setError] = useState();
  const fileUpload = (data) => {
    if (data) {
      if (props.limit) {
        if (props.limit < data.files.length + file.length) {
          setError(`Only ${props.limit} Files Allowed`);
          return 0;
        }
      }
      if (data.files.length > 0) {
        if (props.multiple === true) {
          for (const item of data.files) {
            const fileType = item.type.split("/")[1];
            const fileSize = parseInt(item.size / 1024).toFixed(0);
            console.log("fileSize", fileSize);
            if (props.maxSize && fileSize > Number(props.maxSize)) {
              setError(`File size exeeded, Max: ${props.maxSize}kb`);
              return 0;
            } else if (
              props.allowedType &&
              !props.allowedType.includes("." + fileType)
            ) {
              setError(
                `File type invalid, Valid: ${props.allowedType.toString()}`
              );
              return 0;
            } else setError();
          }
          let multipleData = [...file];
          for (const item of data.files) {
            let newFile = new File(
              [item],
              `${(Math.random() + 1).toString(36).substring(7)}_${item.name}`,
              {
                type: item.type,
              }
            );
            multipleData.push({
              name: newFile.name,
              type: newFile.type.split("/")[1],
              size: parseInt(newFile.size / 1024).toFixed(0),
              url: URL.createObjectURL(newFile),
              data: newFile,
            });
          }
          setFile(multipleData);
          setLatestFile({
            data: multipleData,
            deleted: deleted,
            files: data.files,
          });
        } else {
          let newFile = new File(
            [data.files[0]],
            `${(Math.random() + 1).toString(36).substring(7)}_${
              data.files[0].name
            }`,
            {
              type: data.files[0].type,
            }
          );
          const fileType = newFile.type.split("/")[1];
          const fileSize = parseInt(newFile.size / 1024).toFixed(0);
          console.log("fileSize", fileSize);
          const fileName = newFile.name;
          if (props.maxSize && fileSize > Number(props.maxSize)) {
            setError(`File size exeeded, Max: ${props.maxSize}kb`);
            return 0;
          } else if (
            props.allowedType &&
            !props.allowedType.includes("." + fileType)
          ) {
            setError(
              `File type invalid, Valid: ${props.allowedType.toString()}`
            );
            return 0;
          } else setError();
          const url = URL.createObjectURL(newFile);
          setFile({
            name: fileName,
            type: fileType,
            size: fileSize,
            url: url,
            data: newFile,
          });
          setLatestFile({
            data: {
              name: fileName,
              type: fileType,
              size: fileSize,
              url: url,
              data: newFile,
            },
            deleted: deleted,
            files: newFile,
          });
        }
      }
    }
    inputFile.current.value = "";
  };

  const onDeleteMultipleImage = (index) => {
    let newDelete = [...deleted];
    if (!newDelete.includes(file[index].name)) {
      newDelete.push(file[index].name);
      setDeleted(newDelete);
    }
    let data = [];
    setFile((prev) => {
      let newArray = [...prev];
      newArray.splice(index, 1);
      data = newArray;
      return newArray;
    });
    setLatestFile((prev) => {
      let newObject = { ...prev };
      newObject.data = data;
      newObject.deleted = newDelete;
      return newObject;
    });
  };

  const onResetUpload = (name) => {
    let newDelete = [...deleted];
    newDelete.push(name);
    setDeleted(newDelete);
    inputFile.current.value = "";
    setFile("deleted");
    setLatestFile({ data: "deleted", deleted: newDelete });
  };
  useEffect(() => {
    console.log("props.setData: ", props.setData());
    const data = props.setData();
    if (props.multiple) {
      if (data.length > 0) {
        setFile(props.setData);
      } else {
        setFile([]);
      }
    } else {
      if (props.setData()) {
        setFile(data);
      }
    }
  }, [props.setData]);

  useEffect(() => {
    console.log("file: ", file);
  }, [file]);
  useEffect(() => {
    console.log("latestFile", latestFile);
    props.getData(latestFile);
  }, [latestFile]);
  return (
    <React.Fragment>
      <div
        className={`${style.upload_file_section} ${
          props.error ? style.error : ""
        } ${props.flexDirection === "row" ? style.row_flex : ""}`}
      >
        <div
          className={`${style.uploadFile} ${
            props.customCss ? props.customCss : ""
          }`}
        >
          <input
            type="file"
            className={style.uploadInput}
            ref={inputFile}
            onInput={() => fileUpload(inputFile.current)}
            multiple={props.multiple}
            accept={props.allowedType.join(",")}
          />
          <div className={style.uploadBox}>
            {file &&
            !props.multiple &&
            [".jpeg", ".jpg", ".png", ".webp"].includes("." + file.type) ? (
              <Image
                src={file.url}
                alt="Not Image"
                className={style.image}
                fill
              />
            ) : (Object.keys(file).length === 0 || props.multiple) && !error ? (
              <div className={style.text}>
                <FontAwesomeIcon icon={faCloudArrowUp} />
                <br /> Drag & drop a file here or click
              </div>
            ) : (
              !props.multiple &&
              !error && (
                <div className={style.otherFile}>
                  <FontAwesomeIcon icon={faFile} />
                  <br /> Type: {file.type}
                  <br /> Size: {file.size} KB
                </div>
              )
            )}
            {!props.multiple && Object.keys(file).length > 0 && (
              <div className={style.overlayDelete}>
                <button
                  type="button"
                  className="primary_btn_no_animation"
                  onClick={() => onResetUpload(file.name)}
                >
                  Delete
                </button>
              </div>
            )}

            {error && <div className={style.errorText}>{error}</div>}
          </div>
        </div>
        {props.multiple && file && file.length > 0 && (
          <div
            className={`${style.multple_image} ${
              props.flexDirection === "row" ? style.width_100 : ""
            } `}
          >
            {file.map((item, index) => (
              <div className={style.item_section} key={item.url}>
                <Image
                  src={item.url}
                  alt="Not Available"
                  className={style.image}
                  fill
                />
                <div
                  className={style.delete_btn}
                  onClick={() => onDeleteMultipleImage(index)}
                >
                  <RemoveCircleOutline />
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </React.Fragment>
  );
};

export default UploadFile;
