<div class="ui modal" id="add_connection_modal">
    <div class="header">
        Agregar
    </div>
    <div class="content">
        <form class="ui form" id="add_connection_form">
            <input type="hidden" name="promotion_id" value="{{$promotion->id}}" />
            <div class="field" id="type">
                <label>Tipo</label>
                @foreach (['Proyecto' => 'project', 'Operador' => 'broker', 'Tipo' => 'type', 'Línea' => 'line', 'Unidad' => 'unit'] as $type => $value)
                    <div class="ui radio checkbox type" data-tab="{{ $value }}">
                        <input type="radio" name="type" value="{{$value}}" @if ($value === 'project') checked="checked"@endif />
                        <label>{{$type}}</label>
                    </div>
                @endforeach
            </div>
            <div class="ui active tab segment" data-tab="project">
                <div class="field">
                    <label>Proyecto</label>
                    <div class="ui search multiple selection dropdown" id="project">
                        <input type="hidden" name="project[]" />
                        <i class="dropdown icon"></i>
                        <div class="default text">Proyecto</div>
                        <div class="menu">
                        @foreach ($projects as $project)
                            <div class="item" data-value="{{$project->id}}">{{$project->descripcion}}</div>
                        @endforeach
                        </div>
                    </div>
                </div>
            </div>
            <div class="ui tab segment" data-tab="broker">
                <div class="field">
                    <label>Operador</label>
                    <div class="ui search multiple selection dropdown" id="broker">
                        <input type="hidden" name="broker[]" />
                        <i class="dropdown icon"></i>
                        <div class="default text">Operador</div>
                        <div class="menu">
                        @foreach ($brokers as $broker)
                            <div class="item" data-value="{{$broker->rut}}">{{$broker->name}}</div>
                        @endforeach
                        </div>
                    </div>
                </div>
            </div>
            <div class="ui tab segment" data-tab="type">
                <div class="fields">
                    <div class="six wide field">
                        <label>Proyecto</label>
                        <div class="ui search selection dropdown" id="type_project">
                            <input type="hidden" name="type_project" />
                            <i class="dropdown icon"></i>
                            <div class="default text">Proyecto</div>
                            <div class="menu">
                            @foreach ($projects as $project)
                                <div class="item" data-value="{{$project->id}}">{{$project->descripcion}}</div>
                            @endforeach
                            </div>
                        </div>
                    </div>
                    <div class="six wide field">
                        <label>Tipo</label>
                        <div class="ui search multiple selection dropdown" id="unit_type">
                            <input type="hidden" name="unit_type[]" />
                            <i class="dropdown icon"></i>
                            <div class="default text">Tipo</div>
                            <div class="menu"></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="ui tab segment" data-tab="line">
                <div class="fields">
                    <div class="six wide field">
                        <label>Proyecto</label>
                        <div class="ui search selection dropdown" id="line_project">
                            <input type="hidden" name="line_project" />
                            <i class="dropdown icon"></i>
                            <div class="default text">Proyecto</div>
                            <div class="menu">
                            @foreach ($projects as $project)
                                <div class="item" data-value="{{$project->id}}">{{$project->descripcion}}</div>
                            @endforeach
                            </div>
                        </div>
                    </div>
                    <div class="six wide field">
                        <label>Línea</label>
                        <div class="ui search multiple selection dropdown" id="line">
                            <input type="hidden" name="line[]" />
                            <i class="dropdown icon"></i>
                            <div class="default text">Línea</div>
                            <div class="menu"></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="ui tab segment" data-tab="unit">
                <div class="fields">
                    <div class="six wide field">
                        <label>Proyecto</label>
                        <div class="ui search selection dropdown" id="unit_project">
                            <input type="hidden" name="unit_project" />
                            <i class="dropdown icon"></i>
                            <div class="default text">Proyecto</div>
                            <div class="menu">
                            @foreach ($projects as $project)
                                <div class="item" data-value="{{$project->id}}">{{$project->descripcion}}</div>
                            @endforeach
                            </div>
                        </div>
                    </div>
                    <div class="six wide field">
                        <label>Unidad</label>
                        <div class="ui search multiple selection dropdown" id="unit">
                            <input type="hidden" name="unit[]" />
                            <i class="dropdown icon"></i>
                            <div class="default text">Unidad</div>
                            <div class="menu"></div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
    <div class="actions">
        <div class="ui black deny button">
            Cancelar
        </div>
        <div class="ui positive right labeled icon button">
            Guardar
            <i class="checkmark icon"></i>
        </div>
    </div>
</div>

