import React, { useEffect, useState } from "react";
import { IFile } from "./interface";
import { QueryClient, QueryClientProvider } from "react-query";
import FileManager from "./components/fileManager";
import { setValue } from "./configSrore";
import './styles.css';

interface IProps {
    userToken: string;
    userGroupHash: string;
    podspaceUrl: string;
    clasorUrl: string;
    resourceId?: number;
    onRefresh?: () => Promise<string | undefined>;
    onError?: (err: any) => void;
    onSelectItem?: (fileItem: IFile) => void;
}

export const queryClient = new QueryClient();

const ClasorFileManager = (props: IProps) => {
  const {
    userToken,
    userGroupHash,
    podspaceUrl,
    clasorUrl,
    resourceId,
    onRefresh,
    onError,
    onSelectItem,
  } = props;

  const [loading, setLoading] = useState(false);

  const [error, setError] = useState("");

  const setInitialValues = () => {
    setValue("userToken", userToken);
    setValue("userGroupHash", userGroupHash);
    setValue("podspaceUrl", podspaceUrl);
    setValue("clasorUrl", clasorUrl);

    if (resourceId && typeof resourceId !== "number") {
      setError("resourceId should be a number");
    } else if (resourceId) {
      setValue("resourceId", resourceId);
    }

    if (onRefresh && typeof onRefresh !== "function") {
      setError("onRefresh should be a function");
    } else if (onRefresh) {
      setValue("onRefresh", onRefresh);
    }

    if (onError && typeof onError !== "function") {
      setError("onError should be a function");
    } else if (onError) {
      setValue("onError", onError);
    }

    if (onSelectItem && typeof onSelectItem !== "function") {
      setError("onSelectItem should be a function");
    } else if (onSelectItem) {
      setValue("onSelectItem", onSelectItem);
    }

    setLoading(false);
  };

  useEffect(() => {
    setLoading(true);
    if (userToken && userGroupHash && podspaceUrl && clasorUrl) {
      setInitialValues();
    }
  }, [userGroupHash]);

  if (error) {
    return <h1 className="bg-red-500">{error}</h1>;
  }

  if (!userToken || !userGroupHash || !podspaceUrl || !clasorUrl) {
    return (
      <h1 className="bg-red-500">
        required props are missing
        <b>(userToken , userGroupHash , podspaceUrl, clasorUrl)</b>
      </h1>
    );
  }

  if (loading) {
    return null;
  }

  return (
    <QueryClientProvider client={queryClient}>
      <FileManager />
    </QueryClientProvider>
  );
};

export default ClasorFileManager;
