<template>
  <q-page class="q-pa-md">
    <div class="row items-center q-col-gutter-sm q-mb-md">
      <div class="col-12 col-md">
        <div class="text-h6">Marka Sınıflandırma</div>
        <div class="text-caption text-grey-7">
          Kaynak: NEBIM_V3 marka bilgileri
        </div>
      </div>

      <div class="col-12 col-md-auto">
        <q-input
          v-model="search"
          dense
          outlined
          clearable
          placeholder="Marka ara (kod / ad)"
          @keyup.enter="reload"
          style="min-width: 260px"
        />
      </div>

      <div class="col-12 col-md-auto row items-center q-gutter-sm">
        <q-btn
          color="secondary"
          outline
          :loading="loading"
          label="Yenile"
          @click="reload"
        />
        <q-btn
          color="primary"
          unelevated
          icon="save"
          :disable="!canUpdate || selectedDirtyCount === 0 || saving"
          :loading="saving"
          label="Kaydet (Seçili)"
          @click="saveSelected"
        />
      </div>
    </div>

    <q-table
      flat
      bordered
      :rows="rows"
      :columns="columns"
      row-key="brand_code"
      selection="multiple"
      v-model:selected="selected"
      :loading="loading"
      :pagination="{ rowsPerPage: 0 }"
      hide-bottom
      class="mk-table"
    >
      <template #body-cell-group="props">
        <q-td :props="props">
          <q-select
            v-model="props.row._group_id"
            dense
            outlined
            emit-value
            map-options
            option-value="id"
            option-label="title"
            :options="groupOptionsWithNone"
            :disable="!canUpdate || saving"
            style="min-width: 160px"
            @update:model-value="markDirty(props.row)"
          >
            <template #option="scope">
              <q-item v-bind="scope.itemProps">
                <q-item-section>
                  <div class="text-body2">{{ scope.opt.title }}</div>
                  <div v-if="scope.opt.description" class="text-caption text-grey-7">
                    {{ scope.opt.description }}
                  </div>
                </q-item-section>
              </q-item>
            </template>
          </q-select>
        </q-td>
      </template>

      <template #body-cell-actions="props">
        <q-td :props="props" class="text-right">
          <span class="text-caption text-grey-7" v-if="props.row._dirty">Değişti</span>
        </q-td>
      </template>
    </q-table>
  </q-page>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'
import { Notify } from 'quasar'
import api from 'src/services/api'
import { usePermissionStore } from 'stores/permissionStore'

const perm = usePermissionStore()

const loading = ref(false)
const saving = ref(false)
const search = ref('')
const groups = ref([])
const rows = ref([])
const selected = ref([])

const canUpdate = computed(() => perm.hasApiPermission('pricing:update'))

const groupOptionsWithNone = computed(() => {
  const base = Array.isArray(groups.value) ? groups.value : []
  return [{ id: 0, title: '(Seçiniz)', code: '' }, ...base]
})

const selectedDirtyCount = computed(() => {
  const list = Array.isArray(selected.value) ? selected.value : []
  return list.filter(r => r?._dirty).length
})

const columns = [
  { name: 'brand_code', label: 'Marka Kodu', field: 'brand_code', align: 'left', sortable: true },
  { name: 'brand_name', label: 'Marka Adı', field: 'brand_name', align: 'left', sortable: true },
  { name: 'group', label: 'Grup', field: 'group_name', align: 'left' },
  { name: 'actions', label: '', field: 'actions', align: 'right' }
]

function normalizeRow (r) {
  return {
    brand_code: String(r?.brand_code ?? '').trim(),
    brand_name: String(r?.brand_name ?? '').trim(),
    group_id: Number(r?.group_id ?? 0) || 0,
    group_name: String(r?.group_name ?? '').trim(),
    _group_id: Number(r?.group_id ?? 0) || 0,
    _dirty: false
  }
}

function markDirty (row) {
  row._dirty = true
}

async function loadLookups () {
  const res = await api.request({
    method: 'GET',
    url: '/pricing/brand-classification/lookups',
    timeout: 180000
  })
  groups.value = Array.isArray(res?.data?.groups) ? res.data.groups : []
}

async function reload () {
  loading.value = true
  try {
    await loadLookups()
    const res = await api.request({
      method: 'GET',
      url: '/pricing/brand-classification/brands',
      params: search.value ? { q: search.value } : {},
      timeout: 180000
    })
    const data = Array.isArray(res?.data) ? res.data : []
    rows.value = data.map(normalizeRow)
    selected.value = []
  } catch (err) {
    Notify.create({ type: 'negative', message: err?.response?.data || err?.message || 'Liste alınamadı' })
  } finally {
    loading.value = false
  }
}

async function saveSelected () {
  const list = Array.isArray(selected.value) ? selected.value : []
  const dirty = list.filter(r => r && r._dirty)
  if (dirty.length === 0) return
  saving.value = true
  try {
    const payload = {
      items: dirty.map(r => ({
        brand_code: r.brand_code,
        group_id: Number(r._group_id || 0)
      }))
    }
    await api.request({
      method: 'POST',
      url: '/pricing/brand-classification/brands/group-bulk',
      data: payload,
      timeout: 180000
    })
    for (const r of dirty) {
      r.group_id = Number(r._group_id || 0)
      const selOpt = groupOptionsWithNone.value.find(x => Number(x.id) === r.group_id)
      r.group_name = selOpt ? String(selOpt.title || '') : ''
      r._dirty = false
    }
    Notify.create({ type: 'positive', message: `Kaydedildi: ${dirty.length} satır` })
  } catch (err) {
    Notify.create({ type: 'negative', message: err?.response?.data || err?.message || 'Kaydedilemedi' })
  } finally {
    saving.value = false
  }
}

onMounted(async () => {
  // Initial: ensure data exists. If mk_brands is empty, user can run sync.
  await reload()
})
</script>

<style scoped>
.mk-table :deep(th) {
  white-space: nowrap;
}
</style>
