"use client";

import { useRef } from "react";
import { RICH_TEXT_CONTENT_CLASSES } from "@/lib/shared/rich-text-classes";

type ToolbarAction = { label: string; command: string; value?: string; className?: string };

const TOOLBAR: ToolbarAction[] = [
  { label: "K", command: "bold", className: "font-bold" },
  { label: "İ", command: "italic", className: "italic" },
  { label: "A", command: "underline", className: "underline" },
  { label: "•", command: "insertUnorderedList" },
  { label: "1.", command: "insertOrderedList" },
];

const BLOCK_FORMATS = [
  { label: "Biçim", value: "" },
  { label: "Paragraf", value: "P" },
  { label: "Başlık 2", value: "H2" },
  { label: "Başlık 3", value: "H3" },
  { label: "Başlık 4", value: "H4" },
];

export function RichTextEditor({
  name,
  defaultValue = "",
  placeholder,
}: {
  name: string;
  defaultValue?: string;
  placeholder?: string;
}) {
  const editorRef = useRef<HTMLDivElement>(null);
  const hiddenRef = useRef<HTMLInputElement>(null);

  function syncValue() {
    if (editorRef.current && hiddenRef.current) {
      hiddenRef.current.value = editorRef.current.innerHTML;
    }
  }

  function exec(command: string, value?: string) {
    editorRef.current?.focus();
    document.execCommand(command, false, value);
    syncValue();
  }

  function handleBlockFormat(e: React.ChangeEvent<HTMLSelectElement>) {
    const value = e.target.value;
    e.target.value = "";
    if (!value) return;
    exec("formatBlock", value);
  }

  function handleLink() {
    const url = window.prompt("Bağlantı adresi girin (https://...):");
    if (url) exec("createLink", url);
  }

  function handlePaste(e: React.ClipboardEvent<HTMLDivElement>) {
    e.preventDefault();
    const text = e.clipboardData.getData("text/plain");
    document.execCommand("insertText", false, text);
    syncValue();
  }

  return (
    <div className="overflow-hidden rounded-xl border border-border focus-within:border-accent">
      <div className="flex flex-wrap items-center gap-1 border-b border-border bg-bg-alt px-2 py-1.5">
        <select
          onChange={handleBlockFormat}
          defaultValue=""
          className="h-7 rounded-md border border-border bg-white px-1.5 text-[12px] text-text-muted outline-none hover:text-accent"
          title="Metin biçimi"
        >
          {BLOCK_FORMATS.map((format) => (
            <option key={format.value} value={format.value} disabled={format.value === ""}>
              {format.label}
            </option>
          ))}
        </select>
        <span className="mx-0.5 h-5 w-px bg-border" />
        {TOOLBAR.map((action) => (
          <button
            key={action.command}
            type="button"
            onMouseDown={(e) => e.preventDefault()}
            onClick={() => exec(action.command, action.value)}
            className={`flex h-7 w-7 items-center justify-center rounded-md text-[13px] text-text-muted hover:bg-white hover:text-accent ${action.className ?? ""}`}
          >
            {action.label}
          </button>
        ))}
        <button
          type="button"
          onMouseDown={(e) => e.preventDefault()}
          onClick={handleLink}
          className="flex h-7 w-7 items-center justify-center rounded-md text-text-muted hover:bg-white hover:text-accent"
          title="Bağlantı ekle"
        >
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
            <path d="M10 13a5 5 0 0 0 7.5.5l2-2a5 5 0 0 0-7-7l-1.5 1.5" />
            <path d="M14 11a5 5 0 0 0-7.5-.5l-2 2a5 5 0 0 0 7 7l1.5-1.5" />
          </svg>
        </button>
        <button
          type="button"
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => exec("removeFormat")}
          className="flex h-7 w-7 items-center justify-center rounded-md text-text-muted hover:bg-white hover:text-accent"
          title="Biçimlendirmeyi temizle"
        >
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
            <path d="M18 6L6 18M6 6l12 12" />
          </svg>
        </button>
      </div>

      <div
        ref={editorRef}
        contentEditable
        suppressContentEditableWarning
        onInput={syncValue}
        onBlur={syncValue}
        onPaste={handlePaste}
        data-placeholder={placeholder}
        dangerouslySetInnerHTML={{ __html: defaultValue }}
        className={`min-h-[120px] px-4 py-3 text-[14px] leading-relaxed outline-none empty:before:text-text-muted empty:before:content-[attr(data-placeholder)] ${RICH_TEXT_CONTENT_CLASSES}`}
      />
      <input ref={hiddenRef} type="hidden" name={name} defaultValue={defaultValue} />
    </div>
  );
}
