import { FC } from "react";
import { useAtomValue } from "jotai";
import type { Editor } from "@tiptap/react";
import { pageEditorAtom } from "@/features/editor/atoms/editor-atoms";
import { useToolbarState } from "./use-toolbar-state";
import { BlockTypeGroup } from "./groups/block-type-group";
import { InlineMarksGroup } from "./groups/inline-marks-group";
import { ColorGroup } from "./groups/color-group";
import { ListsGroup } from "./groups/lists-group";
import { AlignmentGroup } from "./groups/alignment-group";
import { MediaGroup } from "./groups/media-group";
import { QuickInsertsGroup } from "./groups/quick-inserts-group";
import { MoreInsertsGroup } from "./groups/more-inserts-group";
import { HistoryGroup } from "./groups/history-group";
import classes from "./fixed-toolbar.module.css";

type FixedToolbarProps = {
  editor?: Editor | null;
  templateMode?: boolean;
};

export const FixedToolbar: FC<FixedToolbarProps> = ({
  editor: editorProp,
  templateMode = false,
}) => {
  const editorFromAtom = useAtomValue(pageEditorAtom);
  const editor = editorProp ?? editorFromAtom;
  const state = useToolbarState(editor);

  if (!editor || !state) return null;

  return (
    <>
      <div
        className={classes.fixedToolbar}
        data-fixed-toolbar="true"
        role="toolbar"
        aria-label="Editor toolbar"
        onMouseDown={(e) => e.preventDefault()}
      >
        <div className={classes.inner}>
          <BlockTypeGroup editor={editor} />
          <div className={classes.divider} />
          <InlineMarksGroup editor={editor} state={state} />
          <div className={classes.divider} />
          <ColorGroup editor={editor} />
          <div className={classes.divider} />
          <ListsGroup editor={editor} state={state} />
          <div className={classes.divider} />
          <AlignmentGroup editor={editor} />
          <div className={classes.divider} />
          <MediaGroup editor={editor} templateMode={templateMode} />
          <div className={classes.divider} />
          <QuickInsertsGroup editor={editor} />
          <MoreInsertsGroup editor={editor} templateMode={templateMode} />
          <div className={classes.divider} />
          <HistoryGroup editor={editor} state={state} />
        </div>
      </div>
      <div className={classes.spacer} aria-hidden />
    </>
  );
};
