import { defineComponent } from 'vue';
import { SbButton, SbMode } from '@schlechtenburg/core';
import PageBreadcrumb from '~~/components/PageBreadcrumb';

import './PageToolbar.scss';

export default defineComponent({
  async setup() {
    const {
      currentPage,
      currentPageId,
      setCurrentPageId,
    } = useCurrentPage();

    const { pages, insertPage } = usePages();

    const {
      mode,
      edit,
      cancel,
      save,
    } = useEditor();

    const addChildPage = () => {
      insertPage({
        id: 'draft',
        attributes: {
          title: 'New page',
          block: getNewPageBlock(),
          slug: 'new-page',
          parent: {
            data: {
              id: currentPage.value?.id,
            },
          },
        },
      });

     setCurrentPageId('draft');
     edit(currentPage.value?.attributes?.block!);
    };

    return () => (
      <div class="ex-page-toolbar">
        <PageBreadcrumb />
        {currentPageId.value !== 'draft'
          ? <SbButton
            type="button"
            onClick={() => addChildPage()}
          >Add child page</SbButton>
          : null}
        { mode.value === SbMode.View
          ? <SbButton
            type="button"
            onClick={() => edit(currentPage.value?.attributes?.block!)}
          >Edit</SbButton>
          : <>
            <SbButton
              type="button"
              onClick={() => cancel()}
            >Cancel</SbButton>
            <SbButton
              type="button"
              onClick={() => save()}
            >Save</SbButton>
          </>}
      </div>
    );
  },
});
