@extends('layouts.admin')

@section('title', 'Edit Tax')

@section('content')
<x-admin.form-page
    title="Edit Tax"
    :crumbs="[['label' => 'Taxes', 'url' => route('admin.taxes.index')], 'Edit']"
    :back-url="route('admin.taxes.index')"
    :action="route('admin.taxes.update', $tax->id)"
    method="PUT"
    form-id="taxForm"
    submit-label="Update Tax"
>
    <section class="pp-card">
        <div class="pp-card__head">
            <span class="pp-card__icon"><i class="bi bi-percent"></i></span>
            <div>
                <h2 class="pp-card__title">Tax Details</h2>
                <p class="pp-card__sub">Name, type and rate configuration</p>
            </div>
        </div>
        <div class="pp-card__body">
            <div class="pp-grid pp-grid--2">
                <div class="pp-field">
                    <label for="name">Tax Name <span class="pp-req">*</span></label>
                    <input type="text"
                           name="name"
                           id="name"
                           class="form-control @error('name') is-invalid @enderror"
                           value="{{ old('name', $tax->name) }}"
                           placeholder="e.g., GST, VAT, Sales Tax"
                           required
                           maxlength="255">
                    @error('name')<div class="invalid-feedback d-block">{{ $message }}</div>@enderror
                </div>

                <div class="pp-field">
                    <label for="taxType">Tax Type <span class="pp-req">*</span></label>
                    <select name="type"
                            id="taxType"
                            class="form-select no-select2 @error('type') is-invalid @enderror"
                            required>
                        <option value="">Select Type</option>
                        <option value="single" {{ old('type', $tax->type) === 'single' ? 'selected' : '' }}>Single</option>
                        <option value="multiple" {{ old('type', $tax->type) === 'multiple' ? 'selected' : '' }}>Multiple</option>
                    </select>
                    @error('type')<div class="invalid-feedback d-block">{{ $message }}</div>@enderror
                    <span class="pp-hint">Single: one tax rate · Multiple: multiple tax components</span>
                </div>
            </div>

            <div id="singleTaxSection" style="display: none;">
                <div class="pp-grid pp-grid--4 mt-3">
                    <div class="pp-field">
                        <label for="singleRate">Tax Rate (%) <span class="pp-req">*</span></label>
                        <input type="number"
                               name="rate"
                               id="singleRate"
                               step="0.01"
                               min="0"
                               max="100"
                               class="form-control @error('rate') is-invalid @enderror"
                               value="{{ old('rate', $tax->type === 'single' ? $tax->rate : '') }}"
                               placeholder="e.g., 18.00">
                        @error('rate')<div class="invalid-feedback d-block">{{ $message }}</div>@enderror
                    </div>
                </div>
            </div>

            <div id="multipleTaxSection" style="display: none;">
                <section class="pp-card mt-3">
                    <div class="pp-card__head">
                        <span class="pp-card__icon"><i class="bi bi-layers"></i></span>
                        <div>
                            <h2 class="pp-card__title">Tax Components</h2>
                            <p class="pp-card__sub">Add CGST, SGST, or other split rates</p>
                        </div>
                    </div>
                    <div class="pp-card__body">
                        <div id="taxComponentsContainer"></div>
                        <button type="button" class="pp-btn pp-btn--ghost mt-2" id="addTaxComponentBtn">
                            <i class="bi bi-plus-circle"></i> Add Tax Component
                        </button>
                    </div>
                </section>

                <div class="pp-grid pp-grid--4 mt-3">
                    <div class="pp-field">
                        <label for="totalRate">Total Tax Rate (%)</label>
                        <input type="number"
                               id="totalRate"
                               step="0.01"
                               readonly
                               disabled
                               class="form-control bg-light"
                               value="{{ old('rate', $tax->type === 'multiple' ? $tax->rate : '0.00') }}">
                        <span class="pp-hint">Auto-calculated from components above</span>
                    </div>
                </div>
            </div>

            <div class="pp-toggles mt-3">
                <label class="pp-toggle" for="isActive">
                    <input type="hidden" name="is_active" value="0">
                    <input type="checkbox"
                           name="is_active"
                           class="form-check-input"
                           role="switch"
                           id="isActive"
                           value="1"
                           {{ old('is_active', $tax->is_active) ? 'checked' : '' }}>
                    Active
                </label>
            </div>
        </div>
    </section>
