import { create } from 'zustand'
import { financeApi } from '@/lib/api'

export interface Account {
  code: string
  name: string
  type: string
  balance: number
}

export interface Invoice {
  id: string
  customer_id: string
  amount: number
  currency: string
  status: string
  due_date: string
}

interface FinanceState {
  accounts: Account[]
  invoices: Invoice[]
  balance: unknown
  income: unknown
  moms: unknown
  cashflow: unknown
  loading: boolean
  error: string | null
  fetchAccounts: () => Promise<void>
  fetchInvoices: () => Promise<void>
  fetchBalance: () => Promise<void>
  fetchIncome: () => Promise<void>
  fetchMoms: () => Promise<void>
  fetchCashflow: () => Promise<void>
}

export const useFinanceStore = create<FinanceState>((set) => ({
  accounts: [],
  invoices: [],
  balance: null,
  income: null,
  moms: null,
  cashflow: null,
  loading: false,
  error: null,

  fetchAccounts: async () => {
    set({ loading: true, error: null })
    try {
      const data = await financeApi.accounts()
      set({ accounts: (data.accounts || []) as Account[], loading: false })
    } catch (err) {
      set({ error: err instanceof Error ? err.message : 'Failed to fetch accounts', loading: false })
    }
  },

  fetchInvoices: async () => {
    set({ loading: true, error: null })
    try {
      const data = await financeApi.invoices()
      set({ invoices: (data.invoices || []) as Invoice[], loading: false })
    } catch (err) {
      set({ error: err instanceof Error ? err.message : 'Failed to fetch invoices', loading: false })
    }
  },

  fetchBalance: async () => {
    try {
      const data = await financeApi.balance()
      set({ balance: data })
    } catch (err) {
      console.error('Failed to fetch balance:', err)
    }
  },

  fetchIncome: async () => {
    try {
      const data = await financeApi.income()
      set({ income: data })
    } catch (err) {
      console.error('Failed to fetch income:', err)
    }
  },

  fetchMoms: async () => {
    try {
      const data = await financeApi.moms()
      set({ moms: data })
    } catch (err) {
      console.error('Failed to fetch moms:', err)
    }
  },

  fetchCashflow: async () => {
    try {
      const data = await financeApi.cashflow()
      set({ cashflow: data })
    } catch (err) {
      console.error('Failed to fetch cashflow:', err)
    }
  },
}))
