import React from "react";
import { GlobalContext, showToast } from "Src/globalContext";

const SimpleFileUpload = ({
  label,
  maxFileSize = 5,
  setFormData,
  uploadedFilesProgressData = {},
}) => {
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const fileRef = React.useRef(null);
  const [fileValues, setFileValues] = React.useState([]);
  const [maxFileSizeStr, setMaxFileSizeStr] = React.useState(
    `${maxFileSize}MB`
  );

  const convertMBToGB = (mb) => {
    return {
      value: mb / 1024,
      unit: "GB",
    };
  };

  const saveFiles = (e) => {
    const files = e.target.files;
    if (files.length > 0) {
      setFileValues([...fileValues, ...files]);
    }
  };

  const validateFileSize = (file) => {
    const fileSize = file.size / 1024 / 1024; // in MB
    if (fileSize > maxFileSize) {
      showToast(
        globalDispatch,
        `File size exceeds ${maxFileSize}MB. Please upload a smaller file.`,
        5000,
        "error"
      );
      return false;
    }
    return true;
  };

  const uploadFiles = async (e) => {
    if (!fileValues || fileValues.length === 0) {
      showToast(globalDispatch, "No file selected", 5000, "error");
      return;
    }

    if (!validateFileSize(fileValues)) return;

    fileRef.current.value = "";
    const formData = new FormData();
    fileValues.forEach((file) => {
      if (!validateFileSize(file)) return;
      formData.append("files", file);
    });

    setFormData(formData);
  };

  React.useEffect(() => {
    if (maxFileSize > 1024) {
      const { value, unit } = convertMBToGB(maxFileSize);
      setMaxFileSizeStr(`${value}${unit}`);
    }
  }, [maxFileSize]);

  return (
    <div className="w-full max-w-xl space-y-3">
      {/* File Upload Section */}
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
        <div className="relative flex-1">
          <input
            ref={fileRef}
            className="w-full cursor-pointer rounded-lg border-2 border-dashed border-strokedark bg-boxdark-2 px-4 py-2.5 text-sm font-medium text-bodydark outline-none transition hover:border-primary"
            type="file"
            accept="*/*"
            onChange={saveFiles}
            multiple
            placeholder={`Upload ${label}`}
          />
        </div>

        {/* Upload Button */}
        <button
          className="inline-flex items-center justify-center rounded-md bg-primary px-6 py-2.5 text-center text-sm font-medium text-white hover:bg-opacity-90 disabled:cursor-not-allowed disabled:bg-opacity-50"
          onClick={uploadFiles}
          disabled={uploadedFilesProgressData?.isUploading}
        >
          {uploadedFilesProgressData?.isUploading ? (
            <>
              <svg className="mr-2 h-4 w-4 animate-spin" viewBox="0 0 24 24">
                <circle
                  className="opacity-25"
                  cx="12"
                  cy="12"
                  r="10"
                  stroke="currentColor"
                  strokeWidth="4"
                  fill="none"
                />
                <path
                  className="opacity-75"
                  fill="currentColor"
                  d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                />
              </svg>
              Uploading...
            </>
          ) : (
            "Upload"
          )}
        </button>
      </div>

      {/* File Info and Progress Section */}
      <div className="flex flex-col gap-2">
        <p className="text-xs text-bodydark2">
          Max file size: {maxFileSizeStr}
        </p>

        {uploadedFilesProgressData?.isUploading && (
          <div className="space-y-2">
            <div className="h-2 w-full overflow-hidden rounded-full bg-boxdark-2">
              <div
                className="h-full rounded-full bg-primary transition-all duration-300"
                style={{ width: `${uploadedFilesProgressData?.progress}%` }}
              />
            </div>
            <p className="text-xs text-bodydark">
              {uploadedFilesProgressData?.progress}% uploaded
            </p>
            {uploadedFilesProgressData?.error && (
              <p className="text-xs text-danger">
                {uploadedFilesProgressData.error}
              </p>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

export default SimpleFileUpload;
