<script setup>
import {onMounted, ref} from 'vue'
import SeniorTab   from './Assignment/SeniorTab.vue'
import GroupTab    from './Assignment/GroupTab.vue'
import SubgroupTab from './Assignment/SubgroupTab.vue'
import { useAuthStore }   from '@/stores/Auth'
/* вкладки */
const active = ref('sen')      // sen | group | sub | counter
const loaded = ref(false)

const bucketSen        = ref([])
const bucketGroup      = ref([])
const bucketSub        = ref([])

const seniorManagers   = ref([])
const groupManagers    = ref([])
const subgroupManagers = ref([])

const auth = useAuthStore()

onMounted(async () => {
  const [regRes, grpRes, subRes] = await Promise.all([
    auth.getRegionsAndSeniorManagers(),
    auth.getDistrictsForGroupAssignment(),
    auth.getDistrictsAndSubgroupManagers()
  ])

  const fio = m =>
      `${m.last_name ?? ''} ${m.first_name ?? ''} ${m.middle_name ?? ''}`.trim()

  /* 1 ─ региональные */
  seniorManagers.value = regRes.response.data.stManagers.map(m => ({
    ...m,
    fio: fio(m),
    regions: regRes.response.data.regions
        .filter(r => r.sen_manager_id === m.id)
        .map(r => ({ id: r.id, name: r.name }))
        .sort((a, b) => a.name.localeCompare(b.name, 'ru'))
  }))
      .sort((a, b) => a.fio.localeCompare(b.fio, 'ru'))
  bucketSen.value = regRes.response.data.regions
      .filter(r => !r.sen_manager_id)
      .map(r => ({ id: r.id, name: r.name, type: 'region' }))
      .sort((a, b) => a.name.localeCompare(b.name, 'ru'))

  /* 2 ─ групповые */
  groupManagers.value = grpRes.response.data.managers.map(m => ({
    ...m,
    fio: fio(m),
    districts: grpRes.response.data.districts
        .filter(d => d.group_manager_id === m.id)
        .map(d => ({ id: d.id, name: d.name, region: d.region.name }))
        .sort((a, b) => a.name.localeCompare(b.name, 'ru'))
  }))
      .sort((a, b) => a.fio.localeCompare(b.fio, 'ru'))

  bucketGroup.value = grpRes.response.data.districts
      .filter(d => !d.group_manager_id)
      .map(d => ({ id: d.id, name: d.name, region: d.region.name, type: 'district-group' }))
      .sort((a, b) => a.name.localeCompare(b.name, 'ru'))

  /* 3 ─ подгрупповые */
  subgroupManagers.value = subRes.response.data.subManagers.map(m => ({
    ...m,
    fio: fio(m),
    districts: subRes.response.data.districts
        .filter(d => d.subgroup_manager_id === m.id)
        .map(d => ({ id: d.id, name: d.name }))
        .sort((a, b) => a.name.localeCompare(b.name, 'ru'))
  }))
      .sort((a, b) => a.fio.localeCompare(b.fio, 'ru'))

  bucketSub.value = subRes.response.data.districts
      .filter(d => !d.subgroup_manager_id)
      .map(d => ({ id: d.id, name: d.name, type: 'district-sub' }))
      .sort((a, b) => a.name.localeCompare(b.name, 'ru'))


  loaded.value = true
})

/* ---------- drag‑and‑drop ---------- */
async function handleDrop (evt) {
  const el = evt?.added?.element || evt?.moved?.element || evt?.removed?.element
  if (!el || evt.to === evt.from) return

  const targetManager = evt.to.dataset.managerId ? Number(evt.to.dataset.managerId) : null

  try {
    if (el.type === 'region') {
      await auth.purposeSenManager({ region_id: el.id, sen_manager_id: targetManager })
    } else if (el.type === 'district-group') {
      await auth.assignGroupManagerToDistrict({ district_id: el.id, group_manager_id: targetManager })
    } else if (el.type === 'district-sub') {
      await auth.assignSubgroupManager({ district_id: el.id, subgroup_manager_id: targetManager })
    }
  } catch (e) {
    console.error(e)
    alert('Не удалось сохранить изменение')
  }
}
</script>

<template>
  <!-- навигация -->
  <ul class="nav nav-tabs mb-3">
    <li v-if="auth.hasPermission(['assign-an-senior'])" class="nav-item"><button class="nav-link" :class="{active:active==='sen'}"
                                 @click="active='sen'">Региональные</button></li>
    <li v-if="auth.hasPermission(['assign-an-group-manager'])" class="nav-item"><button class="nav-link" :class="{active:active==='group'}"
                                 @click="active='group'">Менеджеры&nbsp;групп</button></li>
    <li v-if="auth.hasPermission(['assign-an-subgroup-manager'])" class="nav-item"><button class="nav-link" :class="{active:active==='sub'}"
                                 @click="active='sub'">Менеджеры&nbsp;подгрупп</button></li>
  </ul>

  <!-- содержимое -->
  <SeniorTab
      v-if="active==='sen' && loaded && auth.hasPermission(['assign-an-senior'])"
      :bucket="bucketSen"
      :managers="seniorManagers"
      label="regions"
      @change="handleDrop"
  />

  <GroupTab
      v-if="active==='group' && loaded && auth.hasPermission(['assign-an-group-manager'])"
      :bucket="bucketGroup"
      :managers="groupManagers"
      label="districts"
      type-class="district"
      show-region
      @change="handleDrop"
  />

  <SubgroupTab
      v-if="active==='sub' && loaded && auth.hasPermission(['assign-an-subgroup-manager'])"
      :bucket="bucketSub"
      :managers="subgroupManagers"
      label="districts"
      type-class="sub"
      @change="handleDrop"
  />

</template>
