"use client";

import { useState } from "react";
import { useTranslation } from "react-i18next";
import ToolbarButton, { asset, separator } from "./ToolbarButton";
import { type Editor } from "@tiptap/react";
import { FaAlignCenter, FaAlignLeft, FaAlignRight } from "react-icons/fa6";
import {
  MdOutlineKeyboardArrowDown,
  MdOutlineKeyboardArrowUp,
} from "react-icons/md";

/**
 * The editor's formatting bar.
 *
 * Owns the colour and alignment state because nothing outside the bar reads
 * it — the marks themselves live in the Tiptap document, and these two pieces
 * only track which button should look pressed. The bar mounts once the editor
 * exists and stays mounted, so the state is not reset behind the user.
 */
export default function RichTextToolbar({
  editor,
  selectedLanguage,
}: {
  editor: Editor;
  selectedLanguage: string;
}) {
  const { t } = useTranslation();
  const [currentColor, setCurrentColor] = useState("#29246D");
  const [isAlignOpen, setIsAlignOpen] = useState(false);
  const [currentAlign, setCurrentAlign] = useState(
    selectedLanguage === "ar" ? "right" : "left"
  );

  const toggleColor = () => {
    const newColor = currentColor === "#29246D" ? "#000000" : "#29246D";
    setCurrentColor(newColor);
    editor?.chain().focus().setColor(newColor).run();
  };

  const handleAlignSelect = (alignment: string) => {
    if (editor) {
      editor.chain().focus().setTextAlign(alignment).run();
      setCurrentAlign(alignment);
    }
    setIsAlignOpen(false);
  };

  const renderCurrentAlignIcon = () => {
    switch (currentAlign) {
      case "center":
        return <FaAlignCenter className="w-[18px] h-[17px]" />;
      case "right":
        return <FaAlignRight className="w-[18px] h-[17px]" />;
      default:
        return <FaAlignLeft className="w-[18px] h-[17px]" />;
    }
  };

  return (
      <div className="p-2 flex items-center space-x-2">
        <div className="editorbtn flex items-center">
          <ToolbarButton
            onClick={() => editor.chain().focus().undo().run()}
            src={asset("undo.svg")}
            alt={t("COMMON.EDITOR_UNDO")}
            size={18}
          />
          <ToolbarButton
            onClick={() => editor.chain().focus().redo().run()}
            src={asset("redo.svg")}
            alt={t("COMMON.EDITOR_REDO")}
            size={18}
          />
          {separator("sep-1")}
          <ToolbarButton
            onClick={() => editor.chain().focus().toggleBold().run()}
            active={editor.isActive("bold")}
            src={asset("bold_line.svg")}
            alt={t("COMMON.EDITOR_BOLD")}
          />
          <ToolbarButton
            onClick={() => editor.chain().focus().toggleItalic().run()}
            active={editor.isActive("italic")}
            src={asset("italic_line.svg")}
            alt={t("COMMON.EDITOR_ITALIC")}
          />
          <ToolbarButton
            onClick={() => editor.chain().focus().toggleUnderline().run()}
            active={editor.isActive("underline")}
            src={asset("underline_line.svg")}
            alt={t("COMMON.EDITOR_UNDERLINE")}
          />
          <ToolbarButton
            onClick={() => editor.chain().focus().toggleStrike().run()}
            active={editor.isActive("strike")}
            src={asset("strikethrough_line.svg")}
            alt={t("COMMON.EDITOR_STRIKE")}
          />
          {separator("sep-2")}
          <ToolbarButton
            onClick={() => editor.chain().focus().toggleBulletList().run()}
            active={editor.isActive("bulletList")}
            src={asset("list_check_line.svg")}
            alt={t("COMMON.EDITOR_BULLET_LIST")}
          />
          <ToolbarButton
            onClick={() => editor.chain().focus().toggleOrderedList().run()}
            active={editor.isActive("orderedList")}
            src={asset("list_ordered_line.svg")}
            alt={t("COMMON.EDITOR_ORDERED_LIST")}
          />

          <div className="relative flex items-center">
            <div className="p-1 rounded">{renderCurrentAlignIcon()}</div>
            <button
              type="button"
              onClick={() => setIsAlignOpen(!isAlignOpen)}
              aria-label={t("COMMON.EDITOR_ALIGNMENT")}
              aria-expanded={isAlignOpen}
              className="p-1 rounded hover:bg-gray-200"
            >
              {isAlignOpen ? (
                <MdOutlineKeyboardArrowUp className="w-[18px] h-[18px]" />
              ) : (
                <MdOutlineKeyboardArrowDown className="w-[18px] h-[18px]" />
              )}
            </button>
            {isAlignOpen && (
              <div className="absolute -bottom-10 left-0 bg-white border rounded shadow-lg z-10 flex space-x-2 p-1">
                {(
                  [
                    ["left", <FaAlignLeft key="l" className="w-[18px] h-[17px]" />],
                    ["center", <FaAlignCenter key="c" className="w-[18px] h-[17px]" />],
                    ["right", <FaAlignRight key="r" className="w-[18px] h-[17px]" />],
                  ] as const
                ).map(([alignment, icon]) => (
                  <button
                    key={alignment}
                    type="button"
                    onClick={() => handleAlignSelect(alignment)}
                    aria-label={t(`COMMON.EDITOR_ALIGN_${alignment.toUpperCase()}`)}
                    aria-pressed={currentAlign === alignment}
                    className={`p-1 rounded ${
                      currentAlign === alignment
                        ? "bg-gray-300 hover:bg-gray-300"
                        : "hover:bg-gray-100"
                    }`}
                  >
                    {icon}
                  </button>
                ))}
              </div>
            )}
          </div>

          {separator("sep-3")}
          <button
            type="button"
            onClick={toggleColor}
            className="p-1 rounded hover:bg-gray-200 w-[19px] h-[19px] xss:h-[18px] xss:w-[20px]"
            style={{
              backgroundColor: currentColor,
              borderRadius: "50%",
              border: "1px solid #ccc",
            }}
            title={t("COMMON.EDITOR_TEXT_COLOR")}
            aria-label={t("COMMON.EDITOR_TEXT_COLOR")}
          />
        </div>
      </div>
  );
}
