import { defineComponent } from 'vue';
import { SbMain, SbMode } from '@schlechtenburg/core';
import PageToolbar from '~~/components/PageToolbar';
import SbLayout from '@schlechtenburg/layout';
import SbHeading from '@schlechtenburg/heading';
import SbParagraph from '@schlechtenburg/paragraph';
import SbImage from '@schlechtenburg/image';

export default defineComponent({
  async setup() {
    const { me } = useMe();

    const loggedIn = computed(() => !!me.value?.id);

    const { page, setPage } = usePage();
    const block = page.value?.attributes?.block;

    const {
      mode,
      draft,
      updateDraft,
      revision,
    } = useEditor();

    watch(revision, async () => {
      const { data, error } = await useAsyncGql(
        'updatePage',
        {
          id: page.value?.id || '',
          data: {
            block: draft.value!
          },
        },
      );

      if (error.value) {
        console.error('Error updating page!');
        console.error('error:', error.value);
        console.error('data:', data.value);
        return;
      }

      setPage(data.value?.updatePage?.data?.attributes?.block);
      updateDraft(data.value?.updatePage?.data?.attributes?.block);
    });

    watch(mode, async (newMode) => {
      if (newMode === SbMode.View) {
        updateDraft(block!);
      }
    });

    updateDraft(block!);


    if (!block) {
      console.error('No block!');
      console.error('page', page.value);
    }

    return () => (
      <div class="ex-page">
        {loggedIn.value ? <PageToolbar></PageToolbar> : null}
        {draft.value
        ? <SbMain
          class="ex-page"
          mode={mode.value}
          eventUpdate={(updatedBlock) => updateDraft(updatedBlock)}
          block={draft.value}
          availableBlocks={[
            SbLayout,
            SbHeading,
            SbParagraph,
            SbImage,
          ]}
        />
        : <div class="ex-page ex-page_corrupt">Corrupt page: {page.value?.attributes?.path} ({page.value?.id})</div>}
      </div>
    );
  },
});
