<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="market_id"
      :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="editableByMarket[props.row.market_id] || []"
            :options="mailOptionsByMarket[props.row.market_id] || 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.market_id, val, update)"
            @update:model-value="(val) => updateRowSelection(props.row.market_id, 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 { useMarketMailMappingStore } from 'src/stores/marketMailMappingStore'

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

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

const editableByMarket = ref({})
const originalByMarket = ref({})
const mailOptionsByMarket = ref({})

const columns = [
  {
    name: 'market_code',
    label: 'Piyasa Kodu',
    field: 'market_code',
    align: 'left'
  },
  {
    name: 'market_title',
    label: 'Piyasa',
    field: 'market_title',
    align: 'left'
  },
  {
    name: 'mail_selector',
    label: 'Mail Eslestirme',
    field: 'mail_selector',
    align: 'left'
  }
]

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

const changedMarketIds = computed(() => {
  return (store.rows || [])
    .map((r) => Number(r.market_id))
    .filter((marketId) => {
      const current = normalizeList(editableByMarket.value[marketId] || [])
      const original = normalizeList(originalByMarket.value[marketId] || [])
      return !isEqualList(current, original)
    })
})

const hasChanges = computed(() => changedMarketIds.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 marketId = Number(row.market_id)
    const selected = normalizeList(row.mail_ids || [])
    editable[marketId] = [...selected]
    original[marketId] = [...selected]
  })

  editableByMarket.value = editable
  originalByMarket.value = original
  mailOptionsByMarket.value = {}
}

function updateRowSelection (marketId, newValue) {
  editableByMarket.value = {
    ...editableByMarket.value,
    [Number(marketId)]: normalizeList(newValue)
  }
}

function filterMailOptions (marketId, search, update) {
  update(() => {
    const q = String(search || '').trim().toLowerCase()
    if (!q) {
      mailOptionsByMarket.value = {
        ...mailOptionsByMarket.value,
        [Number(marketId)]: allMailOptions.value
      }
      return
    }

    const filtered = allMailOptions.value.filter((opt) =>
      String(opt.label || '').toLowerCase().includes(q)
    )

    mailOptionsByMarket.value = {
      ...mailOptionsByMarket.value,
      [Number(marketId)]: filtered
    }
  })
}

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

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

  try {
    for (const marketId of changedMarketIds.value) {
      await store.saveMarketMails(marketId, editableByMarket.value[marketId] || [])
    }
    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>
