<x-backend.model :id="'field-model'" class="lg:max-w-2xl" :button="'Submit'" :form_id="'pages-ui'" :action="route('pages.store')"
    :method="__('post')">
    @csrf
    <div class="p-4 sm:p-10 space-y-4">
        <div class="field space-y-2"></div>
        <div class="static space-y-2">
            <x-backend.input-label :value="'Number of displays'" for="dispaly" />
            <x-backend.input-field type="number" name="display" id="display" class="w-full" placeholder="Enter number" />
            <x-backend.input-label :value="'Quantity'" for="quantity" />
            <x-backend.input-select id="quantity" :values="['1', '2', '3', '4', '5', '6', '7', '8', '10', '11', '12']" :placeholder="'Select one'" selected='' />
        </div>
        <div class="sub-field space-y-2"></div>
    </div>

</x-backend.model>
<script>
    var globalFiled;
    $(document).ready(function() {
        $(document).on('click', '.add-field-value', function() {
            let data = $(this).attr('data');
            HSOverlay.open('#field-model');
            data = JSON.parse(data);
            $('#quantity')[0].selectedIndex = 0;
            $('#display').val('');

            let fileds = [];
            let sub_fileds = [];
            let group_fileds = [];
            let group = 1;
            let count = 0;
            let countfield = data.component_filed.filter((element) => {
                return element.group == 1;
            })

            fileds.push(`<input type="hidden" name='id' value='${data.id}'>`)
            globalFiled = countfield;
            textarea = '';
            data.component_filed.forEach(element => {
                if (element.group == null) {
                    if (element.type == "textarea") {
                        fileds.push(` <div class='list'>
                    <x-backend.input-label :value="'${element.name}'" for="${element.name}" />
                    <x-backend.input-textarea name="field_name[]"   :text="'${element.value ?? textarea}'" placeholder='Enter ${element.name}' required/>
                    <x-backend.input-field value='${element.id}' type="hidden" name="field_id[]"  
                        placeholder="''"   />
                        </div>`);
                    } else if (element.type == "file") {
                        fileds.push(` <div class='list'>
                    <x-backend.input-label :value="'${element.name}'" for="${element.name}" />
                  <input type="file"  name='field_image[]' />
                  <x-backend.input-field value='${element.id}' type="hidden" name="field_image_id[]"  
                        placeholder="''"   />
                        ${element.value ? `<img src="{{ asset('images/${element.value}') }}"" height="40" width="50" >` : '' }

                        </div>`);
                    } else {
                        fileds.push(` <div class='list'>
                    <x-backend.input-label :value="'${element.name}'" for="${element.name}" />
                    <x-backend.input-field type="${element.type}" name="field_name[]" value="${element.value ? element.value : '' }"   class="w-full"
                        placeholder="Enter ${element.name}"   required/>
                        <x-backend.input-field value='${element.id}' type="hidden" name="field_id[]"  
                        placeholder="''"   />
                        </div>`);
                    }
                }
                if (element.group != null) {
                    count++
                    group = element.group;
                    textarea = '';
                    if (element.type == "textarea") {
                        sub_fileds = sub_fileds + ` <div class='list'>
                    <x-backend.input-label :value="'${element.name}'" for="${element.name}" />
                    <x-backend.input-textarea   name="subfield[${element.group}][${element.name}]" :text="'${element.value ?? textarea}'" placeholder='Enter ${element.name}' required/>
                    <x-backend.input-field value='${element.id}' type="hidden" name="sub_field_id[]"  
                        placeholder="''"   />
                        </div>`;
                    } else if (element.type == "file") {
                        sub_fileds = sub_fileds + ` <div class='list'>
                    <x-backend.input-label :value="'${element.name}'" for="${element.name}" />
                  <input type="file"   name="subfield[${element.group}][${element.name}]"' />
                  <x-backend.input-field value='${element.id}' type="hidden" name="sub_field_id[]"  
                        placeholder="''"   />
                        ${element.value ? `<img src="{{ asset('images/${element.value}') }}"" height="40" width="50" >` : '' }
                        </div>`;
                    } else {
                        sub_fileds = sub_fileds + ` <div class='list'>
                    <x-backend.input-label :value="'${element.name}'" for="${element.name}" />
                    <x-backend.input-field type="${element.type}" name="subfield[${element.group}][${element.name}]"  class="w-full"
                        placeholder="Enter ${element.name}" value="${element.value ? element.value : '' }" required/>
                        <x-backend.input-field value='${element.id}' type="hidden" name="sub_field_id[]"  
                        placeholder="''"   />
                        </div>`;
                    }

                    if (group != element.group || count == countfield.length) {

                        element = `
                <div class="border clone rounded-md space-y-2">
                      <div class="bg-gray-100 p-3">
                         <button type='button' class="relative toggole  outline-none w-full  text-left  ">Group ${element.group}
                    <span class="absolute right-0 top-0 bottom-0 icone flex items-center">
                        <i class="fa-solid fa-plus"></i>
                    </span>
                </button>
                       </div>
                       <div class="content hidden p-3 space-y-3">
                       ${sub_fileds}
                           </div>

                     </div>
                        `
                        sub_fileds = [];
                        console.log(count);
                        count = 0;

                        group_fileds.push(element);


                    }

                    group = element.group;


                }

            });
            $('.field').html(fileds);
            $('.sub-field').html(group_fileds);
            // $('#component-edit').find('.add-database').html(sub_fileds);


        })
        //   Group Toggole 
        $(document).on('click', '.toggole', function() {
            let parentBorder = $(this).closest('.border');
            let content = parentBorder.find('.content');
            let icone = parentBorder.find('.icone');

            icone.html(content.css('display') == 'block' ? '<i class="fa-solid fa-plus"></i>' :
                '<i class="fa-solid fa-minus"></i>');
            content.slideToggle(200);
        });

        $(document).on('change', '#quantity', function() {
            let value = parseInt($(this).find('option:selected').text()); // Convert value to integer
            let originalElements = $('.clone'); // Original set of elements to clone from
            let clone = originalElements.clone(); // Clone the original elements

            let length = clone.length;
            if (globalFiled.length != 0) {


                if (length > value) {
                    clone = clone.slice(0, value); // Keep only the first 'value' elements
                    $('.sub-field').html(clone);
                } else if (length < value) {
                    let numToAdd = value - length;
                    let increment = length + 1;
                    let data = [];
                    for (let index = 0; index < numToAdd; index++) {
                        globalFiled.forEach(element => {
                            if (element.type == "textarea") {
                                data = data + ` <div class='list'>
                    <x-backend.input-label :value="'${element.name}'" for="${element.name}" />
                    <x-backend.input-textarea name="subfield[${increment}][${element.name}]" :text="''" placeholder='Enter ${element.name}' required/>
                        </div>`;
                            } else if (element.type == "file") {
                                data = data + ` <div class='list'>
                    <x-backend.input-label :value="'${element.name}'" for="${element.name}" />
                  <input type="file" name="subfield[${increment}][${element.name}]"/>
                        </div>`;
                            } else {
                                data = data + ` <div class='list'>
                    <x-backend.input-label :value="'${element.name}'" for="${element.name}" />
                    <x-backend.input-field type="${element.type}" name="subfield[${increment}][${element.name}]"  class="w-full"
                        placeholder="Enter ${element.name}"   required/>
                        </div>`;
                            }
                        });
                        element = `<div class="border clone rounded-md space-y-2">
            <div class="bg-gray-100 p-3">
                <button type='button' class="relative toggole  outline-none w-full  text-left  ">Group ${increment++}
                    <span class="absolute right-0 top-0 bottom-0 icone flex items-center">
                        <i class="fa-solid fa-plus"></i>
                    </span>
                </button>
            </div>
            <div class="content hidden p-3 space-y-3">
                ${data}
            </div>

        </div>`
                        $('.sub-field').append(element);
                        data = [];
                    }
                }
            }
            // Replace the contents of .sub-field with the updated clone
        });
        // Ui Element Store 
        $(document).on('submit', '#pages-ui', function(e) {
            e.preventDefault()
            let form = new FormData(this);
            // Append CSRF token to FormData object
            let thisElement = $(this)
            form.append('_token', $('input[name="_token"]').val());
            fetch('{{ route('add-ui') }}', {
                method: "post",
                credentials: "same-origin",
                body: form,
            }).then(function(response) {
                return response.json();
            }).then(function(json) {
                thisElement.find('.cancle').trigger('click')

                let data = [];
                // Field 
                json.component.forEach(element => {
                    data = data + ` <div
                class=" col-span-4 flex flex-col  w-60 bg-white border shadow-sm rounded-xl dark:bg-slate-900 dark:border-gray-700 dark:shadow-slate-700/[.7]">
                <div class="h-30  text-center">
                    <i class="fa-solid fa-code text-6xl text-gray-400 p-10"></i>
                </div>
                <div class="p-2 md:p-3 border-t-2">
                    <h3 class="text-lg text-gray-800 dark:text-white">
                        ${element.name}
                    </h3>
                    <p class="mt-1 text-gray-500 dark:text-gray-400 float-start">
                        ${element.name}
                    </p>
                    <span class=" float-right">
                        <a href="#" data='${JSON.stringify(element)}' type='button' 
                            class="${element.name+element.id} !py-1 !px-2 add-field-value inline-flex items-center gap-x-2 text-sm font-semibold rounded-lg border border-transparent bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-50 disabled:pointer-events-none">Use
                        </a>
                    </span>


                </div>
            </div>`

                });


                ui = `<div id='${json.item.name + json.item.id}'
                          class="flex flex-col bg-white component-parent border shadow-sm rounded-xl dark:bg-slate-900 dark:border-gray-700 dark:shadow-slate-700/[.7]">
                                    <div
                                        class="flex justify-between items-center border-b rounded-t-xl py-3 px-4 md:px-5 dark:border-gray-700">
                                        <h3 class="text-md  font-semibold text-gray-800 dark:text-white">
                                       ${json.item.name} 
                                        </h3>
                                        <input type="hidden" name='component_id[]' value='${json.item.id}' />
                                        <input type="hidden" id='limit' name='display[]' value='${json.item.display}' />

                                        <div class="flex items-center gap-x-1">
                                            <div class="hs-tooltip inline-block">
                                                <button type="button" target='${json.item.name+json.item.id}'
                                                    class="componet-edit hs-tooltip-toggle size-8 inline-flex justify-center items-center gap-x-2 text-sm font-semibold rounded-full border border-transparent text-gray-500 hover:bg-gray-100 disabled:opacity-50 disabled:pointer-events-none dark:text-gray-400 dark:hover:bg-gray-700 dark:focus:outline-none dark:focus:ring-1 dark:focus:ring-gray-600">
                                                    <i class="fa-solid fa-pen-to-square"></i>
                                                    <span
                                                        class="hs-tooltip-content hs-tooltip-shown:opacity-100 hs-tooltip-shown:visible opacity-0 transition-opacity inline-block absolute invisible z-10 py-1 px-2 bg-gray-900 text-xs font-medium text-white rounded shadow-sm dark:bg-slate-700"
                                                        role="tooltip">
                                                        Edit
                                                    </span>
                                                </button>
                                            </div>

                                            <div class="hs-tooltip inline-block">
                                                <button type="button"
                                                    class="hs-tooltip-toggle removeComonent size-8 inline-flex justify-center items-center gap-x-2 text-sm font-semibold rounded-full border border-transparent text-gray-500 hover:bg-gray-100 disabled:opacity-50 disabled:pointer-events-none dark:text-gray-400 dark:hover:bg-gray-700 dark:focus:outline-none dark:focus:ring-1 dark:focus:ring-gray-600">
                                                    <i class="fa-solid fa-xmark"></i>
                                                    <span
                                                        class="hs-tooltip-content hs-tooltip-shown:opacity-100 hs-tooltip-shown:visible opacity-0 transition-opacity inline-block absolute invisible z-10 py-1 px-2 bg-gray-900 text-xs font-medium text-white rounded shadow-sm dark:bg-slate-700"
                                                        role="tooltip">
                                                        Delete
                                                    </span>
                                                </button>
                                            </div>
                                        </div>
                                </div>
                            </div>`;
                if ($(".ui").find("#" + json.item.name + json.item.id).length == 0) {
                    $('.ui').append(ui);
                } else {
                    $(".ui").find("#" + json.item.name + json.item.id).replaceWith(ui);
                }






                $('.addComponent').html(data);


            })

        })


    });
</script>
