import { defineStore } from 'pinia'
import api from 'src/services/api'

export const useCustomerBalanceListStore = defineStore('customerBalanceList', {
  state: () => ({
    filters: {
      selectedDate: new Date().toISOString().slice(0, 10),
      excludeZeroBalance12: false,
      excludeZeroBalance13: false,
      cariSearch: '',
      cariIlkGrup: [],
      piyasa: [],
      temsilci: [],
      riskDurumu: [],
      islemTipi: [],
      ulke: [],
      il: [],
      ilce: []
    },
    rows: [],
    loading: false,
    error: null,
    hasFetched: false,
    defaultsInitialized: false
  }),

  getters: {
    cariIlkGrupOptions: (state) => uniqueOptions(state.rows, 'cari_ilk_grup'),
    piyasaOptions: (state) => uniqueOptions(state.rows, 'piyasa'),
    temsilciOptions: (state) => uniqueOptions(state.rows, 'temsilci'),
    riskDurumuOptions: (state) => uniqueOptions(state.rows, 'risk_durumu', { includeDash: true }),
    ulkeOptions: (state) => uniqueOptions(state.rows, 'ozellik05'),
    ilOptions: (state) => uniqueOptions(state.rows, 'il'),
    ilceOptions: (state) => uniqueOptions(state.rows, 'ilce'),

    filteredRows: (state) => {
      const selectedCariIlkGrup = new Set((state.filters.cariIlkGrup || []).map(v => normalizeText(v)))
      const selectedPiyasa = new Set((state.filters.piyasa || []).map(v => normalizeText(v)))
      const selectedTemsilci = new Set((state.filters.temsilci || []).map(v => normalizeText(v)))
      const selectedRiskDurumu = new Set((state.filters.riskDurumu || []).map(v => normalizeText(v)))
      const selectedUlke = new Set((state.filters.ulke || []).map(v => normalizeText(v)))
      const selectedIl = new Set((state.filters.il || []).map(v => normalizeText(v)))
      const selectedIlce = new Set((state.filters.ilce || []).map(v => normalizeText(v)))

      const matchMulti = (selectedSet, value) => {
        if (!selectedSet.size) return true
        const normalized = normalizeText(value)
        if (!normalized) return selectedSet.has('-')
        return selectedSet.has(normalized)
      }

      return state.rows.filter((row) => {
        const bak12 = Number(row.bakiye_1_2) || 0
        const bak13 = Number(row.bakiye_1_3) || 0
        const usd12 = Number(row.usd_bakiye_1_2) || 0
        const try12 = Number(row.tl_bakiye_1_2) || 0
        const usd13 = Number(row.usd_bakiye_1_3) || 0
        const try13 = Number(row.tl_bakiye_1_3) || 0
        const cariSearchNeedle = normalizeText(state.filters.cariSearch || '')

        const cariIlkGrupOk =
          matchMulti(selectedCariIlkGrup, row.cari_ilk_grup)

        const piyasaOk =
          matchMulti(selectedPiyasa, row.piyasa)

        const temsilciOk =
          matchMulti(selectedTemsilci, row.temsilci)

        const riskDurumuOk =
          matchMulti(selectedRiskDurumu, row.risk_durumu)

        const cariText = normalizeText([
          row.ana_cari_kodu || '',
          row.ana_cari_adi || '',
          row.cari_kodu || '',
          row.cari_detay || ''
        ].join(' '))
        const cariSearchOk =
          !cariSearchNeedle ||
          cariText.includes(cariSearchNeedle)

        const ulkeOk =
          matchMulti(selectedUlke, row.ozellik05)

        const ilOk =
          matchMulti(selectedIl, row.il)

        const ilceOk =
          matchMulti(selectedIlce, row.ilce)

        const islemTipiOk =
          !state.filters.islemTipi.length ||
          state.filters.islemTipi.some((t) => {
            if (t === '1_2') return bak12 !== 0 || usd12 !== 0 || try12 !== 0
            if (t === '1_3') return bak13 !== 0 || usd13 !== 0 || try13 !== 0
            return false
          })

        const excludeZero12Ok = !state.filters.excludeZeroBalance12 || bak12 !== 0
        const excludeZero13Ok = !state.filters.excludeZeroBalance13 || bak13 !== 0

        return cariIlkGrupOk && piyasaOk && temsilciOk && riskDurumuOk &&
          cariSearchOk && ulkeOk && ilOk && ilceOk && islemTipiOk &&
          excludeZero12Ok && excludeZero13Ok
      })
    },

    summaryRows () {
      const grouped = new Map()

      for (const row of this.filteredRows) {
        const key = String(row.ana_cari_kodu || '').trim()
        const current = grouped.get(key) || {
          group_key: key,
          ana_cari_kodu: key,
          ana_cari_adi: row.ana_cari_adi || '',
          piyasa: '',
          piyasa_set: new Set(),
          temsilci: '',
          temsilci_set: new Set(),
          risk_durumu: '',
          risk_set: new Set(),
          bakiye_1_2_map: {},
          bakiye_1_3_map: {},
          usd_bakiye_1_2: 0,
          tl_bakiye_1_2: 0,
          usd_bakiye_1_3: 0,
          tl_bakiye_1_3: 0
        }

        current.usd_bakiye_1_2 += Number(row.usd_bakiye_1_2) || 0
        current.tl_bakiye_1_2 += Number(row.tl_bakiye_1_2) || 0
        current.usd_bakiye_1_3 += Number(row.usd_bakiye_1_3) || 0
        current.tl_bakiye_1_3 += Number(row.tl_bakiye_1_3) || 0

        if (!String(current.ana_cari_adi || '').trim() && String(row.ana_cari_adi || '').trim()) {
          current.ana_cari_adi = row.ana_cari_adi
        }

        const curr = String(row.cari_doviz || '').trim().toUpperCase() || 'N/A'
        current.bakiye_1_2_map[curr] =
          (Number(current.bakiye_1_2_map[curr]) || 0) + (Number(row.bakiye_1_2) || 0)
        current.bakiye_1_3_map[curr] =
          (Number(current.bakiye_1_3_map[curr]) || 0) + (Number(row.bakiye_1_3) || 0)

        const piyasa = String(row.piyasa || '').trim()
        if (piyasa) current.piyasa_set.add(piyasa)

        const temsilci = String(row.temsilci || '').trim()
        if (temsilci) current.temsilci_set.add(temsilci)

        const risk = String(row.risk_durumu || row.ozellik03 || '').trim()
        if (risk) current.risk_set.add(risk)

        const riskValues = Array.from(current.risk_set)
        current.risk_durumu =
          riskValues.length <= 1
            ? (riskValues[0] || '-')
            : riskValues.join(', ')

        const piyasaValues = Array.from(current.piyasa_set)
        current.piyasa =
          piyasaValues.length <= 1
            ? (piyasaValues[0] || '-')
            : piyasaValues.join(', ')

        const temsilciValues = Array.from(current.temsilci_set)
        current.temsilci =
          temsilciValues.length <= 1
            ? (temsilciValues[0] || '-')
            : temsilciValues.join(', ')

        grouped.set(key, current)
      }

      return Array.from(grouped.values()).map((r) => {
        const { risk_set, piyasa_set, temsilci_set, ...rest } = r
        return rest
      })
    }
  },

  actions: {
    async fetchCustomerBalances () {
      this.loading = true
      this.error = null

      try {
        const { data } = await api.get('/finance/customer-balances', {
          params: {
            selected_date: this.filters.selectedDate,
            cari_search: String(this.filters.cariSearch || '').trim(),
            cari_ilk_grup: (this.filters.cariIlkGrup || []).join(','),
            piyasa: (this.filters.piyasa || []).join(','),
            temsilci: (this.filters.temsilci || []).join(','),
            risk_durumu: (this.filters.riskDurumu || []).join(','),
            islem_tipi: (this.filters.islemTipi || []).join(','),
            ulke: (this.filters.ulke || []).join(','),
            il: (this.filters.il || []).join(','),
            ilce: (this.filters.ilce || []).join(',')
          }
        })
        this.rows = Array.isArray(data) ? data : []
        if (!this.defaultsInitialized) {
          this.applyInitialFilterDefaults()
          this.defaultsInitialized = true
        }
        this.hasFetched = true
      } catch (err) {
        this.rows = []
        this.hasFetched = false
        this.error =
          err?.response?.data?.message ||
          err?.message ||
          'Cari bakiye listesi getirilemedi.'
      } finally {
        this.loading = false
      }
    },

    getDetailsByGroup (groupKey) {
      return this.filteredRows.filter(r =>
        String(r.ana_cari_kodu || '').trim() === String(groupKey || '').trim()
      )
    },

    resetFilters () {
      this.filters.excludeZeroBalance12 = false
      this.filters.excludeZeroBalance13 = false
      this.filters.cariSearch = ''
      this.filters.cariIlkGrup = []
      this.filters.piyasa = []
      this.filters.temsilci = []
      this.filters.riskDurumu = []
      this.filters.islemTipi = []
      this.filters.ulke = []
      this.filters.il = []
      this.filters.ilce = []
      this.defaultsInitialized = false
    },

    selectAll (field, options) {
      this.filters[field] = options.map(o => o.value)
    },

    clearAll (field) {
      this.filters[field] = []
    },

    applyInitialFilterDefaults () {
      const excludedCariIlkGrup = new Set([
        normalizeText('transfer'),
        normalizeText('perakende'),
        normalizeText('dtf')
      ])
      this.filters.cariIlkGrup = this.cariIlkGrupOptions
        .map(o => o.value)
        .filter(v => !excludedCariIlkGrup.has(normalizeText(v)))

      this.filters.riskDurumu = []
    }
  }
})

function uniqueOptions (rows, field, opts = {}) {
  const includeDash = !!opts.includeDash
  const set = new Set()
  if (includeDash) set.add('-')
  for (const r of rows) {
    const v = String(r[field] || '').trim()
    if (v) {
      set.add(v)
      continue
    }
    if (includeDash) {
      set.add('-')
    }
  }

  return Array.from(set)
    .sort((a, b) => a.localeCompare(b, 'tr'))
    .map(v => ({ label: v, value: v }))
}

function normalizeText (str) {
  return String(str || '')
    .toLocaleLowerCase('tr-TR')
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '')
    .trim()
}

