<div class="ui inverted grey two column grid segment">
    <div class="column">
        COMENTARIOS
    </div>
    <div class="right aligned column">
        <button class="ui icon button" style="background: none; color: inherit; padding: 0;" id="add_comentario_button">
            <i class="plus icon"></i>
        </button>
    </div>
</div>
<div class="ui segment">
    <table class="ui very basic table">
        <tbody id="comentarios"></tbody>
    </table>
</div>
<div class="ui modal" id="addComment">
    <div class="header">
        Agregar Comentario
    </div>
    <div class="content">
        <form class="ui form">
            <div class="three wide field">
                <label>Fecha</label>
                <div class="ui calendar" id="fecha">
                    <div class="ui icon input">
                        <input type="text" placeholder="Fecha">
                        <i class="calendar icon"></i>
                    </div>
                </div>
            </div>
            <div class="field">
                <label>Comentario</label>
                <textarea id="comentario" rows="2"></textarea>
            </div>
        </form>
    </div>
    <div class="actions">
        <div class="ui black deny button">
            Cancelar
        </div>
        <div class="ui positive right labeled icon button">
            Agregar
            <i class="checkmark icon"></i>
        </div>
    </div>
</div>
<div class="ui modal" id="editComment">
    <div class="header">
        Edit Comentario
    </div>
    <div class="content">
        <form class="ui form">
            <input type="hidden" name="id" />
            <div class="three wide field">
                <label>Fecha</label>
                <div class="ui calendar" id="fechaEdit">
                    <div class="ui icon input">
                        <input type="text" placeholder="Fecha">
                        <i class="calendar icon"></i>
                    </div>
                </div>
            </div>
            <div class="field">
                <label>Comentario</label>
                <textarea id="comentarioEdit" rows="2"></textarea>
            </div>
        </form>
    </div>
    <div class="actions">
        <div class="ui black deny button">
            Cancelar
        </div>
        <div class="ui positive right labeled icon button">
            Editar
            <i class="checkmark icon"></i>
        </div>
    </div>
</div>

