/*
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */
import PropTypes from 'prop-types';
import { useCallback, useState, useRef } from 'react';

/**
 * Internal dependencies
 */
import { useAPI } from '../../app/api';
import useResizeEffect from '../../utils/useResizeEffect';
import Context from './context';

const DESIGN = 'design';
const DOCUMENT = 'document';
const PREPUBLISH = 'prepublish';

function InspectorProvider({ children }) {
  const {
    actions: { getAllStatuses, getAllUsers },
  } = useAPI();
  const [tab, setTab] = useState(DESIGN);
  const [users, setUsers] = useState([]);
  const [statuses, setStatuses] = useState([]);
  const [inspectorContentHeight, setInspectorContentHeight] = useState(null);
  const inspectorContentRef = useRef();

  const [isUsersLoading, setIsUsersLoading] = useState(false);
  const [isStatusesLoading, setIsStatusesLoading] = useState(false);

  const setInspectorContentNode = useCallback((node) => {
    inspectorContentRef.current = node;
  }, []);

  useResizeEffect(inspectorContentRef, ({ height }) =>
    setInspectorContentHeight(height)
  );

  const loadStatuses = useCallback(() => {
    if (!isStatusesLoading && statuses.length === 0) {
      setIsStatusesLoading(true);
      getAllStatuses()
        .then((data) => {
          data = Object.values(data);
          data = data.filter(({ show_in_list: isShown }) => isShown);
          const saveData = data.map(({ slug, name }) => ({
            value: slug,
            name,
          }));
          setStatuses(saveData);
        })
        .finally(() => {
          setIsStatusesLoading(false);
        });
    }
  }, [isStatusesLoading, statuses.length, getAllStatuses]);

  const loadUsers = useCallback(() => {
    if (!isUsersLoading && users.length === 0) {
      setIsUsersLoading(true);
      getAllUsers()
        .then((data) => {
          const saveData = data.map(({ id, name }) => ({
            value: id,
            name,
          }));

          setUsers(saveData);
        })
        .finally(() => {
          setIsUsersLoading(false);
        });
    }
  }, [isUsersLoading, users.length, getAllUsers]);

  const state = {
    state: {
      tab,
      users,
      statuses,
      inspectorContentHeight,
    },
    actions: {
      setTab,
      loadStatuses,
      loadUsers,
      setInspectorContentNode,
    },
    data: {
      tabs: {
        DESIGN,
        DOCUMENT,
        PREPUBLISH,
      },
    },
  };

  return <Context.Provider value={state}>{children}</Context.Provider>;
}

InspectorProvider.propTypes = {
  children: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.node),
    PropTypes.node,
  ]).isRequired,
};

export default InspectorProvider;

@@ -696,16 +696,27 @@
 , useRef
+, useEffect
  %7D from 
@@ -724,16 +724,16 @@
 react';%0A
-
 %0A/**%0A * 
@@ -857,16 +857,60 @@
 ffect';%0A
+import %7B useStory %7D from '../../app/story';%0A
 import C
@@ -1138,16 +1138,93 @@
 eAPI();%0A
+  const %7B%0A    state: %7B selectedElementIds, currentPage %7D,%0A  %7D = useStory();%0A%0A
   const 
@@ -1464,16 +1464,46 @@
 seRef();
+%0A  const tabRef = useRef(tab);
 %0A%0A  cons
@@ -1835,14 +1835,332 @@
 ht)%0A
-
   );%0A%0A
+  useEffect(() =%3E %7B%0A    tabRef.current = tab;%0A  %7D, %5Btab%5D);%0A%0A  useEffect(() =%3E %7B%0A    if (selectedElementIds.length %3E 0 && tabRef.current === DOCUMENT) %7B%0A      setTab(DESIGN);%0A    %7D%0A  %7D, %5BselectedElementIds%5D);%0A%0A  useEffect(() =%3E %7B%0A    if (tabRef.current === DOCUMENT) %7B%0A      setTab(DESIGN);%0A    %7D%0A  %7D, %5BcurrentPage%5D);%0A%0A
   co

Switch tab to design when selection is changing (#809)