import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from 'react'
import type { Order } from '../services/orderService'

export type DeliveryMode = 'delivery' | 'pickup'

interface CheckoutState {
  deliveryMode: DeliveryMode
  selectedAddressId: string | null
  discountCode: string
  placedOrder: Order | null
}

interface CheckoutContextValue extends CheckoutState {
  setDeliveryMode: (mode: DeliveryMode) => void
  setSelectedAddressId: (id: string | null) => void
  setDiscountCode: (code: string) => void
  setPlacedOrder: (order: Order | null) => void
  resetCheckout: () => void
}

const defaultState: CheckoutState = {
  deliveryMode: 'delivery',
  selectedAddressId: null,
  discountCode: '',
  placedOrder: null,
}

const CheckoutContext = createContext<CheckoutContextValue | null>(null)

export function CheckoutProvider({ children }: { children: ReactNode }) {
  const [state, setState] = useState<CheckoutState>(defaultState)

  const setDeliveryMode = useCallback((deliveryMode: DeliveryMode) => {
    setState((prev) => ({ ...prev, deliveryMode }))
  }, [])

  const setSelectedAddressId = useCallback((selectedAddressId: string | null) => {
    setState((prev) =>
      prev.selectedAddressId === selectedAddressId ? prev : { ...prev, selectedAddressId },
    )
  }, [])

  const setDiscountCode = useCallback((discountCode: string) => {
    setState((prev) => ({ ...prev, discountCode }))
  }, [])

  const setPlacedOrder = useCallback((placedOrder: Order | null) => {
    setState((prev) => ({ ...prev, placedOrder }))
  }, [])

  const resetCheckout = useCallback(() => {
    setState(defaultState)
  }, [])

  const value = useMemo<CheckoutContextValue>(
    () => ({
      ...state,
      setDeliveryMode,
      setSelectedAddressId,
      setDiscountCode,
      setPlacedOrder,
      resetCheckout,
    }),
    [state, setDeliveryMode, setSelectedAddressId, setDiscountCode, setPlacedOrder, resetCheckout],
  )

  return <CheckoutContext.Provider value={value}>{children}</CheckoutContext.Provider>
}

export function useCheckout() {
  const ctx = useContext(CheckoutContext)
  if (!ctx) {
    throw new Error('useCheckout must be used within CheckoutProvider')
  }
  return ctx
}
