<template>
  <q-page v-if="canUpdateSystem" class="q-pa-md">
    <div class="row items-center justify-between q-mb-md">
      <div>
        <div class="text-h6">Fiyat Grubu Kullanici Eslestirme</div>
        <div class="text-caption text-grey-7">Sol tarafta fiyat grubu, sagda o grubu gorebilecek kullanicilar yer alir.</div>
      </div>
      <q-btn
        color="primary"
        icon="save"
        label="Degisiklikleri Kaydet"
        :loading="store.saving"
        :disable="!hasChanges"
        @click="saveChanges"
      />
    </div>

    <q-table
      flat
      bordered
      dense
      row-key="value"
      :loading="store.loading"
      :rows="priceGroupRows"
      :columns="columns"
      :rows-per-page-options="[0]"
      :pagination="{ rowsPerPage: 0 }"
    >
      <template #body-cell-users="props">
        <q-td :props="props">
          <q-select
            :model-value="editableByGroup[props.row.value] || []"
            :options="userOptions"
            option-value="value"
            option-label="label"
            emit-value
            map-options
            multiple
            use-chips
            clearable
            dense
            outlined
            label="Kullanicilar"
            @update:model-value="(val) => updateGroupSelection(props.row.value, val)"
          >
            <template #before-options>
              <q-item clickable @click="selectAll(props.row.value)">
                <q-item-section>Tum Kullanicilari Sec</q-item-section>
              </q-item>
              <q-item clickable @click="clearAll(props.row.value)">
                <q-item-section>Temizle</q-item-section>
              </q-item>
              <q-separator />
            </template>
          </q-select>
        </q-td>
      </template>
    </q-table>
  </q-page>

  <q-page v-else class="q-pa-md flex flex-center">
    <div class="text-negative text-subtitle1">
      Bu module erisim yetkiniz yok.
    </div>
  </q-page>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'
import { useQuasar } from 'quasar'
import { usePermission } from 'src/composables/usePermission'
import { useOrderPriceListUserPriceGroupStore } from 'src/stores/orderPriceListUserPriceGroupStore'

const $q = useQuasar()
const store = useOrderPriceListUserPriceGroupStore()
const { canUpdate } = usePermission()
const canUpdateSystem = canUpdate('system')

const editableByGroup = ref({})
const originalByGroup = ref({})

const columns = [
  { name: 'price_group', label: 'Fiyat Grubu', field: 'label', align: 'left', sortable: true },
  { name: 'users', label: 'Bu Fiyat Grubunu Gorebilen Kullanicilar', field: 'users', align: 'left' }
]

const priceGroupRows = computed(() => store.priceGroupOptions || [])

const userOptions = computed(() => {
  return (store.rows || [])
    .map((row) => {
      const id = Number(row.user_id || 0)
      if (!id) return null
      const username = String(row.username || '').trim()
      const fullName = String(row.full_name || '').trim()
      const email = String(row.email || '').trim()
      const details = [fullName, email].filter(Boolean).join(' - ')
      return {
        value: id,
        label: details ? `${username || id} (${details})` : String(username || id)
      }
    })
    .filter(Boolean)
})

const changedGroups = computed(() => {
  return (store.priceGroupOptions || [])
    .map((r) => String(r.value || '').trim())
    .filter(Boolean)
    .filter((group) => !isEqualList(normalizeUserIdList(editableByGroup.value[group] || []), normalizeUserIdList(originalByGroup.value[group] || [])))
})

const hasChanges = computed(() => changedGroups.value.length > 0)

function normalizePriceGroupList (list) {
  const allowed = new Set((store.priceGroupOptions || []).map((x) => x.value))
  return Array.from(new Set((Array.isArray(list) ? list : []).map((x) => String(x).trim()).filter((x) => allowed.has(x)))).sort()
}

function normalizeUserIdList (list) {
  const allowed = new Set(userOptions.value.map((x) => x.value))
  return Array.from(new Set((Array.isArray(list) ? list : []).map((x) => Number(x || 0)).filter((x) => allowed.has(x)))).sort((a, b) => a - b)
}

function isEqualList (a, b) {
  if (a.length !== b.length) return false
  for (let i = 0; i < a.length; i += 1) {
    if (a[i] !== b[i]) return false
  }
  return true
}

function initEditableState () {
  const editable = {}
  const original = {}
  for (const option of store.priceGroupOptions || []) {
    const group = String(option.value || '').trim()
    if (!group) continue
    editable[group] = []
    original[group] = []
  }
  for (const row of store.rows || []) {
    const id = Number(row.user_id || 0)
    if (!id) continue
    for (const group of normalizePriceGroupList(row.price_groups || [])) {
      editable[group] = normalizeUserIdList([...(editable[group] || []), id])
      original[group] = normalizeUserIdList([...(original[group] || []), id])
    }
  }
  editableByGroup.value = editable
  originalByGroup.value = original
}

function updateGroupSelection (priceGroup, newValue) {
  const group = String(priceGroup || '').trim()
  if (!group) return
  editableByGroup.value = { ...editableByGroup.value, [group]: normalizeUserIdList(newValue) }
}

function selectAll (priceGroup) {
  updateGroupSelection(priceGroup, userOptions.value.map((x) => x.value))
}

function clearAll (priceGroup) {
  updateGroupSelection(priceGroup, [])
}

function buildUserPriceGroupsFromGroupState () {
  const byUser = {}
  for (const user of userOptions.value) {
    byUser[user.value] = []
  }
  for (const group of Object.keys(editableByGroup.value || {})) {
    for (const userId of normalizeUserIdList(editableByGroup.value[group] || [])) {
      byUser[userId] = normalizePriceGroupList([...(byUser[userId] || []), group])
    }
  }
  return byUser
}

function buildOriginalUserPriceGroups () {
  const byUser = {}
  for (const row of store.rows || []) {
    const id = Number(row.user_id || 0)
    if (!id) continue
    byUser[id] = normalizePriceGroupList(row.price_groups || [])
  }
  return byUser
}

function changedUserIdsFromGroupState () {
  const nextByUser = buildUserPriceGroupsFromGroupState()
  const originalByUser = buildOriginalUserPriceGroups()
  return Object.keys(nextByUser)
    .map((id) => Number(id || 0))
    .filter(Boolean)
    .filter((id) => !isEqualList(normalizePriceGroupList(nextByUser[id] || []), normalizePriceGroupList(originalByUser[id] || [])))
}

async function init () {
  try {
    await Promise.all([store.fetchLookups(), store.fetchRows()])
    initEditableState()
  } catch (err) {
    $q.notify({ type: 'negative', message: err?.message || 'Kullanici fiyat grubu eslestirmeleri yuklenemedi' })
  }
}

async function saveChanges () {
  if (!hasChanges.value) return
  try {
    const nextByUser = buildUserPriceGroupsFromGroupState()
    for (const id of changedUserIdsFromGroupState()) {
      await store.saveUserPriceGroups(id, nextByUser[id] || [])
    }
    await store.fetchRows()
    initEditableState()
    $q.notify({ type: 'positive', message: 'Degisiklikler kaydedildi' })
  } catch (err) {
    $q.notify({ type: 'negative', message: err?.message || 'Kayit hatasi' })
  }
}

onMounted(() => { init() })
</script>
