(function($) {
    'use strict';

    $.fn.garmayevDynamicForm = function(options) {
        var settings = $.extend({
            itemsContainer: '.dynamic-items-container',
            itemClass: '.dynamic-form-item',
            addButtonSelector: '.btn-add-dynamic-item',
            removeButtonSelector: '.btn-remove-dynamic-item',
            templateSelector: '.dynamic-form-template',
            relation: 'items',
            relationType: 'many-to-many',
            allowRemoveLast: true,
            modelFormName: 'Template'
        }, options);

        return this.each(function() {
            var $widget = $(this);

            if ($widget.data('dynamic-form-initialized')) {
                return;
            }

            var $container = $widget.find(settings.itemsContainer);
            var $template = $widget.find(settings.templateSelector);
            console.log(settings.templateSelector);
            if (!$template.length) {
                console.error('Template not found for relation:', settings.relation);
                return;
            }

            // Получаем HTML шаблона (уже чистый, без значений)
            var templateHtml = $template.html();

            var isHasOne = settings.relationType === 'has-one';

            if (isHasOne) {
                return;
            }

            function updateIndexes() {
                $container.find(settings.itemClass).each(function(index) {
                    var $item = $(this);
                    $item.attr('data-index', index);

                    var $title = $item.find('.card-title');
                    if ($title.length) {
                        var text = $title.text();
                        $title.text(text.replace(/#\d+/, '#' + (index + 1)));
                    }

                    $item.find('input, select, textarea').each(function() {
                        var $input = $(this);
                        var name = $input.attr('name');
                        var id = $input.attr('id');

                        if (name) {
                            // Template[buttons][0][value] -> Template[buttons][newIndex][value]
                            var newName = name.replace(/\]\[(\d+)\]\[/, '][' + index + '][');
                            $input.attr('name', newName);
                        }

                        if (id) {
                            var newId = id.replace(/-\d+-/, '-' + index + '-');
                            $input.attr('id', newId);
                        }
                    });

                    $item.find('label').each(function() {
                        var $label = $(this);
                        var forAttr = $label.attr('for');
                        if (forAttr) {
                            var newFor = forAttr.replace(/-\d+-/, '-' + index + '-');
                            $label.attr('for', newFor);
                        }
                    });
                });
            }

            function addNewItem(event) {
                if (event) {
                    event.preventDefault();
                    event.stopPropagation();
                }

                var currentItems = $container.find(settings.itemClass);
                var newIndex = currentItems.length;

                // Используем чистый шаблон без значений
                var newHtml = templateHtml
                    .replace(/__INDEX__/g, newIndex)
                    .replace(/__INDEX_PLUS_ONE__/g, newIndex + 1)
                    .replace(/__RELATION__/g, settings.relation)
                    .replace(/__MODEL_FORM_NAME__/g, settings.modelFormName);

                // Заменяем [__INDEX__] на [newIndex] в именах полей
                newHtml = newHtml.replace(/\[__INDEX__\]/g, '[' + newIndex + ']');

                var $newItem = $(newHtml);

                if (!$newItem.length) {
                    console.error('Failed to create new item from template');
                    return false;
                }

                // Убеждаемся, что все поля пустые
                $newItem.find('input, select, textarea').each(function() {
                    var $input = $(this);
                    var tagName = $input.prop('tagName').toLowerCase();
                    var type = $input.attr('type');

                    if (tagName === 'select') {
                        $input.val('');
                    } else if (tagName === 'input') {
                        if (type === 'checkbox' || type === 'radio') {
                            $input.prop('checked', false);
                        } else {
                            $input.val('');
                        }
                    } else if (tagName === 'textarea') {
                        $input.val('');
                    }
                });

                $container.append($newItem);
                updateIndexes();
                $widget.trigger('itemAdded', [$newItem, newIndex]);

                return false;
            }

            function removeItem(event) {
                if (event) {
                    event.preventDefault();
                    event.stopPropagation();
                }

                var $button = $(this);
                var $item = $button.closest(settings.itemClass);
                var index = $item.data('index');
                var $items = $container.find(settings.itemClass);
                var itemsCount = $items.length;

                if (itemsCount > 1) {
                    $item.remove();
                    updateIndexes();
                    $widget.trigger('itemRemoved', [index]);
                } else {
                    $item.find('input, select, textarea').each(function() {
                        var $input = $(this);
                        var tagName = $input.prop('tagName').toLowerCase();
                        var type = $input.attr('type');

                        if (tagName === 'select') {
                            $input.val('');
                        } else if (tagName === 'input') {
                            if (type === 'checkbox' || type === 'radio') {
                                $input.prop('checked', false);
                            } else {
                                $input.val('');
                            }
                        } else if (tagName === 'textarea') {
                            $input.val('');
                        }
                    });
                    $widget.trigger('itemCleared', [$item]);
                }

                return false;
            }

            // Привязываем события
            $widget.off('click.dynamicForm');
            $widget.on('click.dynamicForm', settings.addButtonSelector, addNewItem);
            $widget.on('click.dynamicForm', settings.removeButtonSelector, removeItem);

            updateIndexes();
            $widget.data('dynamic-form-initialized', true);
        });
    };
})(jQuery);