{% extends 'base.html' %}
{% load static %}
{% load inventory_filters %}

{% block title %}Трансформация {{ transformation.document_number }}{% endblock %}

{% block content %}
<!-- CSS для компонента поиска -->
<link rel="stylesheet" href="{% static 'products/css/product-search-picker.css' %}">
<link rel="stylesheet" href="{% static 'inventory/transformation_detail.css' %}">

<div class="container-fluid px-4 py-3">
    <!-- Breadcrumbs -->
    <nav aria-label="breadcrumb" class="mb-2">
        <ol class="breadcrumb breadcrumb-sm mb-0">
            <li class="breadcrumb-item"><a href="{% url 'inventory:transformation-list' %}">Трансформации</a></li>
            <li class="breadcrumb-item active">{{ transformation.document_number }}</li>
        </ol>
    </nav>

    <!-- Messages -->
    {% if messages %}
    {% for message in messages %}
    <div class="alert alert-{{ message.tags }} alert-dismissible fade show" role="alert">
        {{ message }}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    {% endfor %}
    {% endif %}

    <div class="row g-3">
        <!-- Основной контент - одна колонка -->
        <div class="col-12">
            <!-- Информация о трансформации -->
            <div class="card border-0 shadow-sm mb-3">
                <div class="card-header bg-light py-3 d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">
                        <i class="bi bi-arrow-repeat me-2"></i>{{ transformation.document_number }}
                        {% if transformation.status == 'draft' %}
                        <span class="badge bg-warning text-dark ms-2">Черновик</span>
                        {% elif transformation.status == 'completed' %}
                        <span class="badge bg-success ms-2">Проведён</span>
                        {% elif transformation.status == 'cancelled' %}
                        <span class="badge bg-secondary ms-2">Отменён</span>
                        {% endif %}
                    </h5>
                    {% if transformation.status == 'draft' %}
                    <div class="btn-group">
                        <form method="post" action="{% url 'inventory:transformation-confirm' transformation.pk %}" class="d-inline">
                            {% csrf_token %}
                            <button type="submit" class="btn btn-success btn-sm" {% if not transformation.inputs.exists or not transformation.outputs.exists %}disabled{% endif %}>
                                <i class="bi bi-check-lg me-1"></i>Провести
                            </button>
                        </form>
                        <form method="post" action="{% url 'inventory:transformation-cancel' transformation.pk %}" class="d-inline ms-2">
                            {% csrf_token %}
                            <button type="submit" class="btn btn-outline-danger btn-sm" onclick="return confirm('Отменить трансформацию?')">
                                <i class="bi bi-x-lg me-1"></i>Отменить
                            </button>
                        </form>
                    </div>
                    {% elif transformation.status == 'completed' %}
                    <div class="btn-group">
                        <form method="post" action="{% url 'inventory:transformation-cancel' transformation.pk %}" class="d-inline">
                            {% csrf_token %}
                            <button type="submit" class="btn btn-outline-danger btn-sm" onclick="return confirm('Отменить проведенную трансформацию? Операции будут отменены.')">
                                <i class="bi bi-x-lg me-1"></i>Отменить
                            </button>
                        </form>
                    </div>
                    {% endif %}
                </div>
                <div class="card-body">
                    <div class="row mb-3">
                        <div class="col-md-3">
                            <p class="text-muted small mb-1">Склад</p>
                            <p class="fw-semibold">{{ transformation.warehouse.name }}</p>
                        </div>
                        <div class="col-md-3">
                            <p class="text-muted small mb-1">Дата</p>
                            <p class="fw-semibold">{{ transformation.date|date:"d.m.Y H:i" }}</p>
                        </div>
                        <div class="col-md-3">
                            <p class="text-muted small mb-1">Создан</p>
                            <p class="fw-semibold">{{ transformation.created_at|date:"d.m.Y H:i" }}</p>
                        </div>
                        <div class="col-md-3">
                            <p class="text-muted small mb-1">Сотрудник</p>
                            <p class="fw-semibold">{% if transformation.employee %}{{ transformation.employee.name|default:transformation.employee.email }}{% else %}-{% endif %}</p>
                        </div>
                    </div>

                    {% if transformation.comment %}
                    <div class="mb-0">
                        <p class="text-muted small mb-1">Комментарий</p>
                        <p>{{ transformation.comment }}</p>
                    </div>
                    {% endif %}
                </div>
            </div>

            <!-- ДВА виджета поиска товаров -->
            {% if transformation.status == 'draft' %}
            <div class="row g-3 mb-3 align-items-stretch">
                <!-- Карточка для входящего товара -->
                <div class="col-md-6">
                    <div class="card border-0 shadow-sm h-100 d-flex flex-column transformation-picker">
                        <div class="card-header bg-warning bg-opacity-10 py-3">
                            <h6 class="mb-0"><i class="bi bi-box-arrow-in-down me-2"></i>Добавить входящий товар (для списания)</h6>
                        </div>
                        <div class="card-body flex-grow-1 d-flex flex-column overflow-hidden">
                            <!-- Компонент поиска С фильтрацией по наличию -->
                            {% include 'products/components/product_search_picker.html' with container_id='transformation-input-picker' title='Найти товар в наличии' warehouse_id=transformation.warehouse.id categories=categories tags=tags add_button_text='Добавить во входящий' content_height='200px' %}
                        </div>
                        <!-- Поле количества и кнопка всегда видимы внизу карточки -->
                        <div class="card-footer bg-transparent border-top">
                            <div class="row g-3 align-items-end">
                                <div class="col-md-8">
                                    <label for="input-quantity" class="form-label">Количество</label>
                                    <input type="number" class="form-control" id="input-quantity" value="1" min="0.001" step="0.001">
                                </div>
                                <div class="col-md-4">
                                    <button type="button" id="confirm-add-input-btn" class="btn btn-warning w-100">
                                        <i class="bi bi-plus-circle me-1"></i>Добавить
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Карточка для исходящего товара -->
                <div class="col-md-6">
                    <div class="card border-0 shadow-sm h-100 d-flex flex-column transformation-picker">
                        <div class="card-header bg-success bg-opacity-10 py-3">
                            <h6 class="mb-0"><i class="bi bi-box-arrow-up me-2"></i>Добавить исходящий товар (для получения)</h6>
                        </div>
                        <div class="card-body flex-grow-1 d-flex flex-column overflow-hidden">
                            <!-- Компонент поиска БЕЗ фильтрации по наличию (skip_stock_filter=True) -->
                            {% include 'products/components/product_search_picker.html' with container_id='transformation-output-picker' title='Найти товар (даже если нет на складе)' warehouse_id=transformation.warehouse.id skip_stock_filter=True categories=categories tags=tags add_button_text='Добавить в исходящий' content_height='200px' %}
                        </div>
                        <!-- Поле количества и кнопка всегда видимы внизу карточки -->
                        <div class="card-footer bg-transparent border-top">
                            <div class="row g-3 align-items-end">
                                <div class="col-md-8">
                                    <label for="output-quantity" class="form-label">Количество</label>
                                    <input type="number" class="form-control" id="output-quantity" value="1" min="0.001" step="0.001">
                                    <small id="output-quantity-hint" class="form-text" style="display: none;"></small>
                                </div>
                                <div class="col-md-4">
                                    <button type="button" id="confirm-add-output-btn" class="btn btn-success w-100">
                                        <i class="bi bi-plus-circle me-1"></i>Добавить
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            {% endif %}

            <!-- ДВЕ КОЛОНКИ рядом -->
            <div class="row g-3 mb-3">
                <!-- ЛЕВАЯ КОЛОНКА: Входные товары -->
                <div class="col-md-5">
                    <div class="card border-0 shadow-sm h-100" style="border-left: 4px solid #ffc107 !important;">
                        <div class="card-header bg-warning bg-opacity-10 py-3">
                            <h6 class="mb-0">
                                <i class="bi bi-box-arrow-in-down me-2 text-warning"></i>
                                Входной товар (списание)
                            </h6>
                        </div>
                        <div class="card-body p-0">
                            <div class="table-responsive">
                                <table class="table table-hover mb-0">
                                    <thead class="table-light">
                                        <tr>
                                            <th scope="col" class="px-3 py-2">Товар</th>
                                            <th scope="col" class="px-3 py-2 text-end" style="width: 120px;">Кол-во</th>
                                            {% if transformation.status == 'draft' %}
                                            <th scope="col" class="px-3 py-2 text-end" style="width: 60px;"></th>
                                            {% endif %}
                                        </tr>
                                    </thead>
                                    <tbody id="input-products-tbody">
                                        {% for input in transformation.inputs.all %}
                                        <tr data-input-id="{{ input.pk }}">
                                            <td class="px-3 py-2">
                                                <a href="{% url 'products:product-detail' input.product.id %}">
                                                    {{ input.product.name }}
                                                </a>
                                                <small class="text-muted d-block">{{ input.product.sku }}</small>
                                            </td>
                                            <td class="px-3 py-2 text-end">{{ input.quantity|smart_quantity }}</td>
                                            {% if transformation.status == 'draft' %}
                                            <td class="px-3 py-2 text-end">
                                                <form method="post"
                                                      action="{% url 'inventory:transformation-remove-input' transformation.pk input.pk %}"
                                                      class="d-inline">
                                                    {% csrf_token %}
                                                    <button type="submit" class="btn btn-sm btn-outline-danger"
                                                            onclick="return confirm('Удалить?');">
                                                        <i class="bi bi-trash"></i>
                                                    </button>
                                                </form>
                                            </td>
                                            {% endif %}
                                        </tr>
                                        {% empty %}
                                        <tr class="empty-row">
                                            <td colspan="{% if transformation.status == 'draft' %}3{% else %}2{% endif %}"
                                                class="px-3 py-4 text-center text-muted">
                                                <i class="bi bi-inbox fs-3 d-block mb-2"></i>
                                                Нет товаров
                                            </td>
                                        </tr>
                                        {% endfor %}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- СТРЕЛКА посередине -->
                <div class="col-md-2 d-flex align-items-center justify-content-center">
                    <div class="text-center">
                        <i class="bi bi-arrow-right fs-1 text-primary d-none d-md-inline"></i>
                        <i class="bi bi-arrow-down fs-1 text-primary d-md-none"></i>
                        <div class="small text-muted mt-2">Трансформация</div>
                        {% if transformation.status == 'draft' %}
                        <div class="mt-3">
                            <div class="card border-0 shadow-sm">
                                <div class="card-body p-2">
                                    <div class="small text-muted mb-1">Баланс количеств</div>
                                    <div class="d-flex justify-content-between align-items-center mb-1">
                                        <span class="small">Вход:</span>
                                        <strong id="total-input-quantity" class="text-warning">
                                            {{ total_input_quantity|floatformat:3 }}
                                        </strong>
                                    </div>
                                    <div class="d-flex justify-content-between align-items-center">
                                        <span class="small">Выход:</span>
                                        <strong id="total-output-quantity" class="text-success">
                                            {{ total_output_quantity|floatformat:3 }}
                                        </strong>
                                    </div>
                                    <hr class="my-2">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <span class="small">Остаток:</span>
                                        <strong id="quantity-balance" class="{% if quantity_balance == 0 %}text-success{% elif quantity_balance > 0 %}text-warning{% else %}text-danger{% endif %}">
                                            {{ quantity_balance|floatformat:3 }}
                                        </strong>
                                    </div>
                                    <div id="balance-hint" class="small mt-2" style="font-size: 0.75rem;">
                                        {% if total_input_quantity == 0 %}
                                            <span class="text-muted">Добавьте входные товары</span>
                                        {% elif quantity_balance == 0 %}
                                            <span class="text-success"><i class="bi bi-check-circle"></i> Количества равны</span>
                                        {% elif quantity_balance > 0 %}
                                            <span class="text-info">Можно добавить еще: <strong>{{ quantity_balance|floatformat:3 }}</strong></span>
                                        {% else %}
                                            <span class="text-danger"><i class="bi bi-exclamation-triangle"></i> Превышение на {{ quantity_balance|floatformat:3|slice:"1:" }}</span>
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                        </div>
                        {% endif %}
                    </div>
                </div>

                <!-- ПРАВАЯ КОЛОНКА: Выходные товары -->
                <div class="col-md-5">
                    <div class="card border-0 shadow-sm h-100" style="border-left: 4px solid #198754 !important;">
                        <div class="card-header bg-success bg-opacity-10 py-3">
                            <h6 class="mb-0">
                                <i class="bi bi-box-arrow-up me-2 text-success"></i>
                                Исходящий товар (оприходование)
                            </h6>
                        </div>
                        <div class="card-body p-0">
                            <div class="table-responsive">
                                <table class="table table-hover mb-0">
                                    <thead class="table-light">
                                        <tr>
                                            <th scope="col" class="px-3 py-2">Товар</th>
                                            <th scope="col" class="px-3 py-2 text-end" style="width: 120px;">Кол-во</th>
                                            {% if transformation.status == 'draft' %}
                                            <th scope="col" class="px-3 py-2 text-end" style="width: 60px;"></th>
                                            {% endif %}
                                        </tr>
                                    </thead>
                                    <tbody id="output-products-tbody">
                                        {% for output in transformation.outputs.all %}
                                        <tr data-output-id="{{ output.pk }}">
                                            <td class="px-3 py-2">
                                                <a href="{% url 'products:product-detail' output.product.id %}">
                                                    {{ output.product.name }}
                                                </a>
                                                <small class="text-muted d-block">{{ output.product.sku }}</small>
                                            </td>
                                            <td class="px-3 py-2 text-end">{{ output.quantity|smart_quantity }}</td>
                                            {% if transformation.status == 'draft' %}
                                            <td class="px-3 py-2 text-end">
                                                <form method="post"
                                                      action="{% url 'inventory:transformation-remove-output' transformation.pk output.pk %}"
                                                      class="d-inline">
                                                    {% csrf_token %}
                                                    <button type="submit" class="btn btn-sm btn-outline-danger"
                                                            onclick="return confirm('Удалить?');">
                                                        <i class="bi bi-trash"></i>
                                                    </button>
                                                </form>
                                            </td>
                                            {% endif %}
                                        </tr>
                                        {% empty %}
                                        <tr class="empty-row">
                                            <td colspan="{% if transformation.status == 'draft' %}3{% else %}2{% endif %}"
                                                class="px-3 py-4 text-center text-muted">
                                                <i class="bi bi-inbox fs-3 d-block mb-2"></i>
                                                Нет товаров
                                            </td>
                                        </tr>
                                        {% endfor %}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Скрытые формы для AJAX отправки -->
            {% if transformation.status == 'draft' %}
            <form method="post"
                  action="{% url 'inventory:transformation-add-input' transformation.pk %}"
                  id="add-input-form"
                  style="display:none;">
                {% csrf_token %}
                <select name="product" id="hidden-input-product"></select>
                <input type="number" name="quantity" id="hidden-input-quantity" value="1" step="0.001">
            </form>

            <form method="post"
                  action="{% url 'inventory:transformation-add-output' transformation.pk %}"
                  id="add-output-form"
                  style="display:none;">
                {% csrf_token %}
                <select name="product" id="hidden-output-product"></select>
                <input type="number" name="quantity" id="hidden-output-quantity" value="1" step="0.001">
            </form>
            {% endif %}
        </div>
    </div>
