import { defineStore } from 'pinia'
import { LocalStorage } from 'quasar'
import { type TaxpayerForm } from './taxpayer'
import { type MaritalData } from './marital'

const STORAGE_KEY = 'taxstore:v1'

const defaultTaxpayer: TaxpayerForm = {
  prevPreparedByUs: false,
  prevDeclaration: { comments: '', attachments: [] },
  firstName: '',
  lastName: '',
  birthDate: '',
  address: {
    street: '',
    cap: '',
    city: '',
    country: { code: '', name: '' },
    canton: ''
  }
}

const defaultMarital: MaritalData = {
  alimentiVersati: false,
  alimentiCommenti: { comments: '', attachments: [] },
  maritalStatus: '',
  spouseFirstName: '',
  spouseLastName: '',
  spouseBirthDate: '',
  spouseDeadDate  : '',
  spouseTaxNumber: '',
  spouseAddress: { street: '', cap: '', city: '', country: { code: '', name: '' }, canton: '' },
  marriageDate: '',
  separated: false,
  spouseAlimentiVersati: false
}

export const useTaxstore = defineStore('taxstore', {
  state: () => {
    // try to load persisted state from Quasar LocalStorage
    try {
      const saved: unknown = LocalStorage.getItem(STORAGE_KEY)
      if (saved && typeof saved === 'object') {
        const s = saved as Record<string, unknown>
        if (Array.isArray(s.items)) {
          const items = s.items as Array<
            | { key: 'taxpayer'; data: TaxpayerForm }
            | { key: 'marital'; data: MaritalData }
          >
          return { items }
        }
      }
    } catch {
      // ignore parsing errors and fall back to defaults
    }

    return {
      items: [
        { key: 'taxpayer', data: { ...defaultTaxpayer } as TaxpayerForm },
        { key: 'marital', data: { ...defaultMarital } as MaritalData }
      ] as Array<{ key: 'taxpayer'; data: TaxpayerForm } | { key: 'marital'; data: MaritalData }>
    }
  },
  actions: {
    // persist helper
    persist() {
      try {
        LocalStorage.set(STORAGE_KEY, { items: this.items })
      } catch {
        // ignore storage errors (e.g., quota exceeded)
      }
    },
    // Type-guard helpers
    _findTaxpayer(): { key: 'taxpayer'; data: TaxpayerForm } | undefined {
      return this.items.find((i): i is { key: 'taxpayer'; data: TaxpayerForm } => i.key === 'taxpayer')
    },
    _findMarital(): { key: 'marital'; data: MaritalData } | undefined {
      return this.items.find((i): i is { key: 'marital'; data: MaritalData } => i.key === 'marital')
    },

    // Taxpayer-specific helpers
    getTaxpayer() {
      return this._findTaxpayer()?.data
    },
    setTaxpayer(partial: Partial<TaxpayerForm>) {
      const it = this._findTaxpayer()
      if (it) it.data = { ...it.data, ...partial }
      this.persist()
    },
    replaceTaxpayer(payload: TaxpayerForm) {
      const it = this._findTaxpayer()
      if (it) it.data = payload
      this.persist()
    },
    resetTaxpayer() {
      const it = this._findTaxpayer()
      if (it) it.data = { ...defaultTaxpayer }
      this.persist()
    },

    // Marital-specific helpers
    getMarital() {
      return this._findMarital()?.data
    },
    setMarital(partial: Partial<MaritalData>) {
      const it = this._findMarital()
      if (it) it.data = { ...it.data, ...partial }
      this.persist()
    },
    replaceMarital(payload: MaritalData) {
      const it = this._findMarital()
      if (it) it.data = payload
      this.persist()
    },
    resetMarital() {
      const it = this._findMarital()
      if (it) it.data = { ...defaultMarital }
      this.persist()
    }
  }
})
