<template>
    <div :class="cx('root')" v-bind="ptmi('root')">
        <div :class="cx('controls')" v-bind="ptm('controls')">
            <slot name="controlsstart"></slot>
            <Button @click="moveUp" :aria-label="moveUpAriaLabel" :disabled="moveDisabled()" v-bind="{ ...buttonProps, ...moveUpButtonProps }" :pt="ptm('pcMoveUpButton')" :unstyled="unstyled">
                <slot name="moveupicon">
                    <AngleUp v-bind="ptm('pcMoveUpButton')['icon']" data-pc-section="moveupicon" />
                </slot>
            </Button>
            <Button @click="moveTop" :aria-label="moveTopAriaLabel" :disabled="moveDisabled()" v-bind="{ ...buttonProps, ...moveTopButtonProps }" :pt="ptm('pcMoveTopButton')" :unstyled="unstyled">
                <slot name="movetopicon">
                    <AngleDoubleUp v-bind="ptm('pcMoveTopButton')['icon']" data-pc-section="movetopicon" />
                </slot>
            </Button>
            <Button @click="moveDown" :aria-label="moveDownAriaLabel" :disabled="moveDisabled()" v-bind="{ ...buttonProps, ...moveDownButtonProps }" :pt="ptm('pcMoveDownButton')" :unstyled="unstyled">
                <slot name="movedownicon">
                    <AngleDown v-bind="ptm('pcMoveDownButton')['icon']" data-pc-section="movedownicon" />
                </slot>
            </Button>
            <Button @click="moveBottom" :aria-label="moveBottomAriaLabel" :disabled="moveDisabled()" v-bind="{ ...buttonProps, ...moveBottomButtonProps }" :pt="ptm('pcMoveBottomButton')" :unstyled="unstyled">
                <slot name="movebottomicon">
                    <AngleDoubleDown v-bind="ptm('pcMoveBottomButton')['icon']" data-pc-section="movebottomicon" />
                </slot>
            </Button>
            <slot name="controlsend"></slot>
        </div>
        <Listbox
            ref="listbox"
            :id="$id"
            :modelValue="d_selection"
            :options="modelValue"
            multiple
            :metaKeySelection="metaKeySelection"
            :listStyle="listStyle"
            :scrollHeight="scrollHeight"
            :tabindex="tabindex"
            :dataKey="dataKey"
            :autoOptionFocus="autoOptionFocus"
            :focusOnHover="focusOnHover"
            :striped="striped"
            :disabled="disabled"
            :filter="filter"
            :filterPlaceholder="filterPlaceholder"
            :filterLocale="filterLocale"
            :filterMatchMode="filterMatchMode"
            :filterFields="filterFields"
            :filterMessage="filterMessage"
            :emptyFilterMessage="emptyFilterMessage"
            :emptyMessage="emptyMessage"
            :ariaLabel="ariaLabel"
            :ariaLabelledby="ariaLabelledby"
            @focus="onListFocus"
            @blur="onListBlur"
            @change="onChangeSelection"
            @filter="onFilter"
            :pt="ptm('pcListbox')"
            :unstyled="unstyled"
        >
            <template v-if="$slots.header" #header>
                <slot name="header"></slot>
            </template>
            <template v-if="$slots.filtericon" #filtericon>
                <slot name="filtericon"></slot>
            </template>
            <template #option="{ option, selected, index }">
                <slot name="option" :item="option" :option="option" :selected="selected" :index="index" />
            </template>
            <template v-if="$slots.empty" #empty>
                <slot name="empty"></slot>
            </template>
            <template v-if="$slots.emptyfilter" #emptyfilter>
                <slot name="emptyfilter"></slot>
            </template>
            <template v-if="$slots.footer" #footer>
                <slot name="footer" :value="modelValue"></slot>
            </template>
        </Listbox>
    </div>
</template>

<script>
import AngleDoubleDown from '@primeicons/vue/angle-double-down';
import AngleDoubleUp from '@primeicons/vue/angle-double-up';
import AngleDown from '@primeicons/vue/angle-down';
import AngleUp from '@primeicons/vue/angle-up';
import { setAttribute } from '@primeuix/utils/dom';
import { findIndexInList } from '@primeuix/utils/object';
import Button from 'primevue/button';
import Listbox from 'primevue/listbox';
import Ripple from 'primevue/ripple';
import BaseOrderList from './BaseOrderList.vue';

