import {
  ArrowForward,
} from "iconsax-react";
import { useEditorStore } from "../store/editorStore";

const FA_DIGITS = ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"] as const;

function toPersianDigits(num: number): string {
  return String(num).replace(/\d/g, (d) => FA_DIGITS[parseInt(d, 10)]!);
}

type EditorCanvasToolbarProps = {
  barWidthPx: number;
};

const iconHistory = {
  size: 22,
  variant: "Linear" as const,
  color: "currentColor",
};

const EditorCanvasToolbar = ({ barWidthPx }: EditorCanvasToolbarProps) => {
  const {
    pages,
    currentPageId,
    objectHistoryPast,
    objectHistoryFuture,
    undoObjects,
    redoObjects,
  } = useEditorStore();

  const canUndo = objectHistoryPast.length > 0;
  const canRedo = objectHistoryFuture.length > 0;

  const pageIndexOneBased = currentPageId
    ? pages.findIndex((p) => p.id === currentPageId) + 1
    : 0;

  const pageLabel =
    pages.length > 0
      ? `${toPersianDigits(pageIndexOneBased)}\u200e / ${toPersianDigits(pages.length)}`
      : "";

  const historyBtn =
    "flex size-10 items-center justify-center rounded-xl text-[#4a5568] transition-colors hover:bg-black/[0.04] active:bg-black/[0.06] disabled:pointer-events-none disabled:opacity-[0.32] outline-none";

  return (
    <div
      dir="ltr"
      role="toolbar"
      aria-label="نوار کنترل بوم"
      className="flex h-[52px] shrink-0 items-center justify-between"
      style={{ width: barWidthPx }}
    >
      <div className="flex flex-1 items-center min-w-0">
        <div className="flex items-center gap-1 pl-1">
          <button
            type="button"
            title="برگشت"
            disabled={!canUndo}
            onClick={() => undoObjects()}
            className={historyBtn}
          >
            <span className="inline-flex scale-x-[-1]" aria-hidden>
              <ArrowForward {...iconHistory} />
            </span>
          </button>
          <button
            type="button"
            title="از نو"
            disabled={!canRedo}
            onClick={() => redoObjects()}
            className={historyBtn}
          >
            <ArrowForward {...iconHistory} aria-hidden />
          </button>
        </div>
      </div>

      <span
        dir="ltr"
        className="select-none whitespace-nowrap text-[14px]  tabular-nums font-bold"
      >
        {pageLabel}
      </span>
    </div>
  );
};

export default EditorCanvasToolbar;
