import React from 'react';
import { researchBridge } from '../../lib/researchBridge';
import { useResearchActions, researchActionKeys } from '../../research/researchActions';
import { useResearchWorkspacesQuery } from '../../research/researchQueries';
import { getMutationStatus, useResearchUiStore } from '../../research/researchUiStore';
import { ResearchCaptureModal } from './ResearchCaptureModal';

export const ResearchCaptureModalController: React.FC = () => {
  const actions = useResearchActions();
  const { data: workspaces = [] } = useResearchWorkspacesQuery();
  const captureModal = useResearchUiStore((state) => state.captureModal);
  const mutationStateByKey = useResearchUiStore((state) => state.mutationStateByKey);
  const closeCaptureModal = useResearchUiStore((state) => state.closeCaptureModal);
  const updateCaptureDraft = useResearchUiStore((state) => state.updateCaptureDraft);
  const captureStatus = getMutationStatus(
    mutationStateByKey,
    researchActionKeys.captureNote,
  );

  return (
    <ResearchCaptureModal
      isOpen={captureModal.isOpen}
      draft={captureModal.draft}
      workspaces={workspaces}
      contextLabel={captureModal.contextLabel}
      isSubmitting={captureStatus.pending}
      error={captureStatus.error}
      onClose={closeCaptureModal}
      onDraftChange={updateCaptureDraft}
      onPreviewLink={async (url, kind) => {
        const result = await researchBridge.previewNoteLink({ url, kind });
        return result.embed;
      }}
      onSubmit={() => {
        void actions.captureNote({
          draft: captureModal.draft,
          explicitWorkspaceId: captureModal.draft.workspaceId || undefined,
          fallbackTicker: captureModal.draft.ticker || undefined,
          autoCreateFromTicker: Boolean(captureModal.draft.ticker.trim()),
        });
      }}
    />
  );
};
