<template>
  <UPopover v-if="sortingColumns.length > 0" v-model:open="isOpen">
    <UChip :ui="{ base: 'z-1 size-3' }" :show="model.length > 0" size="xl">
      <UButton
        variant="subtle"
        color="neutral"
        label="Сортировка"
        :icon="appConfig.ui.icons.sort"
      />
    </UChip>

    <template #content>
      <div class="flex flex-col gap-2 p-3">
        <URadioGroup
          :model-value="model[0]?.id ?? noSortColumn.value"
          :items="sortingColumns"
          @update:model-value="updateModel({ id: $event, desc: model[0]?.desc ?? false })"
        />

        <USeparator />

        <div class="flex gap-2">
          <UButton
            v-for="item in sortOrder"
            :key="item.icon"
            :icon="item.icon"
            :label="item.label"
            :disabled="!model[0]"
            :variant="item.desc === (model[0]?.desc ?? false) ? 'soft' : 'ghost'"
            size="sm"
            color="neutral"
            class="flex-1"
            @click="updateModel({ id: model[0]?.id ?? '', desc: item.desc })"
          />
        </div>
      </div>
    </template>
  </UPopover>
</template>

<script setup>
import { useAppConfig } from "#imports";
import { computed, ref } from "vue";
const props = defineProps({
  table: { type: Object, required: false }
});
const model = defineModel({ type: Array, ...{ default: [] } });
const appConfig = useAppConfig();
const noSortColumn = { label: "\u0411\u0435\u0437 \u0441\u043E\u0440\u0442\u0438\u0440\u043E\u0432\u043A\u0438", value: "null" };
const sortingColumns = computed(() => {
  if (!props.table) {
    return [];
  }
  const items = props.table.getAllColumns().filter((column) => column.columnDef.enableSorting).map((column) => {
    const label = column.columnDef.meta?.headerLabel ?? (typeof column.columnDef.header === "string" ? column.columnDef.header : column.columnDef.id);
    return {
      label,
      value: column.id
    };
  });
  items.length > 0 && items.unshift(noSortColumn);
  return items;
});
const sortOrder = [
  { icon: appConfig.ui.icons.sortAsc, label: "\u0410-\u042F", desc: false },
  { icon: appConfig.ui.icons.sortDesc, label: "\u042F-\u0410", desc: true }
];
function updateModel(value) {
  const currentSort = model.value[0];
  const shouldUpdate = currentSort?.id !== value.id || currentSort?.desc !== value.desc || value.id === noSortColumn.value && model.value.length > 0;
  if (!shouldUpdate) {
    return;
  }
  if (value.id === noSortColumn.value) {
    model.value = [];
    return;
  }
  model.value = [value];
}
const isOpen = ref(false);
</script>
