<div class="col-md-12">
    <!-- Page Heading -->
    <div class="row">
        <h4 class="c-grey-900 mT-10 mB-30">{{ $title }}</h4>
    </div>

    @include('admin.layouts.errors')

    @include('admin.layouts.notifications')

    <div class="row">
        <div class="col-md-8">
            <div class="bgc-white bd bdrs-3 p-20 mB-20">
                <form action="{{ $route }}" method="POST" id="faq-form">
                    @csrf

                    @if(isset($method))
                        @method($method)
                    @endif

                    <!-- Product -->
                    <div class="mb-3">
                        <div class="form-group">
                            <label for="product_id" class="form-label">Select Product</label>
                            <select class="form-control" id="product_id" name="product_id">
                                <option value="">Global FAQs</option>
                                @foreach($products as $product)
                                    <option value="{{ $product->id }}" {{ isset($product_id) && $product->id == $product_id ? 'selected' : '' }}>{{ $product->name }}</option>
                                @endforeach
                            </select>
                            @error('product_id')
                            <div class="text-danger">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>

                    <!-- Accordion for Question-Answer pairs -->
                    <div class="mb-3">
                        <div class="accordion mb-3" id="faqAccordion">
                            <!-- FAQ items will be dynamically inserted here -->
                        </div>

                        <!-- Add New Question Button -->
                        <button type="button" class="btn btn-primary" id="add-faq">Add New Question</button>
                    </div>

                    <!-- Submission Buttons -->
                    <div>
                        <a href="{{ route('ch-admin.kb.faqs.index') }}" class="btn btn-secondary">Cancel</a>
                        <button class="btn btn-primary">Submit</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

@push('scripts')
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const faqItemTemplate = (index, faqId = '', question = '', answer = '', open = false) => `
            <div class="accordion-item" id="faq-${index}">
                <h2 class="accordion-header" id="heading-${index}">
                    <button class="accordion-button${open ? '' : ' collapsed'}" type="button" data-bs-toggle="collapse" data-bs-target="#collapse-${index}" aria-expanded="${open ? 'true' : 'false'}" aria-controls="collapse-${index}">
                        ${question || 'Question'}
                    </button>
                </h2>
                <div id="collapse-${index}" class="accordion-collapse collapse${open ? ' show' : ''}" aria-labelledby="heading-${index}" data-bs-parent="#faqAccordion">
                    <div class="accordion-body">
                        <!-- Only add the ID input for existing FAQs -->
                        ${faqId ? `<input type="hidden" name="faqs[${index}][id]" value="${faqId}">` : ''}

                        <div class="mb-3">
                            <label class="form-label">Question</label>
                            <input type="text" class="form-control" name="faqs[${index}][question]" value="${question}" data-faq-index="${index}">
                        </div>
                        <div class="mb-3">
                            <label for="faqs[${index}][answer]" class="form-label">Answer</label>
                            <textarea class="form-control" name="faqs[${index}][answer]" rows="3">${answer}</textarea>
                        </div>
                        <button type="button" class="btn btn-danger remove-faq">Remove</button>
                    </div>
                </div>
            </div>
        `;

            let faqCount = {{ count($faqs ?? []) ?: 0 }};
            let faqAccordionItem = 0;
            const faqsData = @json($faqs ?? []);
            const faqAccordionContainer = document.getElementById('faqAccordion');

            // Function to populate the accordion with the existing FAQs
            function populateAccordion() {
                // Iterate over the faqsData array and create an accordion item for each FAQ
                faqsData.forEach((faq, index) => {
                    faqAccordionContainer.insertAdjacentHTML('beforeend', faqItemTemplate(index, faq.id, faq.question, faq.answer, index === 0));
                    faqCount++;
                    faqAccordionItem++;
                });
                toggleRemoveButton();
            }

            if (faqsData.length === 0) {
                console.log("No FAQs available.");
                faqAccordionContainer.innerHTML = faqItemTemplate(faqCount);
                faqCount++;
                faqAccordionItem++;
                toggleRemoveButton();
            } else {
                console.log("There are " + faqsData.length + " FAQs.");
                populateAccordion();
            }

            // Event listener for adding new FAQ
            document.getElementById('add-faq').addEventListener('click', function () {
                // Close all currently open accordions
                const allCollapses = faqAccordionContainer.querySelectorAll('.accordion-collapse');
                const allButtons = faqAccordionContainer.querySelectorAll('.accordion-button');
                allCollapses.forEach(collapse => {
                    collapse.classList.remove('show');
                });
                allButtons.forEach(btn => {
                    btn.classList.add('collapsed');
                    btn.setAttribute('aria-expanded', 'false');
                });

                faqCount++;
                faqAccordionItem++;
                // Add the new item as open
                faqAccordionContainer.insertAdjacentHTML('beforeend', faqItemTemplate(faqCount, '', '', '', true));
                toggleRemoveButton();
            });

            // Event delegation for remove button
            document.getElementById('faqAccordion').addEventListener('click', function (event) {
                if (event.target.classList.contains('remove-faq')) {
                    const faqItem = event.target.closest('.accordion-item');
                    faqItem.remove();
                    faqAccordionItem--;
                    toggleRemoveButton();
                }
            });

            // Function to toggle visibility of the remove button
            function toggleRemoveButton() {
                const removeButtons = document.querySelectorAll('.remove-faq');
                removeButtons.forEach(button => {
                    button.style.display = faqAccordionItem > 1 ? 'inline-block' : 'none';
                });
            }

            // Event listener for question input fields to update the accordion button
            faqAccordionContainer.addEventListener('input', function (event) {
                if (event.target.matches('input[name^="faqs"][name$="[question]"]')) {
                    const index = event.target.dataset.faqIndex;
                    const accordionButton = document.querySelector(`#heading-${index} .accordion-button`);
                    // Update the button's text with the question value
                    accordionButton.textContent = event.target.value || 'Question';
                }
            });
        });
    </script>
@endpush
