import React, { createContext, useContext, useState } from 'react'

export interface BetslipSelection {
  matchId: string
  matchName: string
  marketId: string
  selectionName: string
  price: number
  currentPrice: number
  stake: number
  factionGlyph: string
}

interface BetslipContextType {
  selections: BetslipSelection[]
  addSelection: (sel: Omit<BetslipSelection, 'stake' | 'currentPrice'>) => void
  removeSelection: (marketId: string) => void
  updateStake: (marketId: string, stake: number) => void
  clearAll: () => void
  accumulatorStake: number
  setAccumulatorStake: (stake: number) => void
}

const BetslipContext = createContext<BetslipContextType | undefined>(undefined)

export function BetslipProvider({ children }: { children: React.ReactNode }) {
  const [selections, setSelections] = useState<BetslipSelection[]>([])
  const [accumulatorStake, setAccumulatorStake] = useState<number>(0)

  const addSelection = (
    sel: Omit<BetslipSelection, 'stake' | 'currentPrice'>,
  ) => {
    setSelections((prev) => {
      // Check if selection already exists
      if (prev.some((s) => s.marketId === sel.marketId)) {
        return prev
      }
      return [
        ...prev,
        {
          ...sel,
          currentPrice: sel.price,
          stake: 0,
        },
      ]
    })
  }

  const removeSelection = (marketId: string) => {
    setSelections((prev) => prev.filter((s) => s.marketId !== marketId))
  }

  const updateStake = (marketId: string, stake: number) => {
    setSelections((prev) =>
      prev.map((s) => (s.marketId === marketId ? { ...s, stake } : s)),
    )
  }

  const clearAll = () => {
    setSelections([])
    setAccumulatorStake(0)
  }

  return (
    <BetslipContext.Provider
      value={{
        selections,
        addSelection,
        removeSelection,
        updateStake,
        clearAll,
        accumulatorStake,
        setAccumulatorStake,
      }}
    >
      {children}
    </BetslipContext.Provider>
  )
}

export function useBetslip() {
  const context = useContext(BetslipContext)
  if (!context) {
    throw new Error('useBetslip must be used within a BetslipProvider')
  }
  return context
}
