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

interface MemoWorkbenchProps {
  memoBlocks: MemoBlockCandidate[];
  notes: ResearchNote[];
  value: string;
  showPreview: boolean;
  onChange: (value: string) => void;
  onTogglePreview: () => void;
  onInsert: (kind: 'heading' | 'bullet' | 'quote' | 'callout') => void;
}

export const MemoWorkbench: React.FC<MemoWorkbenchProps> = ({
  memoBlocks,
  notes,
  value,
  showPreview,
  onChange,
  onTogglePreview,
  onInsert,
}) => {
  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}]`);
  };

  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-between gap-3">
          <FormattingToolbar onInsert={onInsert} />
          <button
            type="button"
            onClick={onTogglePreview}
            className="rounded-xl 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>
        <textarea
          value={value}
          onChange={(event) => onChange(event.target.value)}
          className="min-h-[520px] w-full rounded-[28px] border border-term-border bg-term-bg px-5 py-5 text-sm leading-7 text-term-text outline-none focus:border-info"
          placeholder="Write your stock pitch, memo section, catalyst calendar, or earnings recap..."
        />
        {showPreview ? (
          <div className="rounded-[28px] border border-term-border bg-term-surface p-5">
            <MarkdownPreview content={value} />
          </div>
        ) : null}
      </div>
      <EvidenceDrawer notes={notes} onInsertCitation={insertCitation} />
    </div>
  );
};