</x-admin.form-page>

@push('scripts')
<script>
(function() {
    const taxTypeSelect = document.getElementById('taxType');
    const singleTaxSection = document.getElementById('singleTaxSection');
    const multipleTaxSection = document.getElementById('multipleTaxSection');
    const singleRateInput = document.getElementById('singleRate');
    const totalRateInput = document.getElementById('totalRate');
    const addTaxComponentBtn = document.getElementById('addTaxComponentBtn');
    const taxComponentsContainer = document.getElementById('taxComponentsContainer');

    let componentCount = 0;

    taxTypeSelect.addEventListener('change', function() {
        const type = this.value;

        if (type === 'single') {
            singleTaxSection.style.display = 'block';
            multipleTaxSection.style.display = 'none';
            singleRateInput.required = true;
            singleRateInput.disabled = false;
            singleRateInput.setAttribute('name', 'rate');
            totalRateInput.disabled = true;
            totalRateInput.removeAttribute('name');
        } else if (type === 'multiple') {
            singleTaxSection.style.display = 'none';
            multipleTaxSection.style.display = 'block';
            singleRateInput.required = false;
            singleRateInput.disabled = true;
            singleRateInput.removeAttribute('name');
            totalRateInput.disabled = false;
            totalRateInput.setAttribute('name', 'rate');
            totalRateInput.required = false;

            if (taxComponentsContainer.children.length === 0) {
                loadExistingComponents();
            }
        } else {
            singleTaxSection.style.display = 'none';
            multipleTaxSection.style.display = 'none';
            singleRateInput.required = false;
            singleRateInput.disabled = true;
            singleRateInput.removeAttribute('name');
            totalRateInput.disabled = true;
            totalRateInput.removeAttribute('name');
        }
    });

    if (taxTypeSelect.value) {
        taxTypeSelect.dispatchEvent(new Event('change'));
    }

    addTaxComponentBtn.addEventListener('click', function() {
        addTaxComponent();
    });

    function addTaxComponent(name = '', rate = '') {
        const componentId = componentCount++;
        const componentDiv = document.createElement('div');
        componentDiv.className = 'pp-grid pp-grid--3 tax-component-row mb-3';
        componentDiv.dataset.componentId = componentId;

        componentDiv.innerHTML = `
            <div class="pp-field">
                <input type="text"
                       name="components[${componentId}][name]"
                       class="form-control component-name"
                       placeholder="Tax Name (e.g., CGST, SGST)"
                       value="${name}"
                       required>
            </div>
            <div class="pp-field">
                <input type="number"
                       name="components[${componentId}][rate]"
                       class="form-control component-rate"
                       step="0.01"
                       min="0"
                       max="100"
                       placeholder="Rate (%)"
                       value="${rate}"
                       required>
            </div>
            <div class="pp-field">
                <button type="button" class="pp-btn pp-btn--ghost remove-component" data-component-id="${componentId}">
                    <i class="bi bi-trash"></i>
                </button>
            </div>
        `;

        taxComponentsContainer.appendChild(componentDiv);

        const removeBtn = componentDiv.querySelector('.remove-component');
        removeBtn.addEventListener('click', function() {
            componentDiv.remove();
            calculateTotalRate();
        });

        const rateInput = componentDiv.querySelector('.component-rate');
        rateInput.addEventListener('input', calculateTotalRate);
    }

    function loadExistingComponents() {
        @if(old('components'))
            const oldComponents = @json(old('components'));
            oldComponents.forEach((component, index) => {
                addTaxComponent(component.name || '', component.rate || '');
            });
        @elseif($tax->type === 'multiple' && !empty($tax->components))
            const existingComponents = @json($tax->components);
            existingComponents.forEach((component, index) => {
                addTaxComponent(component.name || '', component.rate || '');
            });
        @else
            addTaxComponent();
        @endif

        calculateTotalRate();
    }

    function calculateTotalRate() {
        const rateInputs = document.querySelectorAll('.component-rate');
        let total = 0;

        rateInputs.forEach(input => {
            const value = parseFloat(input.value) || 0;
            total += value;
        });

        totalRateInput.value = total.toFixed(2);
    }
})();
</script>
@endpush
@endsection
