import { defineStore } from 'pinia'
import { LocalStorage } from 'quasar'
import type { Address } from '../types/address'

interface CommentAttachment {
  comments: string
  attachments: string[]
}

export interface ChildItem {
  firstName: string
  lastName: string
  birthDate: string
  sameHousehold: boolean
  alimentiVersati?: boolean
  school: string
  hasCareCost: boolean
  careCosts: CommentAttachment
  address?: Address | null
}

export interface ChildrenData {
  hasChildren: boolean
  children: ChildItem[]
  moreThanFiveChildrenNote: string
}

const STORAGE_KEY = 'children:v1'

const DEFAULT: ChildrenData = {
  hasChildren: false,
  children: [],
  moreThanFiveChildrenNote: ''
}

export const useChildrenStore = defineStore('childrenstore', {
  state: () => {
    try {
      let saved: unknown = LocalStorage.getItem(STORAGE_KEY)
      if (typeof saved === 'string') {
        try {
          saved = JSON.parse(saved)
        } catch {
          saved = null
        }
      }
      if (saved && typeof saved === 'object') {
        return { data: { ...(saved as ChildrenData) } }
      }
    } catch {
      // ignore and fall back to default
    }
    return { data: { ...DEFAULT } as ChildrenData }
  },
  actions: {
    persist() {
      try {
        // LocalStorage (and JSON) can fail when trying to serialize
        // File objects. Build a serializable copy: drop `careCosts`
        // (or convert to file meta) before persisting.
        const serializable: ChildrenData = {
          hasChildren: !!this.data.hasChildren,
          children: Array.isArray(this.data.children)
              ? this.data.children.map(c => {
                  return {
                    firstName: c.firstName,
                    lastName: c.lastName,
                    birthDate: c.birthDate,
                    sameHousehold: c.sameHousehold,
                    alimentiVersati: (c as Partial<ChildItem>).alimentiVersati ?? false,
                    school: c.school,
                    hasCareCost: (c as Partial<ChildItem>).hasCareCost ?? false,
                    careCosts: c.careCosts,
                    address: (c as Partial<ChildItem>).address ?? null,
                  }
                })
              : [],
          moreThanFiveChildrenNote: this.data.moreThanFiveChildrenNote || ''
        }
        LocalStorage.set(STORAGE_KEY, serializable)
      } catch (err) {
        // keep errors visible in console to aid debugging but don't throw
        console.error('children.store: persist error', err)
      }
    },
    getChildren() {
      return this.data
    },
    setChildren(partial: Partial<ChildrenData>) {
      this.data = { ...this.data, ...partial }
      this.persist()
    },
    replaceChildren(payload: ChildrenData) {
      this.data = payload
      this.persist()
    },
    resetChildren() {
      this.data = { ...DEFAULT }
      this.persist()
    }
  }
})
