import { registerBlockType } from '@wordpress/blocks';
import { InnerBlocks } from '@wordpress/block-editor';
import { GutenbergBlockEdit } from '@smx/ui/gutenberg';
import { blockScheduleAttributeDefinitions } from '@smx/ui';
import { COMPONENT_DEFINITIONS } from './generated/registry';

for (const definition of COMPONENT_DEFINITIONS) {
  registerBlockType(`smx/${definition.name}`, {
    title: definition.title,
    description: definition.description,
    category: definition.category === 'layout' ? 'smx-layout' : `smx-${definition.category}`,
    icon: definition.icon ?? 'screenoptions',
    attributes: {
      ...Object.fromEntries(definition.fields.map((field) => [
        field.name,
        {
          type: field.type === 'number'
            ? 'number'
            : field.type === 'boolean'
              ? 'boolean'
              : field.type === 'array'
                ? 'array'
                : field.type === 'image' || field.type === 'video' || field.type === 'link' || field.type === 'object'
                  ? 'object'
                  : 'string',
          default: field.defaultValue,
        },
      ])),
      ...blockScheduleAttributeDefinitions,
    },
    supports: {
      anchor: definition.supports?.anchor ?? true,
      className: definition.supports?.className ?? true,
      html: definition.name === 'rich-text',
    },
    edit: (props) => <GutenbergBlockEdit definition={definition} {...props} />,
    save: () => definition.supports?.innerBlocks ? <InnerBlocks.Content /> : null,
  });
}
