import { create } from 'zustand'
import { shopApi } from '@/api/shop'
import type { ShopItem, InventoryItem, ShopItemType } from '@/types'
import { useAuthStore } from './auth'

interface ShopState {
  // State
  balance: number
  items: ShopItem[]
  inventory: InventoryItem[]
  isLoading: boolean
  isBalanceLoading: boolean
  error: string | null

  // Actions
  loadBalance: () => Promise<void>
  loadItems: (itemType?: ShopItemType) => Promise<void>
  loadInventory: (itemType?: ShopItemType) => Promise<void>
  purchase: (itemId: number, quantity?: number) => Promise<boolean>
  equip: (inventoryId: number) => Promise<boolean>
  unequip: (itemType: ShopItemType) => Promise<boolean>
  updateBalance: (newBalance: number) => void
  clearError: () => void
}

export const useShopStore = create<ShopState>()((set, get) => ({
  balance: 0,
  items: [],
  inventory: [],
  isLoading: false,
  isBalanceLoading: false,
  error: null,

  loadBalance: async () => {
    set({ isBalanceLoading: true })
    try {
      const data = await shopApi.getBalance()
      set({ balance: data.balance, isBalanceLoading: false })
    } catch (err) {
      console.error('Failed to load balance:', err)
      set({ isBalanceLoading: false })
    }
  },

  loadItems: async (itemType?: ShopItemType) => {
    set({ isLoading: true, error: null })
    try {
      const items = await shopApi.getItems(itemType)
      set({ items, isLoading: false })
    } catch (err) {
      const error = err as { response?: { data?: { detail?: string } } }
      set({
        error: error.response?.data?.detail || 'Не удалось загрузить товары',
        isLoading: false,
      })
    }
  },

  loadInventory: async (itemType?: ShopItemType) => {
    set({ isLoading: true, error: null })
    try {
      const inventory = await shopApi.getInventory(itemType)
      set({ inventory, isLoading: false })
    } catch (err) {
      const error = err as { response?: { data?: { detail?: string } } }
      set({
        error: error.response?.data?.detail || 'Не удалось загрузить инвентарь',
        isLoading: false,
      })
    }
  },

  purchase: async (itemId: number, quantity: number = 1) => {
    try {
      const result = await shopApi.purchase(itemId, quantity)
      set({ balance: result.new_balance })
      // Reload items and inventory to update ownership status
      await Promise.all([get().loadItems(), get().loadInventory()])
      return true
    } catch (err) {
      const error = err as { response?: { data?: { detail?: string } } }
      set({ error: error.response?.data?.detail || 'Не удалось совершить покупку' })
      return false
    }
  },

  equip: async (inventoryId: number) => {
    try {
      await shopApi.equip(inventoryId)
      await get().loadInventory()
      // Sync user data to update equipped cosmetics in UI
      await useAuthStore.getState().syncUser()
      return true
    } catch (err) {
      const error = err as { response?: { data?: { detail?: string } } }
      set({ error: error.response?.data?.detail || 'Не удалось экипировать предмет' })
      return false
    }
  },

  unequip: async (itemType: ShopItemType) => {
    try {
      await shopApi.unequip(itemType)
      await get().loadInventory()
      // Sync user data to update equipped cosmetics in UI
      await useAuthStore.getState().syncUser()
      return true
    } catch (err) {
      const error = err as { response?: { data?: { detail?: string } } }
      set({ error: error.response?.data?.detail || 'Не удалось снять предмет' })
      return false
    }
  },

  updateBalance: (newBalance: number) => {
    set({ balance: newBalance })
  },

  clearError: () => set({ error: null }),
}))

// Convenience hook for just getting the balance
export const useCoinsBalance = () => useShopStore((state) => state.balance)
