"use client";
import React, { useState, useRef, useCallback } from "react";
import { marked } from "marked";
import { useI18n } from "@/lib/i18n";

interface MarkdownNoteEditorProps {
  value: string;
  onChange: (newValue: string) => void;
  onSave?: () => void;
}

export function MarkdownNoteEditor({ value, onChange, onSave }: MarkdownNoteEditorProps) {
  const { t } = useI18n();
  const [mode, setMode] = useState<"edit" | "preview">("preview");
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  // Insert markdown syntax at selection or cursor position
  const insertSyntax = useCallback(
    (before: string, after = "", placeholder = "") => {
      const ta = textareaRef.current;
      if (!ta) {
        onChange(value + before + placeholder + after);
        return;
      }
      const start = ta.selectionStart ?? ta.value.length;
      const end = ta.selectionEnd ?? ta.value.length;
      const selected = ta.value.slice(start, end) || placeholder;
      const newVal = ta.value.slice(0, start) + before + selected + after + ta.value.slice(end);
      onChange(newVal);

      requestAnimationFrame(() => {
        ta.focus();
        ta.selectionStart = start + before.length;
        ta.selectionEnd = start + before.length + selected.length;
      });
    },
    [onChange, value]
  );

  // Keyboard shortcuts
  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if ((e.ctrlKey || e.metaKey) && e.key === "b") {
      e.preventDefault();
      insertSyntax("**", "**", "bold");
    } else if ((e.ctrlKey || e.metaKey) && e.key === "i") {
      e.preventDefault();
      insertSyntax("*", "*", "italic");
    } else if ((e.ctrlKey || e.metaKey) && e.key === "s") {
      e.preventDefault();
      if (onSave) onSave();
    } else if (e.key === "Tab") {
      e.preventDefault();
      insertSyntax("  ");
    }
  };

  // Toggle interactive checkboxes in markdown preview
  const handlePreviewCheckboxToggle = (index: number) => {
    const lines = value.split("\n");
    let checkboxCount = 0;
    const newLines = lines.map((line) => {
      const match = line.match(/^(\s*[-*+]\s*\[)([ xX])(\])(.*)$/);
      if (match) {
        if (checkboxCount === index) {
          const currentChecked = match[2].toLowerCase() === "x";
          const newChecked = currentChecked ? " " : "x";
          checkboxCount++;
          return `${match[1]}${newChecked}${match[3]}${match[4]}`;
        }
        checkboxCount++;
      }
      return line;
    });
    onChange(newLines.join("\n"));
  };

  // Convert markdown to sanitized HTML with interactive checkboxes
  const renderMarkdownHtml = () => {
    if (!value || !value.trim()) {
      return `<p style="color: var(--text-tertiary); font-style: italic;">${t("notesPlaceholder").split("\n")[0]}</p>`;
    }

    try {
      let rawHtml = marked.parse(value, { breaks: true, gfm: true }) as string;

      // Replace task list checkboxes with interactive ones
      let cbIdx = 0;
      rawHtml = rawHtml.replace(/<input[^>]*type="checkbox"[^>]*checked[^>]*>/gi, () => {
        const id = `cb-${cbIdx++}`;
        return `<span class="markdown-checkbox-box checked" data-idx="${id}"></span>`;
      });
      rawHtml = rawHtml.replace(/<input[^>]*type="checkbox"[^>]*>/gi, () => {
        const id = `cb-${cbIdx++}`;
        return `<span class="markdown-checkbox-box" data-idx="${id}"></span>`;
      });

      return rawHtml;
    } catch {
      return value;
    }
  };

  return (
    <div className="note-editor-wrap">
      {/* Top Toolbar */}
      <div className="note-editor-toolbar">
        {/* Mode Switcher Tabs */}
        <div className="note-toolbar-group">
          <button
            type="button"
            className={`note-toolbar-btn${mode === "preview" ? " active" : ""}`}
            onClick={() => setMode("preview")}
            title="Preview rendered Markdown"
          >
            👁️ Preview
          </button>
          <button
            type="button"
            className={`note-toolbar-btn${mode === "edit" ? " active" : ""}`}
            onClick={() => {
              setMode("edit");
              setTimeout(() => textareaRef.current?.focus(), 50);
            }}
            title="Edit raw Markdown"
          >
            ✏️ Edit
          </button>
        </div>

        <div className="note-toolbar-divider" />

        {/* Formatting actions */}
        <div className="note-toolbar-group">
          <button
            type="button"
            className="note-toolbar-btn"
            title="H1 Heading"
            onClick={() => {
              setMode("edit");
              insertSyntax("# ", "", "Heading 1");
            }}
          >
            H1
          </button>
          <button
            type="button"
            className="note-toolbar-btn"
            title="H2 Heading"
            onClick={() => {
              setMode("edit");
              insertSyntax("## ", "", "Heading 2");
            }}
          >
            H2
          </button>
          <button
            type="button"
            className="note-toolbar-btn"
            title="H3 Heading"
            onClick={() => {
              setMode("edit");
              insertSyntax("### ", "", "Heading 3");
            }}
          >
            H3
          </button>
        </div>

        <div className="note-toolbar-divider" />

        <div className="note-toolbar-group">
          <button
            type="button"
            className="note-toolbar-btn"
            title="Bold (Ctrl+B)"
            onClick={() => {
              setMode("edit");
              insertSyntax("**", "**", "bold");
            }}
          >
            <strong>B</strong>
          </button>
          <button
            type="button"
            className="note-toolbar-btn"
            title="Italic (Ctrl+I)"
            style={{ fontStyle: "italic" }}
            onClick={() => {
              setMode("edit");
              insertSyntax("*", "*", "italic");
            }}
          >
            <em>I</em>
          </button>
          <button
            type="button"
            className="note-toolbar-btn"
            title="Strikethrough"
            style={{ textDecoration: "line-through" }}
            onClick={() => {
              setMode("edit");
              insertSyntax("~~", "~~", "strikethrough");
            }}
          >
            S
          </button>
        </div>

        <div className="note-toolbar-divider" />

        <div className="note-toolbar-group">
          <button
            type="button"
            className="note-toolbar-btn"
            title="Checkbox item"
            onClick={() => {
              setMode("edit");
              insertSyntax("\n- [ ] ", "", "task");
            }}
          >
            ☑️
          </button>
          <button
            type="button"
            className="note-toolbar-btn"
            title="Bullet list"
            onClick={() => {
              setMode("edit");
              insertSyntax("\n- ", "", "list item");
            }}
          >
            •
          </button>
          <button
            type="button"
            className="note-toolbar-btn"
            title="Numbered list"
            onClick={() => {
              setMode("edit");
              insertSyntax("\n1. ", "", "list item");
            }}
          >
            1.
          </button>
          <button
            type="button"
            className="note-toolbar-btn"
            title="Quote"
            onClick={() => {
              setMode("edit");
              insertSyntax("\n> ", "", "quote");
            }}
          >
            ❝
          </button>
          <button
            type="button"
            className="note-toolbar-btn"
            title="Code Block"
            style={{ fontFamily: "monospace" }}
            onClick={() => {
              setMode("edit");
              insertSyntax("\n```\n", "\n```\n", "code");
            }}
          >
            {"< >"}
          </button>
          <button
            type="button"
            className="note-toolbar-btn"
            title="Horizontal Divider"
            onClick={() => {
              setMode("edit");
              insertSyntax("\n---\n");
            }}
          >
            ―
          </button>
          <button
            type="button"
            className="note-toolbar-btn"
            title="Link"
            onClick={() => {
              setMode("edit");
              insertSyntax("[", "](https://example.com)", "link title");
            }}
          >
            🔗
          </button>
        </div>
      </div>

      {/* Editor / Preview Content Area */}
      {mode === "edit" ? (
        <textarea
          ref={textareaRef}
          id="note-textarea"
          className="note-textarea"
          placeholder={t("notesPlaceholder")}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          onKeyDown={handleKeyDown}
        />
      ) : (
        <div
          className="markdown-body"
          dangerouslySetInnerHTML={{ __html: renderMarkdownHtml() }}
          onClick={(e) => {
            const target = e.target as HTMLElement;
            if (target.classList.contains("markdown-checkbox-box")) {
              const idxStr = target.getAttribute("data-idx");
              if (idxStr) {
                const idx = parseInt(idxStr.replace("cb-", ""), 10);
                if (!isNaN(idx)) handlePreviewCheckboxToggle(idx);
              }
            } else if (e.detail === 2) {
              // Double click anywhere to quickly switch to edit mode
              setMode("edit");
            }
          }}
        />
      )}
    </div>
  );
}