import React, { useState } from "react";
import axios from "axios";
import useShareFileHash from "../hooks/useShareFileHash";
import { configSrore } from "../configSrore";
import { UploadFileIcon } from "../svg";

interface IProps{
    userGroupHash: string;
    page: number;
    refetch: () => void;
}

const UploadFile = ({ userGroupHash, page, refetch }: IProps) => {
  const [processCount, setProcessCount] = useState(0);
  //   const [sizeError, setSizeError] = useState<boolean>(false);

  const { mutate } = useShareFileHash();

  const onSuccess = (fileHash: string, hash?: string) => {
    try {
      mutate({
        page,
        fileHash,
        userGroupHash: hash || "",
        callBack: () => {
          refetch();
          setProcessCount(0);
        },
      });

      return true;
    } catch {
      return false;
    }
  };

  const onUploadClick = async (e: any) => {
    await configSrore.onRefresh?.();
    e.preventDefault();
    const file = e.target.files?.[0];
    if (!file) {
      return;
    }
    const formData = new FormData();
    formData.append("file", e.target.files[0]);
    axios
      .post(
        `${configSrore.podspaceUrl}usergroups/${configSrore.userGroupHash}/files`,
        formData,
        {
          headers: {
            "Content-Type":
                  "multipart/form-data;",
            Authorization: `Bearer ${configSrore.userToken}`,
            _token_: configSrore.userToken || "",
            _token_issuer_: "1",
          },
          onUploadProgress(progressEvent: any) {
            const process = Math.round(
              (progressEvent.loaded * 100) / progressEvent.total,
            );
            setProcessCount(process);
          },
        },
      )
      .then(async (res: any) => {
        if (res.data.result?.hash) {
          onSuccess(res.data.result.hash, userGroupHash);
        }
      });
  };

  return (
    <>
      <form method="POST" encType="multipart/form-data" action="/">
        <label
          htmlFor={`file-upload-${userGroupHash}`}
          className="btn bg-primary hover:bg-primary"
        >
          <i className="fa fa-cloud-upload" />
          <UploadFileIcon className="h-4 w-4 fill-white ml-2" />
          بارگذاری فایل
        </label>
        <input
          id={`file-upload-${userGroupHash}`}
          type="file"
          onChange={(e) => {
            onUploadClick(e);
          }}
        />
      </form>
      {
        processCount > 0
          ? (
            <div className="progressBar">
              <div className="flex items-center">
                <progress
                  className="progress progress-accent w-56"
                  value={processCount}
                  max="100"
                />
                <span className="ml-2">
                  {processCount}
                  %
                </span>
                {processCount === 100 && (
                <span className="ml-2 color-emerald-200">آپلود موفق</span>
                )}
              </div>
            </div>
          )
          : null
      }

    </>
  );
};

export default UploadFile;
