<template>
  <q-page v-if="canUpdateSystem" class="q-pa-md">
    <div class="row justify-end q-mb-md">
      <q-btn
        color="primary"
        icon="save"
        label="Degisiklikleri Kaydet"
        :loading="store.saving"
        :disable="!hasChanges"
        @click="saveChanges"
      />
    </div>

    <q-table
      flat
      bordered
      dense
      row-key="group_code"
      :loading="store.loading"
      :rows="store.rows"
      :columns="columns"
      :rows-per-page-options="[0]"
      :pagination="{ rowsPerPage: 0 }"
    >
      <template #body-cell-mail_selector="props">
        <q-td :props="props">
          <q-select
            :model-value="editableByGroup[props.row.group_code] || []"
            :options="mailOptionsByGroup[props.row.group_code] || allMailOptions"
            option-value="id"
            option-label="label"
            emit-value
            map-options
            multiple
            use-chips
            use-input
            input-debounce="0"
            clearable
            dense
            outlined
            label="Mail ara ve sec"
            @filter="(val, update) => filterMailOptions(props.row.group_code, val, update)"
            @update:model-value="(val) => updateRowSelection(props.row.group_code, val)"
          />
        </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 { usePricingMailMappingStore } from 'src/stores/pricingMailMappingStore'

const $q = useQuasar()
const store = usePricingMailMappingStore()

const { canUpdate } = usePermission()
const canUpdateSystem = canUpdate('system')

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

const columns = [
  { name: 'group_code', label: 'Urun Ilk Grup Kodu', field: 'group_code', align: 'left' },
  { name: 'group_title', label: 'Urun Ilk Grup Aciklama', field: 'group_title', align: 'left' },
  { name: 'mail_selector', label: 'Fiyatlandirma Mail Eslestirme', field: 'mail_selector', align: 'left' }
]

const allMailOptions = computed(() =>
  (store.mails || []).map((m) => ({ id: m.id, label: m.display_name || m.email }))
)

const changedGroups = computed(() => {
  return (store.rows || [])
    .map((r) => String(r.group_code || r.urun_ilk_grubu || '').trim())
    .filter(Boolean)
    .filter((g) => {
      const current = normalizeList(editableByGroup.value[g] || [])
      const original = normalizeList(originalByGroup.value[g] || [])
      return !isEqualList(current, original)
    })
})

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

function normalizeList (list) {
  return Array.from(
    new Set(
      (Array.isArray(list) ? list : [])
        .map((x) => String(x).trim())
        .filter(Boolean)
    )
  ).sort()
}

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 = {}

  ;(store.rows || []).forEach((row) => {
    const g = String(row.group_code || row.urun_ilk_grubu || '').trim()
    const selected = normalizeList(row.mail_ids || [])
    editable[g] = [...selected]
    original[g] = [...selected]
  })

  editableByGroup.value = editable
  originalByGroup.value = original
  mailOptionsByGroup.value = {}
}

function updateRowSelection (group, newValue) {
  const g = String(group || '').trim()
  editableByGroup.value = { ...editableByGroup.value, [g]: normalizeList(newValue) }
}

function filterMailOptions (group, search, update) {
  const g = String(group || '').trim()
  update(() => {
    const q = String(search || '').trim().toLowerCase()
    const filtered = !q
      ? allMailOptions.value
      : allMailOptions.value.filter((opt) => String(opt.label || '').toLowerCase().includes(q))

    mailOptionsByGroup.value = { ...mailOptionsByGroup.value, [g]: filtered }
  })
}

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

async function saveChanges () {
  if (!hasChanges.value) return

  try {
    for (const g of changedGroups.value) {
      await store.saveGroupMails(g, editableByGroup.value[g] || [])
    }
    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>
