"use client";

import { cn } from "@/lib/utils";
import Highlight from "@tiptap/extension-highlight";
import Image from "@tiptap/extension-image";
import Placeholder from "@tiptap/extension-placeholder";
import TextAlign from "@tiptap/extension-text-align";
import Underline from "@tiptap/extension-underline";
import { EditorContent, useEditor } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import {
  AlignCenter,
  AlignLeft,
  AlignRight,
  Bold,
  ChevronDown,
  FileUp,
  Highlighter,
  ImageUp,
  Italic,
  List,
  ListOrdered,
  Strikethrough,
  Type,
  Underline as UnderlineIcon,
} from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import type { ReactNode } from "react";
import { useEffect, useRef } from "react";

interface PageContentEditorProps {
  value: string;
  onChange: (value: string) => void;
  placeholder: string;
  className?: string;
}

function ToolbarButton({
  label,
  active = false,
  onClick,
  children,
}: {
  label: string;
  active?: boolean;
  onClick: () => void;
  children: ReactNode;
}) {
  return (
    <button
      type="button"
      aria-label={label}
      title={label}
      onClick={onClick}
      className={cn(
        "flex h-8 w-8 items-center justify-center rounded-full text-muted-foreground transition-colors",
        "hover:bg-muted",
        active && "bg-highlights-bg text-primary"
      )}
    >
      {children}
    </button>
  );
}

function ToolbarDivider() {
  return <div className="h-8 w-px bg-border" />;
}

