<!-- src/components/SubgroupTab.vue -->
<script setup>
import {ref, onMounted} from 'vue'
import {useAuthStore} from '@/stores/Auth'
import AssignmentBoard from './AssignmentBoard.vue'

const auth = useAuthStore()
const loading = ref(true)

const bucket = ref([])
const managers = ref([])

onMounted(async () => {
  const {response, error} = await auth.getDistrictsAndSubgroupManagers()
  if (error) {
    console.error(error);
    return
  }

  const districts = response.data.districts
  const users = response.data.subManagers


  managers.value = users.map(u => ({
    ...u,
    districts: districts
        .filter(d => d.subgroup_manager_id === u.id)
        .map(d => ({id: d.id, name: d.name}))
  }))


  bucket.value = districts
      .filter(d => !d.subgroup_manager_id)
      .map(d => ({
        id: d.id,
        name: d.name,
        type: 'district-sub'
      }))

  loading.value = false
})

async function save({evt, managerId}) {
  const el = evt?.added?.element
  if (!el) return               // drag внутри списка

  try {
    await auth.assignSubgroupManager({
      district_id: el.id,
      subgroup_manager_id: managerId ?? null
    })
  } catch (e) {
    console.error(e)
    alert('Не удалось сохранить изменение')
  }
}
</script>

<template>
  <div v-if="loading" class="text-center py-5">
    <div class="spinner-border text-primary"/>
  </div>

  <AssignmentBoard
      v-else
      :bucket="bucket"
      :managers="managers"
      label="districts"
      type-class="sub"
      @change="save"
  />
</template>
