import React from 'react';
import { useResearchActions, researchActionKeys } from '../../research/researchActions';
import { getMutationStatus, useResearchUiStore } from '../../research/researchUiStore';
import { CreateWorkspaceModal } from './CreateWorkspaceModal';

export const CreateWorkspaceModalController: React.FC = () => {
  const actions = useResearchActions();
  const createWorkspaceModal = useResearchUiStore((state) => state.createWorkspaceModal);
  const closeCreateWorkspaceModal = useResearchUiStore(
    (state) => state.closeCreateWorkspaceModal,
  );
  const setCreateWorkspaceTickerDraft = useResearchUiStore(
    (state) => state.setCreateWorkspaceTickerDraft,
  );
  const mutationStateByKey = useResearchUiStore((state) => state.mutationStateByKey);
  const createStatus = getMutationStatus(
    mutationStateByKey,
    researchActionKeys.createWorkspace,
  );

  return (
    <CreateWorkspaceModal
      isOpen={createWorkspaceModal.isOpen}
      tickerDraft={createWorkspaceModal.tickerDraft}
      isSubmitting={createStatus.pending}
      error={createStatus.error}
      onClose={closeCreateWorkspaceModal}
      onTickerChange={setCreateWorkspaceTickerDraft}
      onSubmit={() => {
        if (!createWorkspaceModal.tickerDraft.trim()) {
          return;
        }
        void actions.createWorkspace(createWorkspaceModal.tickerDraft);
      }}
    />
  );
};