export function PageContentEditor({
  value,
  onChange,
  placeholder,
  className,
}: PageContentEditorProps) {
  const t = useTranslations("dashboard.pages.form.editor");
  const locale = useLocale();
  const isRtl = locale === "ar";
  const imageInputRef = useRef<HTMLInputElement>(null);

  const editor = useEditor({
    immediatelyRender: false,
    extensions: [
      StarterKit.configure({
        heading: {
          levels: [1, 2, 3],
        },
      }),
      Underline,
      Highlight.configure({
        multicolor: true,
      }),
      TextAlign.configure({
        types: ["heading", "paragraph"],
      }),
      Image,
      Placeholder.configure({
        placeholder,
      }),
    ],
    content: value,
    editorProps: {
      attributes: {
        class: cn(
          "page-content-editor min-h-[68px] w-full px-4 py-3 text-sm text-foreground outline-none",
          isRtl ? "" : ""
        ),
      },
    },
    onUpdate: ({ editor: currentEditor }) => {
      onChange(currentEditor.getHTML());
    },
  });

  useEffect(() => {
    if (!editor) return;

    const currentHtml = editor.getHTML();
    if (value !== currentHtml) {
      editor.commands.setContent(value || "", { emitUpdate: false });
    }
  }, [editor, value]);

  const insertImageFromFile = (file: File) => {
    if (!editor) return;

    const reader = new FileReader();
    reader.onload = () => {
      if (typeof reader.result !== "string") return;

      editor
        .chain()
        .focus()
        .setImage({
          src: reader.result,
          alt: file.name,
        })
        .run();
    };
    reader.readAsDataURL(file);
  };

  const insertImageFromUrl = () => {
    if (!editor) return;

    const src = window.prompt(t("imagePrompt"));
    if (!src) return;

    editor
      .chain()
      .focus()
      .setImage({
        src,
      })
      .run();
  };

  if (!editor) {
    return (
      <div className={cn("rounded-2xl border border-border bg-card", className)}>
        <div className="h-[48px] border-b border-border" />
        <div className="h-[68px]" />
      </div>
    );
  }

  const currentFontSize = editor.isActive("heading", { level: 1 })
    ? "32"
    : editor.isActive("heading", { level: 2 })
      ? "24"
      : editor.isActive("heading", { level: 3 })
        ? "20"
        : "16";

  return (
    <div className={cn("overflow-hidden rounded-2xl border border-border bg-card", className)}>
      <input
        ref={imageInputRef}
        type="file"
        accept="image/*"
        className="hidden"
        onChange={(event) => {
          const file = event.target.files?.[0];
          if (!file) return;
          insertImageFromFile(file);
          event.target.value = "";
        }}
      />

      <div className="flex min-h-[48px] items-center border-b border-border px-2">
        <div className="flex items-center gap-2">
          <ToolbarButton
            label={t("uploadImage")}
            onClick={() => imageInputRef.current?.click()}
          >
            <ImageUp className="h-4 w-4" />
          </ToolbarButton>
          <ToolbarButton label={t("insertImage")} onClick={insertImageFromUrl}>
            <FileUp className="h-4 w-4" />
          </ToolbarButton>
        </div>

        <ToolbarDivider />

        <div className="flex items-center gap-2 px-2">
          <ToolbarButton
            label={t("orderedList")}
            active={editor.isActive("orderedList")}
            onClick={() => editor.chain().focus().toggleOrderedList().run()}
          >
            <ListOrdered className="h-4 w-4" />
          </ToolbarButton>
          <ToolbarButton
            label={t("bulletList")}
            active={editor.isActive("bulletList")}
            onClick={() => editor.chain().focus().toggleBulletList().run()}
          >
            <List className="h-4 w-4" />
          </ToolbarButton>
        </div>

        <ToolbarDivider />

        <div className="flex items-center gap-2 px-2">
          <ToolbarButton
            label={t("alignLeft")}
            active={editor.isActive({ textAlign: "left" })}
            onClick={() => editor.chain().focus().setTextAlign("left").run()}
          >
            <AlignLeft className="h-4 w-4" />
          </ToolbarButton>
          <ToolbarButton
            label={t("alignCenter")}
            active={editor.isActive({ textAlign: "center" })}
            onClick={() => editor.chain().focus().setTextAlign("center").run()}
          >
            <AlignCenter className="h-4 w-4" />
          </ToolbarButton>
          <ToolbarButton
            label={t("alignRight")}
            active={editor.isActive({ textAlign: "right" })}
            onClick={() => editor.chain().focus().setTextAlign("right").run()}
          >
            <AlignRight className="h-4 w-4" />
          </ToolbarButton>
        </div>

        <ToolbarDivider />

        <div className="flex items-center gap-2 px-2">
          <ToolbarButton
            label={t("highlight")}
            active={editor.isActive("highlight")}
            onClick={() => editor.chain().focus().toggleHighlight().run()}
          >
            <Highlighter className="h-4 w-4" />
          </ToolbarButton>
          <ToolbarButton
            label={t("bold")}
            active={editor.isActive("bold")}
            onClick={() => editor.chain().focus().toggleBold().run()}
          >
            <Bold className="h-4 w-4" />
          </ToolbarButton>
          <ToolbarButton
            label={t("italic")}
            active={editor.isActive("italic")}
            onClick={() => editor.chain().focus().toggleItalic().run()}
          >
            <Italic className="h-4 w-4" />
          </ToolbarButton>
          <ToolbarButton
            label={t("underline")}
            active={editor.isActive("underline")}
            onClick={() => editor.chain().focus().toggleUnderline().run()}
          >
            <UnderlineIcon className="h-4 w-4" />
          </ToolbarButton>
          <ToolbarButton
            label={t("strike")}
            active={editor.isActive("strike")}
            onClick={() => editor.chain().focus().toggleStrike().run()}
          >
            <Strikethrough className="h-4 w-4" />
          </ToolbarButton>
        </div>

        <ToolbarDivider />

        <div className="flex items-center gap-2 px-2">
          <button
            type="button"
            aria-label={t("fontSize")}
            className="flex h-8 items-center gap-1 rounded-md px-2 text-sm font-bold text-muted-foreground hover:bg-muted"
          >
            <span>{currentFontSize}</span>
            <ChevronDown className="h-4 w-4" />
          </button>
        </div>

        <ToolbarDivider />

        <button
          type="button"
          onClick={() => editor.chain().focus().setParagraph().run()}
          className="ms-auto flex h-8 items-center gap-1 rounded-md px-2 text-sm font-bold text-muted-foreground hover:bg-muted"
        >
          <span>{t("paragraph")}</span>
          <Type className="h-4 w-4" />
        </button>
      </div>

      <EditorContent editor={editor} />
    </div>
  );
}
