"use client";
import { useEffect, useRef, useState } from "react";

type ToolbarButton = { label: string; cmd: string; arg?: string; title: string };

const TOGGLE_BUTTONS: ToolbarButton[] = [
  { label: "B", cmd: "bold", title: "Bold" },
  { label: "I", cmd: "italic", title: "Italic" },
  { label: "U", cmd: "underline", title: "Underline" },
];

const BLOCK_BUTTONS: ToolbarButton[] = [
  { label: "H2", cmd: "formatBlock", arg: "H2", title: "Heading" },
  { label: "H3", cmd: "formatBlock", arg: "H3", title: "Subheading" },
  { label: "❝", cmd: "formatBlock", arg: "BLOCKQUOTE", title: "Quote" },
  { label: "•", cmd: "insertUnorderedList", title: "Bullet list" },
  { label: "1.", cmd: "insertOrderedList", title: "Numbered list" },
];

const ALIGN_BUTTONS: ToolbarButton[] = [
  { label: "⯇", cmd: "justifyLeft", title: "Align left" },
  { label: "☰", cmd: "justifyCenter", title: "Align center" },
  { label: "⯈", cmd: "justifyRight", title: "Align right" },
];

const COLORS = [
  // Whites / grays
  "#ffffff", "#f5f5f5", "#a3a3a3", "#6b7280", "#374151",
  // Reds / pinks
  "#ef4444", "#f43f5e", "#ec4899", "#db2777", "#b91c1c",
  // Oranges / yellows
  "#f97316", "#f59e0b", "#eab308", "#fbbf24", "#fde68a",
  // Greens
  "#22c55e", "#16a34a", "#4ade80", "#86efac", "#065f46",
  // Blues
  "#3b82f6", "#2563eb", "#60a5fa", "#93c5fd", "#1d4ed8",
  // Purples / indigo
  "#a855f7", "#8b5cf6", "#7c3aed", "#c084fc", "#6d28d9",
  // Cyans / teals
  "#06b6d4", "#14b8a6", "#67e8f9", "#2dd4bf", "#0e7490",
];

function isValidVideoUrl(url: string) {
  return /youtube\.com|youtu\.be|vimeo\.com/.test(url);
}

function videoEmbedHtml(url: string): string | null {
  const ytMatch = url.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([\w-]{11})/);
  if (ytMatch) {
    return `<div contenteditable="false" style="position:relative;padding-bottom:56.25%;height:0;margin:16px 0;"><iframe src="https://www.youtube.com/embed/${ytMatch[1]}" style="position:absolute;top:0;left:0;width:100%;height:100%;border-radius:8px;border:0;" allowfullscreen></iframe></div>`;
  }
  const vimeoMatch = url.match(/vimeo\.com\/(\d+)/);
  if (vimeoMatch) {
    return `<div contenteditable="false" style="position:relative;padding-bottom:56.25%;height:0;margin:16px 0;"><iframe src="https://player.vimeo.com/video/${vimeoMatch[1]}" style="position:absolute;top:0;left:0;width:100%;height:100%;border-radius:8px;border:0;" allowfullscreen></iframe></div>`;
  }
  return null;
}

