/**
 * Field template: Repeat Field
 */
Vue.component('form-repeat_field', {
    template: '#tmpl-wpuf-form-repeat_field',

    mixins: [
        wpuf_mixins.form_field_mixin,
        wpuf_mixins.add_form_field
    ],

    data() {
        return {
            showFieldPicker: false,
        }
    },

    computed: {
        editing_form_id: function () {
            return this.$store.state.editing_field_id;
        },

        action_button_classes: function () {
            return 'wpuf-px-3 wpuf-py-2 wpuf-text-sm wpuf-font-medium wpuf-rounded-md hover:wpuf-bg-green-700 wpuf-transition wpuf-duration-150 wpuf-ease-out hover:wpuf-transition-all';
        },
    },

    mounted() {
        this.initializeSortable();
    },

    methods: {
        initializeSortable() {
            var self = this;
            var sortableFields = $(self.$el).find('.wpuf-repeat-fields-sortable-list');

            // bind jquery ui sortable
            $(sortableFields).sortable({
                placeholder: 'form-preview-stage-dropzone',
                items: '.repeat-field-items',
                handle: '.wpuf-repeat-field-control-buttons .move',
                scroll: true,
                stop: function( event, ui ) {
                    var item        = ui.item[0];
                    var data        = item.dataset;
                    var data_source = data.source;

                    if ('panel' === data_source) {
                        var payload = {
                            toIndex: parseInt($(ui.item).index()),
                            field_template: data.formField,
                            to_repeat_field: self.field.id
                        };

                        self.add_repeat_inner_field(payload);

                        // remove button from stage
                        $(this).find('.wpuf-field-button').remove();
                    }
                },
                update: function (e, ui) {
                    var item    = ui.item[0],
                        data    = item.dataset,
                        source  = data.source,
                        toIndex = parseInt($(ui.item).index()),
                        payload = {
                            toIndex: toIndex
                        };

                    if ( 'repeat-field-stage' === source) {
                        payload.field_id   = self.field.id;
                        payload.fromIndex  = parseInt(item.attributes['repeat-field-index'].value);
                        payload.toIndex    = toIndex;

                        self.$store.commit('swap_repeat_field_elements', payload);
                    }
                }
            });
        },

        is_full_width: function (template) {
            if (this.$store.state.field_settings[template] && this.$store.state.field_settings[template].is_full_width) {
                return true;
            }
            return false;
        },

        is_failed_to_validate: function (template) {
            // TODO: Implement validation check
            return false;
        },

        get_field_name: function (template) {
            return this.$store.state.field_settings[template] ? this.$store.state.field_settings[template].title : template;
        },

        is_pro_preview: function (template) {
            return !!( this.$store.state.field_settings[template] && this.$store.state.field_settings[template].is_pro_preview );
        },

        pro_link: function () {
            return wpuf_admin_script.pro_link || '#';
        },

        open_inner_field_settings(innerField, idx) {
            var self = this,
                payload = {
                    field_id: self.field.id,
                    repeat_field: innerField,
                    index: idx
                };
            self.$store.commit('open_repeat_field_settings', payload);
        },

        clone_inner_field(innerField, idx) {
            var self = this,
                payload = {
                    field_id: self.field.id,
                    repeat_field_id: innerField.id,
                    index: idx,
                    new_id: self.get_random_id()
                };

            // check if the field is allowed
            if ( this.isSingleInstance( field_template ) && this.containsField( field_template ) ) {
                Swal.fire({
                    title: '<span class="wpuf-text-primary">Oops...</span>',
                    html: '<p class="wpuf-text-gray-500 wpuf-text-xl wpuf-m-0 wpuf-p-0">You already have this field in the form</p>',
                    imageUrl: wpuf_form_builder.asset_url + '/images/oops.svg',
                    showCloseButton: true,
                    padding: '1rem',
                    width: '35rem',
                    customClass: {
                        confirmButton: "!wpuf-flex focus:!wpuf-shadow-none !wpuf-bg-primary",
                        closeButton: "wpuf-absolute"
                    },
                });
                return;
            }

            self.$store.commit('clone_repeat_inner_field_element', payload);
        },
        delete_inner_field(idx) {
            var self = this,
                payload = {
                    field_id: self.field.id,
                    index: idx
                };

            const icon_delete = wpuf_admin_script.asset_url + '/images/delete-icon-rounded.svg';
            const delete_icon_html = '<img src="' + icon_delete + '" alt="delete">';

            (Swal.fire({
                title: self.i18n.delete_field_warn_title,
                html: '<span class="wpuf-text-gray-500 wpuf-font-medium">' + self.i18n.delete_field_warn_msg + '</span>',
                iconHtml: delete_icon_html,
                showCancelButton: true,
                confirmButtonText: self.i18n.yes_delete_it,
                cancelButtonText: self.i18n.no_cancel_it,
                cancelButtonColor: '#fff',
                confirmButtonColor: '#EF4444',
                reverseButtons: true
            })).then((result) => {
                if (result.isConfirmed) {
                    self.$store.commit('delete_repeat_inner_field_element', payload);
                }
            });
        },

        isAllowedInRepeatField(field_template) {
            var allowedFields = [
                'text_field',
                'textarea_field',
                'dropdown_field',
                'multiple_select',
                'radio_field',
                'checkbox_field',
                'website_url',
                'date_field',
                'phone_field',
                'numeric_text_field',
                'email_address',
                // 'country_list_field',
                // 'image_upload',
                // 'file_upload'
            ];

            return $.inArray(field_template, allowedFields) >= 0;
        },

        openFieldPicker(e) {
            if (e) e.stopPropagation();
            this.showFieldPicker = true;
        },
        closeFieldPicker(e) {
            if (e) e.stopPropagation();
            this.showFieldPicker = false;
        },
        addInnerFieldFromPicker(fieldType) {
            // Create a new field object with default settings
            var fieldSettings = this.$store.state.field_settings[fieldType];
            if (!fieldSettings) return;
            var field = $.extend(true, {}, fieldSettings.field_props);
            field.id = this.get_random_id();
            // Set a unique name if needed
            if ('yes' === field.is_meta && !field.name && field.label) {
                field.name = field.label.replace(/\W/g, '_').toLowerCase();
                field.name += '_' + this.get_random_id();
            }
            if (!this.field.inner_fields) {
                this.$set(this.field, 'inner_fields', []);
            }
            this.field.inner_fields.push(field);
            this.showFieldPicker = false;
        },
        add_repeat_inner_field(data) {
            var payload = {
                toWhichRepeatField: this.field.id,
                toWhichRepeatFieldMeta: this.field.name,
                toIndex: data.toIndex
            };

            if (!this.isAllowedInRepeatField(data.field_template)) {
                Swal.fire({
                    title: '<span class="wpuf-text-primary">Oops...</span>',
                    html: '<p class="wpuf-text-gray-500 wpuf-text-xl wpuf-m-0 wpuf-p-0">This field type is not supported in repeat field\n</p>',
                    imageUrl: wpuf_form_builder.asset_url + '/images/oops.svg',
                    showCloseButton: true,
                    padding: '1rem',
                    width: '35rem',
                    customClass: {
                        confirmButton: "!wpuf-flex focus:!wpuf-shadow-none !wpuf-bg-primary",
                        closeButton: "wpuf-absolute"
                    },
                });
                return;
            }


            // check if these are already inserted
            if ( this.isSingleInstance( data.field_template ) && this.containsField( data.field_template ) ) {
                Swal.fire({
                    title: "Oops...",
                    text: "You already have this field in the form"
                });
                return;
            }

            // check if these are already inserted
            if ( this.isSingleInstance( data.field_template ) && this.containsField( data.field_template ) ) {
                Swal.fire({
                    title: '<span class="wpuf-text-primary">Oops...</span>',
                    html: '<p class="wpuf-text-gray-500 wpuf-text-xl wpuf-m-0 wpuf-p-0">You already have this field in the form</p>',
                    imageUrl: wpuf_form_builder.asset_url + '/images/oops.svg',
                    showCloseButton: true,
                    padding: '1rem',
                    width: '35rem',
                    customClass: {
                        confirmButton: "!wpuf-flex focus:!wpuf-shadow-none !wpuf-bg-primary",
                        closeButton: "wpuf-absolute"
                    },
                });
                return;
            }

            var field = $.extend(true, {}, this.$store.state.field_settings[data.field_template].field_props),
            form_fields = this.$store.state.form_fields;

            field.id = this.get_random_id();

            if ('yes' === field.is_meta && !field.name && field.label) {
                field.name = field.label.replace(/\W/g, '_').toLowerCase();

                var same_template_fields = form_fields.filter(function (form_field) {
                    return (form_field.template === field.template);
                });

                if (same_template_fields) {
                    field.name += '_' + this.get_random_id();
                }
            }

            payload.field = field;

            // add new form element
            this.$store.commit('add_repeat_inner_field_element', payload);

            // Trigger field initialization after adding new field
            this.$nextTick(function() {
                this.initializeRepeatFieldComponents();
            }.bind(this));
        },

        /**
         * Initialize field components that require JavaScript plugins
         * This is called after new fields are added to repeat fields
         */
        initializeRepeatFieldComponents: function() {
            var self = this;

            // Wait for DOM to be updated
            setTimeout(function() {
                // Check if WPUF_Field_Initializer is available
                if (typeof window.WPUF_Field_Initializer !== 'undefined' && typeof window.WPUF_Field_Initializer.reinitialize === 'function') {
                    window.WPUF_Field_Initializer.reinitialize();
                }

                // Also trigger a custom event for any other initialization needs
                $(document).trigger('wpuf-repeat-field-updated', [self.$el]);
            }, 100);
        },
    }
});
