/* global Drupal */

import { registerBlockType } from '@wordpress/blocks';
import { dispatch, select } from '@wordpress/data';
import { RichText, useBlockProps } from '@wordpress/block-editor';

const __ = Drupal.t;

const settings = {
  apiVersion: 3,
  title: __('Field'),
  description: __('Field block.'),
  icon: 'editor-textcolor',
  attributes: {
    tag: {
      type: 'string',
      default: 'h1',
    },
    text: {
      type: 'string',
    },
    mappingField: {
      type: 'string',
    },
    mappingAttribute: {
      type: 'string',
    },
    placeholder: {
      type: 'string',
      default: __('Insert text'),
    },
  },

  edit({ attributes, setAttributes }) {
    const blockProps = useBlockProps();
    const { text, tag, placeholder } = attributes;
    return (
      <div {...blockProps}>
        <RichText
          tagName={tag}
          value={text}
          placeholder={placeholder}
          onChange={(newValue) => setAttributes({ text: newValue })}
        />
      </div>
    );
  },

  save({ attributes }) {
    const { text } = attributes;
    return text;
  },

  deprecated: [
    {
      attributes: {
        tag: {
          type: 'string',
          default: 'h1',
        },
        text: {
          type: 'string',
        },
        mappingField: {
          type: 'string',
        },
        mappingAttribute: {
          type: 'string',
        },
        placeholder: {
          type: 'string',
          default: 'Insert text',
        },
      },
      save({ attributes }) {
        const { text } = attributes;
        return text;
      },
    },
  ],
};

const category = {
  slug: 'drupal',
  title: __('Drupal'),
};

const currentCategories = select('core/blocks')
  .getCategories()
  .filter((item) => item.slug !== category.slug);
dispatch('core/blocks').setCategories([...currentCategories, category]);

registerBlockType(`${category.slug}/field`, {
  category: category.slug,
  ...settings,
});
