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

const PAGE_SIZE = 20;

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

const {
  items: employees,
  filters,
  loading,
} = useModelApi(employeeApi, {
  defaultListParams: { ordering: "id", limit: PAGE_SIZE, offset: 0 } as EmployeeListParams,
  loadErrorMessage: "Не удалось загрузить сотрудников",
  cleanListParams: (params) => {
    if (!params.name__contains?.trim()) {
      delete params.name__contains;
    }
  },
});

const selectedEmployee = computed(() =>
  employees.value.find((employee) => employee.id === selectedEmployeeId.value),
);

const selectedEmployeeName = computed(() => selectedEmployee.value?.name ?? "не указан");

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

function selectEmployee(id: number) {
  selectedEmployeeId.value = id;
  showSelector.value = false;
}

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

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

  <van-popup v-model:show="showSelector" round position="bottom" class="employee-popup">
    <div class="employee-popup-header">
      <h2>Выберите сотрудника</h2>
      <van-button size="small" type="primary" plain @click="selectEmployee(0)">Не указан</van-button>
    </div>

    <div class="employee-popup-body">
      <van-search v-model="search" placeholder="Поиск по имени" />

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

      <template v-else>
        <van-cell-group inset>
          <van-cell
            v-for="employee in employees"
            :key="employee.id"
            :title="employee.name"
            :label="`ID: ${employee.id}`"
            clickable
            center
            @click="selectEmployee(employee.id)"
          >
            <template #icon>
              <RemoteImage class="employee-avatar" round width="36" height="36" :src="employee.avatar_small" />
            </template>
            <template #right-icon>
              <van-icon v-if="selectedEmployeeId === employee.id" name="success" color="#1989fa" />
            </template>
          </van-cell>
        </van-cell-group>

        <van-empty v-if="employees.length === 0" description="Сотрудники не найдены" />
      </template>
    </div>
  </van-popup>
</template>

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

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

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

.employee-avatar {
  margin-right: 10px;
}

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

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

.employee-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;
}

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