"use client";

import { useState, useEffect, useRef } from "react";
import { apiFetch } from "../api";

interface Document {
  id: number | null;
  title: string;
  content: string;
  author?: string;
  created_at?: string;
  updated_at?: string;
}

interface EditorProps {
  doc: Document;
  onSave: (doc: Document) => void;
  onCancel: () => void;
}

export default function Editor({ doc, onSave, onCancel }: EditorProps) {
  const [title, setTitle] = useState<string>(doc.title || "");
  const [content, setContent] = useState<string>(doc.content || "");
  const [error, setError] = useState<string>("");
  const [preview, setPreview] = useState<string>('Preview will appear here…');
  const [editingTitle, setEditingTitle] = useState(false);
  const [showCheatsheet, setShowCheatsheet] = useState(true);
  const [isReady, setIsReady] = useState(false);
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const asciidoctorRef = useRef<any>(null);

  // Initialize Asciidoctor once on client mount
  useEffect(() => {
    setIsReady(false);
    (async () => {
      try {
        if (typeof window !== "undefined") {
          // Dynamic import to avoid SSR issues
          const module = await import("@asciidoctor/core");
          const Asciidoctor = module.default;
          asciidoctorRef.current = Asciidoctor();
          setIsReady(true);
          console.log("✓ Asciidoctor initialized");
        }
      } catch (e) {
        console.error("✗ Asciidoctor init error:", e);
        setPreview(`<p style="color: red;">Error: Cannot initialize Asciidoctor</p>`);
      }
    })();
  }, []);

  // Live preview with debouncing
  useEffect(() => {
    const timer = setTimeout(() => {
      if (!isReady || !asciidoctorRef.current) {
        return;
      }
      if (!content) {
        setPreview("Start typing...");
        return;
      }
      try {
        const html = asciidoctorRef.current.convert(content) as string;
        setPreview(html);
        console.log("✓ Preview updated");
      } catch (e) {
        console.error("✗ Convert error:", e);
        setPreview(`<p style="color: red;">Error: ${e}</p>`);
      }
    }, 500); // debounce 500ms

    return () => clearTimeout(timer);
  }, [content, isReady]);

  // Auto-hide cheatsheet on smaller screens
  useEffect(() => {
    const handleResize = () => {
      if (window.innerWidth < 1100) {
        setShowCheatsheet(false);
      }
    };

    // Check on mount
    handleResize();

    // Listen for resize events
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  const handleSave = async () => {
    setError("");
    if (!title.trim()) {
      setError("Title cannot be empty");
      return;
    }
    try {
      const payload = { title: title.trim(), content };
      let updatedDoc: Document = { ...doc, title: title.trim(), content };

      if (doc.id) {
        const data = await apiFetch(`/api/documents/${doc.id}`, null, {
          method: "PUT",
          body: JSON.stringify(payload),
        });
        updatedDoc = { ...updatedDoc, ...data, title: data.title || title.trim() };
      } else {
        const data = await apiFetch("/api/documents", null, {
          method: "POST",
          body: JSON.stringify(payload),
        });
        updatedDoc = { ...updatedDoc, ...data, title: data.title || title.trim() };
      }

      onSave(updatedDoc);
    } catch (e: unknown) {
      const errorMessage = e instanceof Error ? e.message : "Save failed";
      setError(errorMessage);
    }
  };

  const insertCommand = (command: string) => {
    const textarea = textareaRef.current;
    if (!textarea) return;

    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const before = content.substring(0, start);
    const after = content.substring(end);
    
    setContent(before + command + after);
    
    // Focus and position cursor after insert
    setTimeout(() => {
      if (textarea) {
        textarea.focus();
        const newPos = start + command.length;
        textarea.setSelectionRange(newPos, newPos);
      }
    }, 0);
  };

  const insertBlockCommand = (command: string) => {
    const textarea = textareaRef.current;
    if (!textarea) return;

    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const before = content.substring(0, start);
    const after = content.substring(end);

    const normalized = command.replace(/\s+$/, "");
    const prefix =
      before.length === 0 || before.endsWith("\n\n")
        ? ""
        : before.endsWith("\n")
          ? "\n"
          : "\n\n";
    const suffix = "\n\n";

    const blockText = `${prefix}${normalized}${suffix}`;
    setContent(before + blockText + after);

    // Cursor lands after inserted block content, before separating blank line.
    setTimeout(() => {
      if (textarea) {
        textarea.focus();
        const newPos = start + prefix.length + normalized.length;
        textarea.setSelectionRange(newPos, newPos);
      }
    }, 0);
  };

  return (
    <div className="editor-panel">
      <div className="panel-header">
        {editingTitle ? (
          <input
            type="text"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            onBlur={() => setEditingTitle(false)}
            onKeyDown={(e) => {
              if (e.key === "Enter") setEditingTitle(false);
              if (e.key === "Escape") {
                setTitle(doc.title);
                setEditingTitle(false);
              }
            }}
            autoFocus
            className="title-input"
          />
        ) : (
          <strong 
            onClick={() => setEditingTitle(true)}
            className="editable-title"
            title="Click to edit title"
          >
            {title || "Untitled"}
          </strong>
        )}
        <div className="panel-header-actions">
          <button
            className="btn-secondary"
            onClick={() => setShowCheatsheet((prev) => !prev)}
            title={showCheatsheet ? "Hide cheatsheet" : "Show cheatsheet"}
          >
            {showCheatsheet ? "Hide Cheatsheet" : "Show Cheatsheet"}
          </button>
          <button className="btn-secondary" onClick={onCancel}>
            Back
          </button>
          <button onClick={handleSave}>Save</button>
        </div>
      </div>

      {/* Split Editor Layout */}
      <div className={`split-editor ${showCheatsheet ? "with-cheatsheet" : "without-cheatsheet"}`}>
        <div className="editor-section">
          <textarea 
            ref={textareaRef}
            value={content} 
            onChange={(e) => setContent(e.target.value)}
            placeholder="Write your AsciiDoc content here..."
          />
        </div>
        <div className="preview-section">
          <div
            className="rendered"
            dangerouslySetInnerHTML={{ __html: preview }}
          />
        </div>
        {showCheatsheet && (
        <div className="cheatsheet-section">
          <div className="cheatsheet-header">
            <h3>AsciiDoc Commands</h3>
          </div>
          <div className="cheatsheet-content">
            <div className="command-group">
              <h4>Headings</h4>
              <button onClick={() => insertBlockCommand("== Heading 1")} className="cmd-btn">== Heading 1</button>
              <button onClick={() => insertBlockCommand("=== Heading 2")} className="cmd-btn">=== Heading 2</button>
              <button onClick={() => insertBlockCommand("==== Heading 3")} className="cmd-btn">==== Heading 3</button>
            </div>

            <div className="command-group">
              <h4>Formatting</h4>
              <button onClick={() => insertCommand("*bold*")} className="cmd-btn">* Bold *</button>
              <button onClick={() => insertCommand("_italic_")} className="cmd-btn">_ Italic _</button>
              <button onClick={() => insertCommand("`code`")} className="cmd-btn">` Code `</button>
              <button onClick={() => insertCommand("~strikethrough~")} className="cmd-btn">~ Strike ~</button>
            </div>

            <div className="command-group">
              <h4>Lists</h4>
              <button onClick={() => insertBlockCommand("//\n* Item 1\n* Item 2")} className="cmd-btn">* Bullet List</button>
              <button onClick={() => insertBlockCommand("//\n. Item 1\n. Item 2")} className="cmd-btn">1. Ordered List</button>
              <button onClick={() => insertBlockCommand("//\n* Item 1\n** Sub-item\n* Item 2")} className="cmd-btn">Nested List</button>
            </div>

            <div className="command-group">
              <h4>Blocks</h4>
              <button onClick={() => insertBlockCommand("[source]\n----\ncode\n----")} className="cmd-btn">Code Block</button>
              <button onClick={() => insertBlockCommand("____\nquote text\n____")} className="cmd-btn">Quote</button>
            </div>
          </div>
        </div>
        )}
      </div>

      {error && <p className="error">{error}</p>}
    </div>
  );
}