</div>

<!-- JS для компонента поиска -->
<script src="{% static 'products/js/product-search-picker.js' %}"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    var selectedInputProduct = null;
    var selectedOutputProduct = null;
    var inputPicker = null;
    var outputPicker = null;

    // ========== ВХОДЯЩИЙ ТОВАР (с фильтрацией по наличию) ==========
    if (document.getElementById('transformation-input-picker')) {
        inputPicker = ProductSearchPicker.init('#transformation-input-picker', {
            onSelect: function(product, instance) {
                selectedInputProduct = product;
                // Focus on the quantity input when a product is selected
                setTimeout(function() {
                    var qtyInput = document.getElementById('input-quantity');
                    if (qtyInput) {
                        qtyInput.focus();
                        qtyInput.select();
                        qtyInput.onkeypress = function(e) {
                            if (e.key === 'Enter') {
                                e.preventDefault();
                                document.getElementById('confirm-add-input-btn').click();
                            }
                        };
                    }
                }, 100);
            },
            onDeselect: function(instance) {
                selectedInputProduct = null;
            }
        });
    }

    // ========== ИСХОДЯЩИЙ ТОВАР (БЕЗ фильтрации по наличию) ==========
    if (document.getElementById('transformation-output-picker')) {
        outputPicker = ProductSearchPicker.init('#transformation-output-picker', {
            onSelect: function(product, instance) {
                selectedOutputProduct = product;
                updateOutputQuantityHint();
                setTimeout(function() {
                    var qtyInput = document.getElementById('output-quantity');
                    if (qtyInput) {
                        qtyInput.focus();
                        qtyInput.select();
                        qtyInput.onkeypress = function(e) {
                            if (e.key === 'Enter') {
                                e.preventDefault();
                                document.getElementById('confirm-add-output-btn').click();
                            }
                        };
                        qtyInput.addEventListener('input', updateOutputQuantityHint);
                    }
                }, 100);
            },
            onDeselect: function(instance) {
                selectedOutputProduct = null;
            }
        });
    }

    // Функция обновления подсказки количества для исходящего товара
    function updateOutputQuantityHint() {
        var qtyInput = document.getElementById('output-quantity');
        var hint = document.getElementById('output-quantity-hint');
        var totalInputEl = document.getElementById('total-input-quantity');
        var totalOutputEl = document.getElementById('total-output-quantity');

        if (!qtyInput || !hint || !totalInputEl || !totalOutputEl) return;

        var qty = parseFloat(qtyInput.value) || 0;
        var totalInput = parseFloat(totalInputEl.textContent.replace(/\s/g, '').replace(',', '.'));
        var totalOutput = parseFloat(totalOutputEl.textContent.replace(/\s/g, '').replace(',', '.'));
        var newTotalOutput = totalOutput + qty;

        if (qty > 0 && totalInput > 0) {
            if (newTotalOutput > totalInput) {
                var maxAllowed = totalInput - totalOutput;
                hint.textContent = 'Максимум: ' + maxAllowed.toFixed(3) + ' (превышение!)';
                hint.className = 'form-text text-danger';
                hint.style.display = 'block';
            } else if (newTotalOutput === totalInput) {
                hint.textContent = 'Количества будут равны ✓';
                hint.className = 'form-text text-success';
                hint.style.display = 'block';
            } else {
                var remaining = totalInput - newTotalOutput;
                hint.textContent = 'Остаток после добавления: ' + remaining.toFixed(3);
                hint.className = 'form-text text-info';
                hint.style.display = 'block';
            }
        } else {
            hint.style.display = 'none';
        }
    }

    // ========== Кнопка "Добавить входящий товар" ==========
    var confirmAddInputBtn = document.getElementById('confirm-add-input-btn');
    if (confirmAddInputBtn) {
        confirmAddInputBtn.addEventListener('click', function() {
            if (!selectedInputProduct) {
                alert('Выберите товар для добавления');
                return;
            }

            var qtyInput = document.getElementById('input-quantity');
            var quantity = parseFloat(qtyInput.value);

            if (!quantity || quantity <= 0) {
                alert('Введите корректное количество (больше 0)');
                qtyInput.focus();
                return;
            }

            // Заполняем скрытую форму
            var productSelect = document.getElementById('hidden-input-product');
            productSelect.innerHTML = '<option value="' + selectedInputProduct.id + '">' +
                                      selectedInputProduct.text + '</option>';
            productSelect.value = selectedInputProduct.id;
            document.getElementById('hidden-input-quantity').value = quantity;

            // Отправляем форму через AJAX
            var form = document.getElementById('add-input-form');
            var formData = new FormData(form);

            fetch(form.action, {
                method: 'POST',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRFToken': formData.get('csrfmiddlewaretoken')
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    window.location.reload();
                } else {
                    alert('Ошибка: ' + data.error);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Ошибка при добавлении товара');
            });

            // Очищаем выбор
            if (inputPicker) inputPicker.clearSelection();
            selectedInputProduct = null;
            qtyInput.value = 1;
        });
    }

    // ========== Кнопка "Добавить исходящий товар" ==========
    var confirmAddOutputBtn = document.getElementById('confirm-add-output-btn');
    if (confirmAddOutputBtn) {
        confirmAddOutputBtn.addEventListener('click', function() {
            if (!selectedOutputProduct) {
                alert('Выберите товар для добавления');
                return;
            }

            var qtyInput = document.getElementById('output-quantity');
            var quantity = parseFloat(qtyInput.value);

            if (!quantity || quantity <= 0) {
                alert('Введите корректное количество (больше 0)');
                qtyInput.focus();
                return;
            }

            // Проверяем баланс количеств
            var totalInputEl = document.getElementById('total-input-quantity');
            var totalOutputEl = document.getElementById('total-output-quantity');
            if (totalInputEl && totalOutputEl) {
                var totalInput = parseFloat(totalInputEl.textContent.replace(/\s/g, '').replace(',', '.'));
                var totalOutput = parseFloat(totalOutputEl.textContent.replace(/\s/g, '').replace(',', '.'));
                var newTotalOutput = totalOutput + quantity;

                if (newTotalOutput > totalInput) {
                    var maxAllowed = totalInput - totalOutput;
                    alert('Сумма выходных количеств не может превышать сумму входных количеств.\n' +
                          'Вход: ' + totalInput + '\n' +
                          'Выход (текущий): ' + totalOutput + '\n' +
                          'Максимально можно добавить: ' + maxAllowed.toFixed(3));
                    qtyInput.focus();
                    qtyInput.select();
                    return;
                }
            }

            // Заполняем скрытую форму
            var productSelect = document.getElementById('hidden-output-product');
            productSelect.innerHTML = '<option value="' + selectedOutputProduct.id + '">' +
                                      selectedOutputProduct.text + '</option>';
            productSelect.value = selectedOutputProduct.id;
            document.getElementById('hidden-output-quantity').value = quantity;

            // Отправляем форму через AJAX
            var form = document.getElementById('add-output-form');
            var formData = new FormData(form);

            fetch(form.action, {
                method: 'POST',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRFToken': formData.get('csrfmiddlewaretoken')
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    window.location.reload();
                } else {
                    alert('Ошибка: ' + data.error);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Ошибка при добавлении товара');
            });

            // Очищаем выбор
            if (outputPicker) outputPicker.clearSelection();
            selectedOutputProduct = null;
            qtyInput.value = 1;
        });
    }
});
</script>
{% endblock %}
