import {
  computed,
  defineComponent,
  reactive,
  ref,
} from 'vue';

import { SbMain, IBlockData, SbMode } from '@schlechtenburg/core';

import SbLayout from '@schlechtenburg/layout';
import SbHeading from '@schlechtenburg/heading';
import SbParagraph from '@schlechtenburg/paragraph';
import SbImage from '@schlechtenburg/image';

import exampleData from './example-data';

import './ExampleEditor.scss';

export default defineComponent({
  name: 'ExampleEditor',

  setup() {
    const activeTab = ref('edit');
    const block: IBlockData<any> = reactive({ ...exampleData });
    const dateID = +(new Date());

    const displayedElement = computed(() => {
      switch (activeTab.value) {
        case 'data':
          return <pre class="example-editor--json"><code>{ JSON.stringify(block, null, 2) }</code></pre>;
        default:
          return <SbMain
            class="example-editor--sb"
            block={block}
            availableBlocks={[
              SbLayout,
              SbHeading,
              SbImage,
              SbParagraph,
            ]}
            mode={activeTab.value as SbMode}
            eventUpdate={(data:IBlockData<any>) => {
              block.id = data.id;
              block.name = data.name;
              block.data = data.data;
            }}
          />;
      }
    });

    const onModeChange = ($event: Event) => {
      activeTab.value = ($event.target as HTMLSelectElement).value;
    };

    return () => {
      return <div class="example-editor">
        <div class="example-editor--mode">
          <label class={{
            'example-editor--mode-tab': true,
            'example-editor--mode-tab_checked': activeTab.value === SbMode.Edit,
          }}>
            <input
              type="radio"
              name={`example-editor-${dateID}`}
              value={SbMode.Edit}
              checked={activeTab.value === SbMode.Edit}
              onChange={onModeChange}
            />
            Editor mode
          </label>
          <label class={{
            'example-editor--mode-tab': true,
            'example-editor--mode-tab_checked': activeTab.value === SbMode.View,
          }}>
            <input
              type="radio"
              name={`example-editor-${dateID}`}
              value={SbMode.View}
              checked={activeTab.value === SbMode.View}
              onChange={onModeChange}
            />
            View mode
          </label>
          <label class={{
            'example-editor--mode-tab': true,
            'example-editor--mode-tab_checked': activeTab.value === "data",
          }}>
            <input
              type="radio"
              name={`example-editor-${dateID}`}
              value="data"
              checked={activeTab.value === "data"}
              onChange={onModeChange}
            />
            JSON Data structure
          </label>
        </div>
        {displayedElement.value}
      </div>;
    };
  },
});