@push('page_scripts')
    <script type="text/javascript">
        class Comentario {
            id
            fecha
            texto

            constructor({id, fecha, texto})
            {
                this.id = id
                this.fecha = new Date(fecha + 'T00:00:00')
                this.texto = texto
            }
            draw(dateFormatter)
            {
                return [
                    '<tr>',
                        `<td class="collapsing">${dateFormatter.format(this.fecha)}</td>`,
                        `<td>${this.texto}</td>`,
                        '<td class="right aligned">',
                            `<button class="ui tiny tertiary icon button editComentario" data-id="${this.id}">`,
                                '<i class="edit icon"></i>',
                            '</button>',
                            `<button class="ui tiny tertiary red icon button removeComentario" data-id="${this.id}">`,
                                '<i class="minus icon"></i>',
                            '</button>',
                        '</td>',
                    '</tr>'
                ].join("\n")
            }
        }
        class AddModal {
            props
            constructor({id}) {
                this.props = {
                    id
                }
                $(this.props.id).modal({
                    onApprove: () => {
                        this.approve()
                    }
                })
                const cdo = structuredClone(calendar_date_options)
                $(this.props.id).find('.ui.calendar').calendar(cdo)
                this.hide()
            }
            approve() {
                const fecha = $(this.props.id).find('#fecha').calendar('get date')
                const fechaString = [fecha.getFullYear(), fecha.getMonth()+1, fecha.getDate()].join('-')
                const comentario = $(this.props.id).find('#comentario').val()
                const uri = '{{$urls->api}}/venta/{{$venta->id}}/comentarios/add'
                const body = new FormData()
                body.append('fecha', fechaString)
                body.append('texto', comentario)
                fetchAPI(uri, {method: 'post', body}).then(response => {
                    if (!response) {
                        return
                    }
                    return response.json().then(data => {
                        if (data.added) {
                            comentarios.comentarios.push(new Comentario(data.comentario))
                            comentarios.draw().comentarios()
                        }
                    })
                })
            }
            show() {
                const modal = $(this.props.id)
                modal.find('form').trigger('reset')
                modal.modal('show')
            }
            hide() {
                const modal = $(this.props.id)
                modal.modal('hide')
            }
        }
        class EditModal {
            props
            constructor({id}) {
                this.props = {
                    id
                }
                $(this.props.id).modal({
                    onApprove: () => {
                        this.approve()
                    }
                })
                const cdo = structuredClone(calendar_date_options)
                $(this.props.id).find('.ui.calendar').calendar(cdo)
                this.hide()
            }
            approve() {
                const id = $(this.props.id).find("[name='id']").val()
                const fecha = $(this.props.id).find('#fechaEdit').calendar('get date')
                const fechaString = [fecha.getFullYear(), fecha.getMonth()+1, fecha.getDate()].join('-')
                const comentario = $(this.props.id).find('#comentarioEdit').val()
                const uri = `{{$urls->api}}/ventas/comentario/${id}/edit`
                const body = new FormData()
                body.append('fecha', fechaString)
                body.append('texto', comentario)
                fetchAPI(uri, {method: 'post', body}).then(response => {
                    if (!response) {
                        return
                    }
                    return response.json().then(data => {
                        if (data.edited) {
                            const idx = comentarios.comentarios.findIndex(comentario => comentario.id === data.comentario_id)
                            comentarios.comentarios[idx] = new Comentario(data.comentario)
                            comentarios.draw().comentarios()
                        }
                    })
                })
            }
            show() {
                const modal = $(this.props.id)
                modal.modal('show')
            }
            hide() {
                const modal = $(this.props.id)
                modal.modal('hide')
            }
        }
        const comentarios = {
            comentarios: [],
            id: '',
            modals: {
                add: null,
                edit: null
            },
            fetch: function() {
                return {
                    comentarios: () => {
                        const uri = '{{$urls->api}}/venta/{{$venta->id}}/comentarios'
                        return fetchAPI(uri).then(response => {
                            if (response.ok) {
                                return response.json()
                            }
                        }).then(data => {
                            if (data.total === 0) {
                                return
                            }
                            data.comentarios.forEach(settings => {
                                this.comentarios.push(new Comentario(settings))
                            })
                            this.draw().comentarios()

                        })
                    }
                }
            },
            draw: function() {
                return {
                    comentarios: () => {
                        const body = $(this.id)
                        const dateFormatter = new Intl.DateTimeFormat('es-CL', {dateStyle: 'medium'})
                        body.html('')
                        this.comentarios.forEach(comentario => {
                            body.append(comentario.draw(dateFormatter))
                        })
                        $('.editComentario').on('click', event => {
                            const id = $(event.currentTarget).data('id')
                            const comentario = this.comentarios.find(comentario => comentario.id === id)
                            const modal = this.modals.edit
                            const fecha = new Date(comentario.fecha)
                            $(modal.props.id).find("[name='id']").val(id)
                            $(modal.props.id).find('#fechaEdit').calendar('set date', fecha)
                            $(modal.props.id).find('#comentarioEdit').val(comentario.texto)
                            modal.show()
                        })
                        $('.removeComentario').click(event => {
                            const id = $(event.currentTarget).data('id')
                            const uri = `{{$urls->api}}/ventas/comentario/${id}/remove`
                            fetchAPI(uri, {method: 'delete'}).then(response => {
                                if (!response) {
                                    return
                                }
                                return response.json().then(data => {
                                    if (data.removed) {
                                        this.comentarios = this.comentarios.filter(comentario => comentario.id !== id)
                                        this.draw().comentarios()
                                    }
                                })
                            })
                        })
                    }
                }
            },
            setup: function(id) {
                this.id = id
                this.modals.add = new AddModal({id: '#addComment'})
                this.modals.edit = new EditModal({id: '#editComment'})
                $('#add_comentario_button').click(() => {
                    this.modals.add.show()
                })
                this.fetch().comentarios()
            }
        }
        $(document).ready(() => {
            comentarios.setup('#comentarios')
        })
    </script>
@endpush
