import React from 'react';
import type { MemoBlockCandidate, ResearchNote } from '../../../types/research';
import { MarkdownPreview } from '../primitives/MarkdownPreview';
import { MemoOutlineRail } from '../primitives/MemoOutlineRail';
import { EvidenceDrawer } from '../primitives/EvidenceDrawer';
import { ResearchEditor } from '../primitives/ResearchEditor';
import { htmlToPlainText } from '../../../lib/htmlUtils';

interface MemoWorkbenchProps {
  memoBlocks: MemoBlockCandidate[];
  notes: ResearchNote[];
  value: string;
  showPreview: boolean;
  onChange: (value: string) => void;
  onTogglePreview: () => void;
}

export const MemoWorkbench: React.FC<MemoWorkbenchProps> = ({
  memoBlocks,
  notes,
  value,
  showPreview,
  onChange,
  onTogglePreview,
}) => {
  const insertMemoBlock = (block: MemoBlockCandidate) => {
    const sectionLabel = block.sectionKind.replace(/_/g, ' ');
    onChange(`${value}\n\n## ${block.headline}\n> Section: ${sectionLabel}\n\n${block.body}\n`);
  };

  const insertCitation = (note: ResearchNote) => {
    onChange(`${value} [${note.title || note.noteType}:${note.id}]`);
  };

  const handleEditorChange = (html: string) => {
    onChange(html);
  };

  return (
    <div className="grid gap-4 xl:grid-cols-[280px_minmax(0,1fr)_320px]">
      <MemoOutlineRail blocks={memoBlocks} onInsertBlock={insertMemoBlock} />
      <div className="space-y-4">
        <div className="flex items-center justify-end gap-3">
          <button
            type="button"
            onClick={onTogglePreview}
            className="border border-term-border bg-term-bg px-3 py-2 text-xs uppercase tracking-[0.18em] text-term-text-tertiary transition-colors hover:border-info/60 hover:text-term-text"
          >
            {showPreview ? 'Hide preview' : 'Show preview'}
          </button>
        </div>
        <ResearchEditor
          content={value}
          onChange={handleEditorChange}
          placeholder="Write your stock pitch, memo section, catalyst calendar, or earnings recap..."
          minRows={18}
        />
        {showPreview ? (
          <div className="border border-term-border bg-term-surface p-5">
            <MarkdownPreview content={htmlToPlainText(value)} />
          </div>
        ) : null}
      </div>
      <EvidenceDrawer notes={notes} onInsertCitation={insertCitation} />
    </div>
  );
};