export default function RichTextEditor({
  value,
  onChange,
}: {
  value: string;
  onChange: (html: string) => void;
}) {
  const ref = useRef<HTMLDivElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const pdfInputRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);
  const [uploadingPdf, setUploadingPdf] = useState(false);
  const [showColors, setShowColors] = useState(false);
  const [activeStates, setActiveStates] = useState<Record<string, boolean>>({});
  const initialized = useRef(false);

  useEffect(() => {
    if (ref.current && !initialized.current) {
      ref.current.innerHTML = value || "";
      initialized.current = true;
    }
  }, [value]);

  // Reflects the cursor's current formatting on the toolbar buttons — e.g.
  // Bold lights up while your cursor sits inside bold text — so the editor
  // behaves the way people expect from any standard text editor.
  function updateActiveStates() {
    const states: Record<string, boolean> = {};
    for (const b of [...TOGGLE_BUTTONS, ...BLOCK_BUTTONS, ...ALIGN_BUTTONS]) {
      try {
        states[b.cmd + (b.arg || "")] = document.queryCommandState(b.cmd);
      } catch {}
    }
    setActiveStates(states);
  }

  useEffect(() => {
    document.addEventListener("selectionchange", updateActiveStates);
    return () => document.removeEventListener("selectionchange", updateActiveStates);
  }, []);

  function exec(cmd: string, arg?: string) {
    ref.current?.focus();
    document.execCommand(cmd, false, arg);
    onChange(ref.current?.innerHTML || "");
    updateActiveStates();
  }

  function handleLink() {
    const url = prompt("Link URL:");
    if (url) exec("createLink", url);
  }

  function handleVideo() {
    const url = prompt("Paste a YouTube or Vimeo link:");
    if (!url) return;
    if (!isValidVideoUrl(url)) {
      alert("That doesn't look like a YouTube or Vimeo link.");
      return;
    }
    const html = videoEmbedHtml(url);
    if (html) exec("insertHTML", html + "<p><br></p>");
  }

  async function uploadFile(file: File): Promise<string | null> {
    const formData = new FormData();
    formData.append("file", file);
    const res = await fetch("/api/upload", { method: "POST", body: formData });
    const data = await res.json();
    return res.ok ? data.url : null;
  }

  async function handleImageUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploading(true);
    const url = await uploadFile(file);
    setUploading(false);
    e.target.value = "";
    if (url) exec("insertHTML", `<img src="${url}" style="max-width:100%;border-radius:8px;margin:12px 0;" />`);
  }

  async function handlePdfUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setUploadingPdf(true);
    const url = await uploadFile(file);
    setUploadingPdf(false);
    e.target.value = "";
    if (url) {
      exec(
        "insertHTML",
        `<a href="${url}" target="_blank" contenteditable="false" style="display:inline-flex;align-items:center;gap:8px;background:#1a1a1a;border:1px solid #2a2a2a;border-radius:8px;padding:10px 16px;color:#f5f5f5;text-decoration:none;font-size:14px;margin:8px 0;">📄 ${file.name}</a><p><br></p>`
      );
    }
  }

  const btnCls = (active: boolean) =>
    `w-8 h-8 flex items-center justify-center rounded text-sm font-semibold transition-colors ${
      active ? "bg-red-600 text-white" : "text-neutral-300 hover:bg-neutral-800 hover:text-white"
    }`;

  return (
    <div className="border border-neutral-800 rounded-lg overflow-hidden">
      <div className="flex flex-wrap items-center gap-1 bg-neutral-900 border-b border-neutral-800 p-2 relative">
        {TOGGLE_BUTTONS.map((b) => (
          <button
            key={b.label}
            type="button"
            title={b.title}
            onMouseDown={(e) => e.preventDefault()}
            onClick={() => exec(b.cmd, b.arg)}
            className={btnCls(!!activeStates[b.cmd])}
          >
            {b.label}
          </button>
        ))}

        <div className="relative">
          <button
            type="button"
            title="Text color"
            onMouseDown={(e) => e.preventDefault()}
            onClick={() => setShowColors((s) => !s)}
            className="w-8 h-8 flex items-center justify-center rounded text-sm text-neutral-300 hover:bg-neutral-800 hover:text-white"
          >
            🎨
          </button>
          {showColors && (
            <div className="absolute top-9 left-0 z-10 bg-neutral-900 border border-neutral-800 rounded-lg p-2.5 shadow-lg w-56">
              <div className="grid grid-cols-5 gap-1.5">
                {COLORS.map((c) => (
                  <button
                    key={c}
                    type="button"
                    onMouseDown={(e) => e.preventDefault()}
                    onClick={() => { exec("foreColor", c); setShowColors(false); }}
                    style={{ background: c }}
                    className="w-7 h-7 rounded border border-neutral-700 hover:scale-110 transition-transform"
                    title={c}
                  />
                ))}
              </div>
            </div>
          )}
        </div>

        <div className="w-px h-5 bg-neutral-800 mx-1" />

        {BLOCK_BUTTONS.map((b) => (
          <button
            key={b.label}
            type="button"
            title={b.title}
            onMouseDown={(e) => e.preventDefault()}
            onClick={() => exec(b.cmd, b.arg)}
            className={btnCls(!!activeStates[b.cmd + (b.arg || "")])}
          >
            {b.label}
          </button>
        ))}

        <div className="w-px h-5 bg-neutral-800 mx-1" />

        {ALIGN_BUTTONS.map((b) => (
          <button
            key={b.label}
            type="button"
            title={b.title}
            onMouseDown={(e) => e.preventDefault()}
            onClick={() => exec(b.cmd)}
            className={btnCls(!!activeStates[b.cmd])}
          >
            {b.label}
          </button>
        ))}

        <div className="w-px h-5 bg-neutral-800 mx-1" />

        <button
          type="button"
          title="Insert link"
          onMouseDown={(e) => e.preventDefault()}
          onClick={handleLink}
          className="w-8 h-8 flex items-center justify-center rounded text-sm text-neutral-300 hover:bg-neutral-800 hover:text-white"
        >
          🔗
        </button>
        <input ref={fileInputRef} type="file" accept="image/*" className="hidden" onChange={handleImageUpload} />
        <button
          type="button"
          title="Insert image"
          disabled={uploading}
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => fileInputRef.current?.click()}
          className="h-8 px-2.5 flex items-center justify-center rounded text-xs font-medium text-neutral-300 hover:bg-neutral-800 hover:text-white"
        >
          {uploading ? "Uploading..." : "🖼 Image"}
        </button>
        <button
          type="button"
          title="Embed a YouTube or Vimeo video"
          onMouseDown={(e) => e.preventDefault()}
          onClick={handleVideo}
          className="h-8 px-2.5 flex items-center justify-center rounded text-xs font-medium text-neutral-300 hover:bg-neutral-800 hover:text-white"
        >
          🎬 Video
        </button>
        <input ref={pdfInputRef} type="file" accept="application/pdf" className="hidden" onChange={handlePdfUpload} />
        <button
          type="button"
          title="Attach a PDF"
          disabled={uploadingPdf}
          onMouseDown={(e) => e.preventDefault()}
          onClick={() => pdfInputRef.current?.click()}
          className="h-8 px-2.5 flex items-center justify-center rounded text-xs font-medium text-neutral-300 hover:bg-neutral-800 hover:text-white"
        >
          {uploadingPdf ? "Uploading..." : "📄 PDF"}
        </button>
      </div>
      <div
        ref={ref}
        contentEditable
        suppressContentEditableWarning
        onInput={() => onChange(ref.current?.innerHTML || "")}
        onBlur={() => onChange(ref.current?.innerHTML || "")}
        onMouseUp={updateActiveStates}
        onKeyUp={updateActiveStates}
        className="prose-editor min-h-[300px] max-h-[600px] overflow-y-auto p-4 text-sm leading-relaxed outline-none [&_h2]:text-xl [&_h2]:font-bold [&_h2]:mt-4 [&_h2]:mb-2 [&_h3]:text-lg [&_h3]:font-bold [&_h3]:mt-3 [&_h3]:mb-2 [&_blockquote]:border-l-4 [&_blockquote]:border-red-600 [&_blockquote]:pl-4 [&_blockquote]:italic [&_blockquote]:text-neutral-400 [&_ul]:list-disc [&_ul]:pl-5 [&_ol]:list-decimal [&_ol]:pl-5 [&_a]:text-red-500 [&_a]:underline"
      />
    </div>
  );
}