export default {
    name: 'OrderList',
    extends: BaseOrderList,
    inheritAttrs: false,
    emits: ['update:modelValue', 'reorder', 'update:selection', 'selection-change', 'focus', 'blur', 'filter'],
    itemTouched: false,
    reorderDirection: null,
    styleElement: null,
    data() {
        return {
            d_selection: this.selection
        };
    },
    beforeUnmount() {
        this.destroyStyle();
    },
    updated() {
        if (this.reorderDirection) {
            this.updateListScroll();
            this.reorderDirection = null;
        }
    },
    mounted() {
        if (this.responsive) {
            this.createStyle();
        }
    },
    methods: {
        updateSelection(event) {
            this.$emit('update:selection', this.d_selection);
            this.$emit('selection-change', {
                originalEvent: event,
                value: this.d_selection
            });
        },
        onChangeSelection(params) {
            this.d_selection = params.value;
            this.updateSelection(params.event);
        },
        onListFocus(event) {
            this.$emit('focus', event);
        },
        onListBlur(event) {
            this.$emit('blur', event);
        },
        onFilter(event) {
            this.$emit('filter', event);
        },
        onReorderUpdate(event, value) {
            this.$emit('update:modelValue', value);
            this.$emit('reorder', {
                originalEvent: event,
                value: value,
                direction: this.reorderDirection
            });
        },
        moveUp(event) {
            if (this.d_selection) {
                let value = [...this.modelValue];
                const sortedSelection = this.sortByIndexInList(this.d_selection, value);

                for (let selectedItem of sortedSelection) {
                    let selectedItemIndex = findIndexInList(selectedItem, value);

                    if (selectedItemIndex > 0 && findIndexInList(value[selectedItemIndex - 1], this.d_selection) === -1) {
                        let movedItem = value[selectedItemIndex];
                        let temp = value[selectedItemIndex - 1];

                        value[selectedItemIndex - 1] = movedItem;
                        value[selectedItemIndex] = temp;
                    }
                }

                this.reorderDirection = 'up';
                this.onReorderUpdate(event, value);
            }
        },
        moveTop(event) {
            if (this.d_selection) {
                let value = [...this.modelValue];
                const sortedSelection = this.sortByIndexInList(this.d_selection, value).reverse();

                for (let selectedItem of sortedSelection) {
                    let selectedItemIndex = findIndexInList(selectedItem, value);

                    if (selectedItemIndex !== 0) {
                        let movedItem = value.splice(selectedItemIndex, 1)[0];

                        value.unshift(movedItem);
                    }
                }

                this.reorderDirection = 'top';
                this.onReorderUpdate(event, value);
            }
        },
        moveDown(event) {
            if (this.d_selection) {
                let value = [...this.modelValue];
                const sortedSelection = this.sortByIndexInList(this.d_selection, value).reverse();

                for (let selectedItem of sortedSelection) {
                    let selectedItemIndex = findIndexInList(selectedItem, value);

                    if (selectedItemIndex < value.length - 1 && findIndexInList(value[selectedItemIndex + 1], this.d_selection) === -1) {
                        let movedItem = value[selectedItemIndex];
                        let temp = value[selectedItemIndex + 1];

                        value[selectedItemIndex + 1] = movedItem;
                        value[selectedItemIndex] = temp;
                    }
                }

                this.reorderDirection = 'down';
                this.onReorderUpdate(event, value);
            }
        },
        moveBottom(event) {
            if (this.d_selection) {
                let value = [...this.modelValue];
                const sortedSelection = this.sortByIndexInList(this.d_selection, value);

                for (let selectedItem of sortedSelection) {
                    let selectedItemIndex = findIndexInList(selectedItem, value);

                    if (selectedItemIndex !== value.length - 1) {
                        let movedItem = value.splice(selectedItemIndex, 1)[0];

                        value.push(movedItem);
                    }
                }

                this.reorderDirection = 'bottom';
                this.onReorderUpdate(event, value);
            }
        },
        sortByIndexInList(items, list) {
            return [...items].sort((a, b) => findIndexInList(a, list) - findIndexInList(b, list));
        },
        updateListScroll() {
            if (!this.$refs.listbox || !this.d_selection || !this.d_selection.length) {
                return;
            }

            const indexes = this.d_selection.map((item) => findIndexInList(item, this.modelValue));
            const targetIndex = this.reorderDirection === 'up' || this.reorderDirection === 'top' ? Math.min(...indexes) : Math.max(...indexes);

            this.$refs.listbox.scrollInView(targetIndex);
        },
        createStyle() {
            if (!this.styleElement && !this.isUnstyled) {
                this.styleElement = document.createElement('style');
                this.styleElement.type = 'text/css';
                setAttribute(this.styleElement, 'nonce', this.$primevue?.config?.csp?.nonce);
                document.head.appendChild(this.styleElement);

                let innerHTML = `
@media screen and (max-width: ${this.breakpoint}) {
    .p-orderlist[${this.$attrSelector}] {
        flex-direction: column;
    }

    .p-orderlist[${this.$attrSelector}] .p-orderlist-controls {
        flex-direction: row;
    }
}
`;

                this.styleElement.innerHTML = innerHTML;
            }
        },
        destroyStyle() {
            if (this.styleElement) {
                document.head.removeChild(this.styleElement);
                this.styleElement = null;
            }
        },
        moveDisabled() {
            return this.disabled ? true : !this.d_selection || !this.d_selection.length ? true : false;
        }
    },
    computed: {
        moveUpAriaLabel() {
            return this.$primevue.config.locale.aria ? this.$primevue.config.locale.aria.moveUp : undefined;
        },
        moveTopAriaLabel() {
            return this.$primevue.config.locale.aria ? this.$primevue.config.locale.aria.moveTop : undefined;
        },
        moveDownAriaLabel() {
            return this.$primevue.config.locale.aria ? this.$primevue.config.locale.aria.moveDown : undefined;
        },
        moveBottomAriaLabel() {
            return this.$primevue.config.locale.aria ? this.$primevue.config.locale.aria.moveBottom : undefined;
        }
    },
    components: {
        Listbox,
        Button,
        AngleUp,
        AngleDown,
        AngleDoubleUp,
        AngleDoubleDown
    },
    directives: {
        ripple: Ripple
    }
};
</script>
