<template>
  <div class="add-employee-modal">
    <div class="mb-4">
      <label class="block text-sm font-medium text-gray-700">Выберите сотрудников</label>
    </div>
    <MultiSelect
        v-model="selectedEmployeeIds"
        :options="employeesWithFullName"
        optionLabel="fullName"
        optionValue="id"
        placeholder="Выберите сотрудников"
        class="w-full"
        display="chip"
        :maxSelectedLabels="3"
        :filter="true"
    >
      <template #chip></template>
      <template #removetokenicon></template>
      <template #dropdownicon>
        <DropdownIcon />
      </template>
      <template #option="{ option }">
        <div class="d-flex align-items-center gap-2">
          <img v-if="option.user_logo" :src="`https://joywork.ru/photos/agency/${option.user_logo}`"
               class="emp-avatar" alt="">
          <div v-else class="emp-avatar text-center">{{ getInitials(option) }}</div>
          <span class="align-self-center">{{ option.fullName }}</span>
        </div>
      </template>
    </MultiSelect>
    <div class="mt-4 flex justify-center">
      <button @click="handleSelect" class="p-2 rounded add-employee-btn">
        Выбрать
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, inject, watch, computed } from 'vue';
import MultiSelect from 'primevue/multiselect';
import DropdownIcon from "@/shared/assets/icons/dropdown-icon.vue";

const dialogRef = inject('dialogRef');
const props = dialogRef.value.data;

const selectedEmployeeIds = ref([]);

const employeesWithFullName = computed(() => {
  return (props.employees || []).map(employee => ({
    ...employee,
    fullName: `${employee.last_name} ${employee.first_name} ${employee.middle_name}` || employee.fio,
  }));
});

watch(() => props.selected, (newSelected) => {
  selectedEmployeeIds.value = newSelected.map(employee => employee.id);
}, { immediate: true });

const handleSelect = () => {
  const selectedEmployeeObjects = selectedEmployeeIds.value
      .map(id => props.employees.find(employee => employee.id === id))
      .filter(employee => employee !== undefined);

  dialogRef.value.close(selectedEmployeeObjects);
};

const getInitials = (emp) => {
  const last = (emp.last_name || '').charAt(0);
  const first = (emp.first_name || '').charAt(0);
  return (last + first).toUpperCase() || '?';
};

const getEmployeeById = (id) => {
  return employeesWithFullName.value.find(e => e.id === id);
};
</script>

<style>
.add-employee-modal {
  padding: 4px;

  .p-multiselect {
    height: auto;
  }

  .add-employee-btn {
    background: #64A853;
    color: #fff;
    border: none;
    cursor: pointer;
    border-radius: 6px;
    padding: 10px 32px;
    font-size: 14px;
  }
}

.emp-avatar {
  width: 32px;
  height: 32px;
  min-width: 32px;
  border-radius: 50%;
  object-fit: cover;
  background-color: #e0e0e0;
  color: #666;
  font-size: 11px;
  font-weight: 600;
  line-height: 32px;
  text-align: center;
}
</style>
