<template>
  <q-page class="q-pa-md">
    <div class="row items-center justify-between q-col-gutter-sm q-mb-md">
      <div class="col-12 col-md">
        <div class="text-h6">Marka Grubu Pr Br. Seçimi</div>
        <div class="text-caption text-grey-7">
          Marka gruplarının varsayılan çalışma para birimi burada tanımlanır.
        </div>
      </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 || dirtyCount === 0 || saving"
          :loading="saving"
          :label="`Kaydet (${dirtyCount})`"
          @click="saveRows"
        />
      </div>
    </div>

    <q-table
      flat
      bordered
      row-key="id"
      :rows="rows"
      :columns="columns"
      :loading="loading"
      :pagination="{ rowsPerPage: 0 }"
      hide-bottom
      class="bg-white"
    >
      <template #body-cell-anchor_mode="props">
        <q-td :props="props">
          <q-select
            v-model="props.row._anchor_mode"
            dense
            outlined
            emit-value
            map-options
            :options="anchorOptions"
            :disable="!canUpdate || saving"
            style="min-width: 120px"
            @update:model-value="() => markDirty(props.row)"
          />
        </q-td>
      </template>

      <template #body-cell-status="props">
        <q-td :props="props" class="text-right">
          <q-badge v-if="props.row._dirty" color="orange-7">Degisti</q-badge>
          <q-badge v-else color="grey-6">Kayitli</q-badge>
        </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 canUpdate = computed(() => perm.hasApiPermission('pricing:update'))

const loading = ref(false)
const saving = ref(false)
const rows = ref([])

const anchorOptions = [
  { label: 'USD', value: 'USD' },
  { label: 'TRY', value: 'TRY' }
]

const columns = [
  { name: 'code', label: 'Kod', field: 'code', align: 'left', sortable: true },
  { name: 'title', label: 'Marka Grubu', field: 'title', align: 'left', sortable: true },
  { name: 'description', label: 'Açıklama', field: 'description', align: 'left', sortable: true },
  { name: 'anchor_mode', label: 'Varsayılan Pr.Br.', field: 'anchor_mode', align: 'left', sortable: true },
  { name: 'status', label: '', field: 'status', align: 'right' }
]

const dirtyCount = computed(() => rows.value.filter(row => row?._dirty).length)

function normalizeRow (row) {
  const mode = String(row?.anchor_mode || 'USD').trim().toUpperCase() || 'USD'
  return {
    id: Number(row?.id || 0),
    code: String(row?.code || '').trim(),
    title: String(row?.title || '').trim(),
    description: String(row?.description || '').trim(),
    anchor_mode: mode,
    _anchor_mode: mode,
    _dirty: false
  }
}

function markDirty (row) {
  row._dirty = String(row._anchor_mode || 'USD').trim().toUpperCase() !== String(row.anchor_mode || 'USD').trim().toUpperCase()
}

async function reload () {
  loading.value = true
  try {
    const res = await api.request({
      method: 'GET',
      url: '/pricing/brand-group-currency',
      timeout: 180000
    })
    rows.value = (Array.isArray(res?.data) ? res.data : []).map(normalizeRow)
  } catch (err) {
    Notify.create({ type: 'negative', message: err?.response?.data || err?.message || 'Marka grubu para birimi listesi alinamadi' })
  } finally {
    loading.value = false
  }
}

async function saveRows () {
  const dirty = rows.value.filter(row => row?._dirty)
  if (dirty.length === 0) return
  saving.value = true
  try {
    await api.request({
      method: 'POST',
      url: '/pricing/brand-group-currency/bulk-save',
      data: {
        items: dirty.map(row => ({
          id: row.id,
          anchor_mode: String(row._anchor_mode || 'USD').trim().toUpperCase()
        }))
      },
      timeout: 180000
    })
    for (const row of dirty) {
      row.anchor_mode = String(row._anchor_mode || 'USD').trim().toUpperCase()
      row._dirty = false
    }
    Notify.create({ type: 'positive', message: `Kaydedildi: ${dirty.length} satir` })
  } catch (err) {
    Notify.create({ type: 'negative', message: err?.response?.data || err?.message || 'Marka grubu para birimi kaydedilemedi' })
  } finally {
    saving.value = false
  }
}

onMounted(reload)
</script>
