import React, { useState } from 'react';
import { researchBridge } from '../../lib/researchBridge';
import { useResearchActions, researchActionKeys } from '../../research/researchActions';
import { useResearchFilesQuery, useResearchWorkspacesQuery } from '../../research/researchQueries';
import { getMutationStatus, useResearchUiStore } from '../../research/researchUiStore';
import { ResearchCaptureModal } from './ResearchCaptureModal';
import {
  openResearchFile,
  ResearchFilePreviewModal,
} from './primitives/ResearchFiles';
import type { ResearchFile } from '../../types/research';

export const ResearchCaptureModalController: React.FC = () => {
  const actions = useResearchActions();
  const [previewFile, setPreviewFile] = useState<ResearchFile | null>(null);
  const { data: workspaces = [] } = useResearchWorkspacesQuery();
  const captureModal = useResearchUiStore((state) => state.captureModal);
  const { data: workspaceFiles = [] } = useResearchFilesQuery(
    captureModal.draft.workspaceId || null,
  );
  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;
      }}
      workspaceFiles={workspaceFiles}
      onUploadFiles={(files) => actions.uploadFiles(captureModal.draft.workspaceId, files)}
      onOpenFile={(file) => openResearchFile(file)}
      onPreviewFile={setPreviewFile}
      onSubmit={() => {
        void actions.captureNote({
          draft: captureModal.draft,
          explicitWorkspaceId: captureModal.draft.workspaceId || undefined,
          fallbackTicker: captureModal.draft.ticker || undefined,
          autoCreateFromTicker: Boolean(captureModal.draft.ticker.trim()),
        });
      }}
      />
      <ResearchFilePreviewModal file={previewFile} onClose={() => setPreviewFile(null)} />
    </>
  );
};
