import React, { useState, useRef, useEffect } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { EditorState } from "@codemirror/state";
import { EditorView, keymap, lineNumbers, highlightActiveLine, drawSelection } from "@codemirror/view";
import { markdown } from "@codemirror/lang-markdown";
import { languages } from "@codemirror/language-data";
import { defaultKeymap, history, historyKeymap } from "@codemirror/commands";
import { oneDark } from "@codemirror/theme-one-dark";
import type { Phase } from "../types";

interface DocumentPaneProps {
  content: string;
  onChange: (content: string) => void;
  phase: Phase;
  disabled: boolean;
  showOnboarding?: boolean;
}

function MarkdownEditor({
  content,
  onChange,
  disabled,
}: {
  content: string;
  onChange: (content: string) => void;
  disabled: boolean;
}) {
  const editorRef = useRef<HTMLDivElement>(null);
  const viewRef = useRef<EditorView | null>(null);

  useEffect(() => {
    if (!editorRef.current) return;

    const updateListener = EditorView.updateListener.of((update) => {
      if (update.docChanged) {
        onChange(update.state.doc.toString());
      }
    });

    const state = EditorState.create({
      doc: content,
      extensions: [
        lineNumbers(),
        highlightActiveLine(),
        drawSelection(),
        history(),
        keymap.of([...defaultKeymap, ...historyKeymap]),
        markdown({ codeLanguages: languages }),
        oneDark,
        updateListener,
        EditorView.editable.of(!disabled),
        EditorView.lineWrapping,
        EditorView.theme({
          "&": {
            height: "100%",
            fontSize: "14px",
          },
          ".cm-scroller": {
            overflow: "auto",
            fontFamily: '"SF Mono", Monaco, "Cascadia Code", monospace',
          },
          ".cm-content": {
            padding: "16px 0",
          },
          ".cm-line": {
            padding: "0 16px",
          },
        }),
      ],
    });

    const view = new EditorView({
      state,
      parent: editorRef.current,
    });

    viewRef.current = view;

    return () => {
      view.destroy();
      viewRef.current = null;
    };
  }, [disabled]);

  // Update content when it changes externally
  useEffect(() => {
    const view = viewRef.current;
    if (!view) return;

    const currentContent = view.state.doc.toString();
    if (content !== currentContent) {
      view.dispatch({
        changes: {
          from: 0,
          to: currentContent.length,
          insert: content,
        },
      });
    }
  }, [content]);

  return <div ref={editorRef} className="codemirror-editor" />;
}

export function DocumentPane({
  content,
  onChange,
  phase,
  disabled,
  showOnboarding,
}: DocumentPaneProps) {
  const [isEditing, setIsEditing] = useState(false);

  if (showOnboarding) {
    return (
      <div className="document-pane">
        <div className="document-header">
          <span>Welcome to Claude Flow</span>
        </div>
        <div className="document-content rendered onboarding">
          <h1>Claude Flow</h1>
          <p>
            A structured workflow for AI-assisted coding:{" "}
            <strong>Research → Plan → Implement</strong>.
          </p>

          <h2>Setup</h2>
          <p>Export your Anthropic API key:</p>
          <pre>
            <code>export ANTHROPIC_API_KEY=your-key-here</code>
          </pre>
          <p>
            Get one at{" "}
            <a
              href="https://platform.claude.com"
              target="_blank"
              rel="noopener"
            >
              platform.claude.com
            </a>
          </p>

          <h2>Getting Started</h2>
          <ol>
            <li>
              <strong>Add a project</strong> — Select a codebase folder
            </li>
            <li>
              <strong>Create a session</strong> — Start a new task
            </li>
            <li>
              <strong>Describe your work</strong> — Tell Claude what you want to
              build
            </li>
          </ol>

          <h2>Workflow</h2>
          <p>
            <strong>Research:</strong> Claude analyzes your codebase and writes
            findings to <code>research.md</code>. Add notes like{" "}
            <code>// REVIEW: check this</code> — click <strong>Review</strong>{" "}
            when done.
          </p>
          <p>
            <strong>Plan:</strong> Claude drafts an implementation plan in{" "}
            <code>plan.md</code> with code snippets and a TODO list. Iterate the
            same way.
          </p>
          <p>
            <strong>Implement:</strong> Claude executes the plan, marking tasks
            complete as it goes.
          </p>

          <p className="onboarding-tip">
            Iterate on research and plan docs as long as you want. Click{" "}
            <strong>Submit</strong> when happy to move to the next phase.
          </p>
        </div>
      </div>
    );
  }

  if (phase === "implement") {
    return (
      <div className="document-pane">
        <div className="document-header">
          <span>plan.md</span>
          <span className="badge">Implementing...</span>
        </div>
        <div className="document-content rendered">
          <ReactMarkdown remarkPlugins={[remarkGfm]}>{content}</ReactMarkdown>
        </div>
      </div>
    );
  }

  const filename = phase === "research" ? "research.md" : "plan.md";

  return (
    <div className="document-pane">
      <div className="document-header">
        <span>{filename}</span>
        <button onClick={() => setIsEditing(!isEditing)}>
          {isEditing ? "Preview" : "Edit"}
        </button>
      </div>

      {isEditing ? (
        <MarkdownEditor
          content={content}
          onChange={onChange}
          disabled={disabled}
        />
      ) : (
        <div
          className="document-content rendered"
          onClick={() => !disabled && setIsEditing(true)}
        >
          {content ? (
            <ReactMarkdown remarkPlugins={[remarkGfm]}>{content}</ReactMarkdown>
          ) : (
            <p className="empty">
              Document will appear here after Claude generates it...
            </p>
          )}
        </div>
      )}
    </div>
  );
}
