<template>
    <a
        v-if="formAreaNode && !error"
        href="#"
        :class="`ye-builder-icon-${icon}`"
        :title="title"
        :uk-tooltip="`delay: 1000; pos: ${tooltipDirection}`"
        @click.prevent="Form.openFormAreaSettings(formAreaNode)"
    ></a>

    <span
        v-else
        :class="`ye-builder-icon-${icon}`"
        :title="title"
        :uk-tooltip="`delay: 1000; pos: ${tooltipDirection}`"
    ></span>
</template>

<script>
import essentials from 'essentials';
import { flattenChildren } from '@essentials/core/util';

export default {
    name: 'FormAreaIcon',

    inject: {
        Form: {
            from: 'EssentialsForm',
        },
    },

    props: {
        node: {
            type: Object,
            required: true,
        },
        tooltipDirection: {
            type: String,
            default: 'bottom',
        },
    },

    computed: {
        icon() {
            let icon = 'form';

            if (this.error) {
                icon += '-error';
            }

            return icon;
        },

        title() {
            if (!this.error) {
                return this.$t('Form Area');
            }

            const errors = {
                'double-form-area': 'Duplicated Form Area',
                'field-outside-form-area': 'Outside Form Area',
                'field-duplicated-control': 'Duplicated Control Name',
            };

            return errors[this.error] || 'Invalid Form Area';
        },

        formAreaNode() {
            const { node } = this.node;

            const children = flattenChildren(node);
            const formAreas = [node, ...children].filter(
                (n) => n?.props?.yooessentials_form?.state
            );

            if (formAreas.length === 1) {
                return formAreas[0];
            }

            return null;
        },

        error() {
            const { node } = this.node;

            const children = flattenChildren(node);
            const formAreas = children.filter((n) => n.props?.yooessentials_form?.state);

            if (node?.type === 'section' && formAreas.length) {
                return 'double-form-area';
            }

            return essentials.FormModel.isInvalidField(node);
        },
    },
};
</script>