@push('page_scripts')
    <script>
        class AddModal {
            ids
            modal
            units = []
            constructor() {
                this.ids = {
                    form: 'add_connection_form',
                    modal: 'add_connection_modal',
                    radios: '#type .ui.radio.checkbox.type',
                    type_project: 'type_project',
                    unit_type: 'unit_type',
                    line_project: 'line_project',
                    line: 'line',
                    unit_project: 'unit_project',
                    unit: 'unit',
                    broker: 'broker'
                }
                this.modal = $(`#${this.ids.modal}`).modal({
                    onApprove: () => {
                        const form = document.getElementById(this.ids.form)
                        const body = new FormData(form)
                        const url = `{{$urls->api}}/ventas/promotion/{{$promotion->id}}/connections/add`
                        const method = 'post'
                        return APIClient.fetch(url, {method, body}).then(response => response.json()).then(json => {
                            if (json.success) {
                                window.location.reload()
                            }
                        })
                    }
                })
                $(`#${this.ids.form} ${this.ids.radios}`).checkbox({
                    fireOnInit: true,
                    onChecked: () => {
                        $(`#${this.ids.form} ${this.ids.radios}`).each((index, radio) => {
                            if ($(radio).checkbox('is checked')) {
                                const tab = radio.dataset.tab
                                $.tab('change tab', tab)
                            }
                        })
                    }
                })
                $('.ui.dropdown').dropdown()

                const typeProject = $(`#${this.ids.type_project}`)
                typeProject.dropdown('clear', false)
                typeProject.dropdown({
                    onChange: (value, text, $choice) => {
                        this.draw().types(value)
                    }
                })
                const lineProject = $(`#${this.ids.line_project}`)
                lineProject.dropdown('clear', false)
                lineProject.dropdown({
                    onChange: (value, text, $choice) => {
                        this.draw().lines(value)
                    }
                })
                const unitProject = $(`#${this.ids.unit_project}`)
                unitProject.dropdown('clear', false)
                unitProject.dropdown({
                    onChange: (value, text, $choice) => {
                        this.draw().units(value)
                    }
                })
            }
            show() {
                this.modal.modal('show')
            }
            draw() {
                return {
                    types: project_id => {
                        this.load().units(project_id).then(() => {
                            const values = []
                            this.units[project_id].forEach(unit => {
                                const tipo = unit.proyecto_tipo_unidad.tipo_unidad
                                if (values.find(value => value.value === tipo.id)) return
                                const label = `${tipo.descripcion.charAt(0).toUpperCase() + tipo.descripcion.slice(1)}`
                                values.push( {
                                    value: tipo.id,
                                    text: label,
                                    name: label
                                } )
                            })
                            $(`#${this.ids.unit_type}`).dropdown('change values', values)
                        })
                    },
                    lines: project_id => {
                        this.load().units(project_id).then(() => {
                            const values = []
                            this.units[project_id].forEach(unit => {
                                const tipo = unit.proyecto_tipo_unidad.tipo_unidad
                                const linea = unit.proyecto_tipo_unidad
                                if (values.find(value => value.value === linea.id)) return
                                let name = linea.nombre
                                if (!linea.nombre.includes(tipo.descripcion.charAt(0).toUpperCase() + tipo.descripcion.slice(1))) {
                                    name = `${tipo.descripcion.charAt(0).toUpperCase() + tipo.descripcion.slice(1)} ${name}`
                                }
                                const label = `${name} - ${linea.tipologia}`
                                values.push( {
                                    value: linea.id,
                                    text: label,
                                    name: label
                                } )
                            })
                            $(`#${this.ids.line}`).dropdown('change values', values)
                        })
                    },
                    units: project_id => {
                        this.load().units(project_id).then(() => {
                            const values = this.units[project_id].map(unit => {
                                const tipo = unit.proyecto_tipo_unidad.tipo_unidad.descripcion
                                const label = `${tipo.charAt(0).toUpperCase() + tipo.slice(1)} - ${unit.descripcion}`
                                return {
                                    value: unit.id,
                                    text: label,
                                    name: label
                                }
                            })
                            $(`#${this.ids.unit}`).dropdown('change values', values)
                        })
                    }
                }
            }
            load() {
                return {
                    units: project_id => {
                        if (typeof this.units[project_id] !== 'undefined' && this.units[project_id].length > 0) {
                            return new Promise( resolve => resolve(this.units[project_id]) )
                        }
                        const url = `{{ $urls->api }}/proyecto/${project_id}/unidades`
                        return APIClient.fetch(url).then(response => response.json()).then(json => {
                            if (json.unidades.length === 0) {
                                throw new Error('No se encontraron unidades')
                            }
                            const units = []
                            Object.values(json.unidades).forEach(unidades => {
                                unidades.forEach(unit => {
                                    units.push(unit)
                                })
                            })
                            this.units[project_id] = units
                            return units
                        })
                    }
                }
            }
        }
    </script>
@endpush
