import React, { useState, useMemo, useEffect } from "react";
import PageTitle from "../../../../components/PageTitle";
import { useParams } from "react-router-dom";
import { useResourcesApi, useDictionariesApi } from "../../api";
import { LoadingText } from "../../../../components";
import ResourceComponent from "./ResourceComponent";
import { makeStyles } from "@material-ui/core/styles";
import style from "../styles";

const useStyles = makeStyles(style);

const ResourceContainer = () => {
  const [state, setState] = useState(null);
  const [loading, setLoading] = useState(false);
  const [mimeTypes, setMimeTypes] = useState(null);
  const [resourceCategories, setResourceCategories] = useState(null);
  const [processing, setProcessing] = useState(null);

  const classes = useStyles();
  const params = useParams();
  const { getResource } = useResourcesApi();
  const { getMimeTypes, getResourceCategories } = useDictionariesApi();

  const isNew = useMemo(() => params.id === "new", [params.id]);

  useEffect(() => {
    getMimeTypes().then((r) => setMimeTypes(r));
  }, [getMimeTypes]);

  useEffect(() => {
    getResourceCategories().then((r) => setResourceCategories(r));
  }, [getResourceCategories]);

  useEffect(() => {
    if (isNew) return;
    const resourceId = parseInt(params.id);
    setLoading(true);
    getResource(resourceId).then((resource) => {
      setState(resource);
      setLoading(false);
    });
  }, [getResource, isNew, params.id]);

  const handlePropertyChange = (prop) => (value) => {
    setState((prev) => ({ ...prev, [prop]: value }));
  };

  if (loading || !state || !mimeTypes || !resourceCategories)
    return <LoadingText lines={15} onPaper />;

  return (
    <>
      <PageTitle title={state.resourceName} />
      <div className={classes.root}>
        <ResourceComponent
          resource={state}
          mimeTypes={mimeTypes}
          resourceCategories={resourceCategories}
          onPropertyChange={handlePropertyChange}
          processing={processing}
          setProcessing={setProcessing}
        />
      </div>
    </>
  );
};

export default ResourceContainer;
