import { StateCreator } from 'zustand'
import { v4 as uuidv4 } from 'uuid'
import { FixedDebt, VariableDebt } from '@/lib/types'

export interface DebtsSlice {
  fixedDebts: FixedDebt[]
  variableDebts: VariableDebt[]
  
  // Actions Fixed
  addFixedDebt: (debt: Omit<FixedDebt, 'id'>) => void
  updateFixedDebt: (id: string, debt: Partial<FixedDebt>) => void
  deleteFixedDebt: (id: string) => void
  toggleFixedDebtPaid: (id: string) => void
  
  // Actions Variable
  addVariableDebt: (debt: Omit<VariableDebt, 'id'>) => void
  updateVariableDebt: (id: string, debt: Partial<VariableDebt>) => void
  deleteVariableDebt: (id: string) => void
  toggleVariableDebtPaid: (id: string) => void
}

export const createDebtsSlice: StateCreator<DebtsSlice> = (set) => ({
  fixedDebts: [],
  variableDebts: [],

  addFixedDebt: (debt) =>
    set((state) => ({
      fixedDebts: [...state.fixedDebts, { ...debt, id: uuidv4() }],
    })),

  updateFixedDebt: (id, debt) =>
    set((state) => ({
      fixedDebts: state.fixedDebts.map((d) =>
        d.id === id ? { ...d, ...debt } : d
      ),
    })),

  deleteFixedDebt: (id) =>
    set((state) => ({
      fixedDebts: state.fixedDebts.filter((d) => d.id !== id),
    })),

  toggleFixedDebtPaid: (id) =>
    set((state) => ({
      fixedDebts: state.fixedDebts.map((d) =>
        d.id === id ? { ...d, isPaid: !d.isPaid } : d
      ),
    })),

  addVariableDebt: (debt) =>
    set((state) => ({
      variableDebts: [...state.variableDebts, { ...debt, id: uuidv4() }],
    })),

  updateVariableDebt: (id, debt) =>
    set((state) => ({
      variableDebts: state.variableDebts.map((d) =>
        d.id === id ? { ...d, ...debt } : d
      ),
    })),

  deleteVariableDebt: (id) =>
    set((state) => ({
      variableDebts: state.variableDebts.filter((d) => d.id !== id),
    })),

  toggleVariableDebtPaid: (id) =>
    set((state) => ({
      variableDebts: state.variableDebts.map((d) =>
        d.id === id ? { ...d, isPaid: !d.isPaid } : d
      ),
    })),
})
