<reponame>debel27/react-form<gh_stars>0
// @flow
import * as React from "react";
import { TopBar } from "./TopBar";
import { FormPanel } from "./FormPanel";
import type { DevToolsDataType } from "../../src/devtools-integration";
import "./DevTools.css";

type DevToolsPropsType = {|
  data: DevToolsDataType | null
|};

export function DevTools(props: DevToolsPropsType): React.Node {
  const { data } = props;
  if (!data) {
    return (
      <div className="devTools notConnected">
        This page doesn't use react-form
      </div>
    );
  }
  return <DevToolsInternal data={data} />;
}

function DevToolsInternal(props: {| data: DevToolsDataType |}) {
  const { data } = props;
  const [selectedFormId, setSelectedFormId] = React.useState(
    Object.keys(data)[0] || null
  );

  React.useEffect(() => {
    const keys = Object.keys(data);
    if (
      (!selectedFormId || !keys.includes(selectedFormId)) &&
      keys.length > 0
    ) {
      setSelectedFormId(keys.sort()[0]);
    }
  }, [selectedFormId, data]);

  return (
    <div className="devTools">
      <TopBar
        data={data}
        selectedFormId={selectedFormId}
        onSelectedFormIdChange={setSelectedFormId}
      />
      <FormPanel data={data} formId={selectedFormId} />
    </div>
  );
}
