import React, { Suspense } from 'react';
import type {
  GhostNote,
  NoteAuditTrail,
  ResearchDensityMode,
  WorkspaceProjection,
  WorkspaceViewKind,
} from '../../types/research';
import { CatalystRiskMap } from './views/CatalystRiskMap';
import { EvidenceTracePanel } from './views/EvidenceTracePanel';
import { MemoWorkbench } from './views/MemoWorkbench';
import { ModelWorkbench } from './views/ModelWorkbench';
import { ResearchCanvas } from './views/ResearchCanvas';
import { ResearchKanban } from './views/ResearchKanban';
import { ResearchTimeline } from './views/ResearchTimeline';
import { ThesisBoard } from './views/ThesisBoard';

const ResearchGraph = React.lazy(() =>
  import('./views/ResearchGraph').then((module) => ({ default: module.ResearchGraph })),
);

interface ResearchWorkbenchProps {
  projection: WorkspaceProjection | null;
  currentView: WorkspaceViewKind;
  density: ResearchDensityMode;
  selectedNoteIds: string[];
  selectedGhostId: string | null;
  visibleGhosts: GhostNote[];
  railGhosts: GhostNote[];
  memoDraft: string;
  memoPreview: boolean;
  auditTrail: NoteAuditTrail | null;
  isLoading: boolean;
  error?: string;
  emptyMessage: string;
  onSelectNote: (noteId: string) => void;
  onSelectGhost: (ghostId: string) => void;
  onMemoDraftChange: (value: string) => void;
  onToggleMemoPreview: () => void;
}

const ResearchEmptyState: React.FC<{ title: string; message: string }> = ({
  title,
  message,
}) => (
  <div className="rounded-[28px] border border-term-border bg-term-surface p-8 text-center">
    <h2 className="text-base font-semibold text-term-text">{title}</h2>
    <p className="mt-2 text-sm leading-6 text-term-text-muted">{message}</p>
  </div>
);

export const ResearchWorkbench: React.FC<ResearchWorkbenchProps> = ({
  projection,
  currentView,
  density,
  selectedNoteIds,
  selectedGhostId,
  visibleGhosts,
  railGhosts,
  memoDraft,
  memoPreview,
  auditTrail,
  isLoading,
  error,
  emptyMessage,
  onSelectNote,
  onSelectGhost,
  onMemoDraftChange,
  onToggleMemoPreview,
}) => {
  if (!projection) {
    if (isLoading) {
      return (
        <div className="rounded-[28px] border border-term-border bg-term-surface p-10 text-sm text-term-text-muted">
          Loading workspace snapshot...
        </div>
      );
    }

    if (error) {
      return (
        <div className="rounded-[28px] border border-negative/40 bg-negative/10 p-10 text-sm text-negative">
          {error}
        </div>
      );
    }

    return (
      <div className="rounded-[28px] border border-dashed border-term-border bg-term-surface p-10 text-center">
        <h2 className="text-xl font-semibold text-term-text">No research workspace selected</h2>
        <p className="mt-3 text-sm leading-7 text-term-text-muted">
          Create a workspace or open one from the rail to begin organizing research.
        </p>
      </div>
    );
  }

  const notes = projection.notes;
  const selectedNoteId = selectedNoteIds[0] ?? null;

  switch (currentView) {
    case 'canvas':
      return (
        <ResearchCanvas
          notes={notes}
          ghosts={railGhosts}
          density={density}
          selectedNoteIds={selectedNoteIds}
          selectedGhostId={selectedGhostId}
          onSelectNote={onSelectNote}
          onSelectGhost={onSelectGhost}
          emptyMessage={emptyMessage}
        />
      );
    case 'kanban':
      return projection.kanbanColumns.every((column) => column.notes.length === 0) ? (
        <ResearchEmptyState title="No notes visible" message={emptyMessage} />
      ) : (
        <ResearchKanban
          columns={projection.kanbanColumns}
          density={density}
          selectedNoteIds={selectedNoteIds}
          onSelectNote={onSelectNote}
        />
      );
    case 'graph':
      return projection.graphNodes.length === 0 ? (
        <ResearchEmptyState title="No graph nodes visible" message={emptyMessage} />
      ) : (
        <Suspense fallback={<div className="text-sm text-term-text-muted">Loading graph...</div>}>
          <ResearchGraph
            nodes={projection.graphNodes}
            edges={projection.graphEdges}
            selectedNodeId={selectedNoteId}
            onSelectNode={onSelectNote}
          />
        </Suspense>
      );
    case 'thesis_builder':
      return (
        <ThesisBoard
          notes={notes}
          ghosts={visibleGhosts}
          density={density}
          selectedNoteIds={selectedNoteIds}
          selectedGhostId={selectedGhostId}
          onSelectNote={onSelectNote}
          onSelectGhost={onSelectGhost}
        />
      );
    case 'memo_drafting':
      return (
        <MemoWorkbench
          memoBlocks={projection.memoBlocks}
          notes={notes.filter((note) =>
            ['quoted', 'corroborated', 'inferred'].includes(note.evidenceStatus),
          )}
          value={memoDraft}
          showPreview={memoPreview}
          onChange={onMemoDraftChange}
          onTogglePreview={onToggleMemoPreview}
        />
      );
    case 'evidence_trace':
      return <EvidenceTracePanel auditTrail={auditTrail} />;
    case 'catalyst_risk_map':
      return (
        <CatalystRiskMap
          notes={notes}
          ghosts={visibleGhosts}
          density={density}
          selectedNoteIds={selectedNoteIds}
          onSelectNote={onSelectNote}
          onSelectGhost={onSelectGhost}
        />
      );
    case 'timeline':
      return projection.timelineEvents.length === 0 ? (
        <ResearchEmptyState title="No timeline events visible" message={emptyMessage} />
      ) : (
        <ResearchTimeline
          events={projection.timelineEvents}
          notes={notes}
          onSelectNote={onSelectNote}
        />
      );
    case 'model':
      return <ModelWorkbench workspace={projection.workspace} notes={notes} />;
    default:
      return null;
  }
};
