<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { contractCategoryApi } from "../../../generated/api";
import type { ContractCategoryListParams } from "../../../generated/models";
import { useModelApi } from "../../../shared/composables/useModelApi";

const PAGE_SIZE = 30;

const selectedCategoryId = defineModel<number>({ required: true });
const search = ref("");
const showSelector = ref(false);

const {
  items: categories,
  filters,
  loading,
} = useModelApi(contractCategoryApi, {
  defaultListParams: { ordering: "id", limit: PAGE_SIZE, offset: 0 } as ContractCategoryListParams,
  loadErrorMessage: "Не удалось загрузить категории",
  cleanListParams(params) {
    params.name__contains = params.name__contains?.trim() || undefined;
  },
});

const selectedCategory = computed(() =>
  categories.value.find((category) => category.id === selectedCategoryId.value),
);
const selectedCategoryName = computed(() => selectedCategory.value?.name ?? "все");

function openSelector() {
  search.value = "";
  showSelector.value = true;
}

function selectCategory(id: number) {
  selectedCategoryId.value = id;
  showSelector.value = false;
}

watch(search, (value) => {
  filters.name__contains = value.trim();
  filters.offset = 0;
});
</script>

<template>
  <button class="entity-select" type="button" @click="openSelector">
    <span>{{ selectedCategoryName }}</span>
    <van-icon name="arrow" />
  </button>

  <van-popup v-model:show="showSelector" round position="bottom" class="entity-popup">
    <div class="entity-popup-header">
      <h2>Выберите категорию</h2>
      <van-button size="small" type="primary" plain @click="selectCategory(0)">Все</van-button>
    </div>

    <div class="entity-popup-body">
      <van-search v-model="search" placeholder="Поиск по категории" />

      <van-loading v-if="loading" class="entity-state" type="spinner">Загрузка...</van-loading>

      <template v-else>
        <van-cell-group inset>
          <van-cell
            v-for="category in categories"
            :key="category.id"
            :title="category.name"
            :label="category.name_group || `ID: ${category.id}`"
            clickable
            center
            @click="selectCategory(category.id)"
          >
            <template #right-icon>
              <van-icon v-if="selectedCategoryId === category.id" name="success" color="#1989fa" />
            </template>
          </van-cell>
        </van-cell-group>

        <van-empty v-if="categories.length === 0" description="Категории не найдены" />
      </template>
    </div>
  </van-popup>
</template>

<style scoped>
.entity-popup {
  display: flex;
  flex-direction: column;
  height: 70vh;
  max-height: 70vh;
  overflow: hidden;
  padding: 18px 0 16px;
}

.entity-popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 0 18px 10px;
}

.entity-popup-header h2 {
  margin: 0;
  font-size: 18px;
}

.entity-state {
  display: flex;
  justify-content: center;
  padding: 36px 0;
}

.entity-popup-body {
  flex: 1;
  min-height: 0;
  overflow-y: auto;
}

.entity-select {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 4px;
  width: 100%;
  border: 0;
  padding: 0;
  color: #323233;
  background: transparent;
  font: inherit;
  line-height: 24px;
  text-align: right;
}

.entity-select .van-icon {
  color: #969799;
  font-size: 16px;
}
</style>
