import { createContext, useContext, useState, useEffect, useCallback, type ReactNode } from 'react'
import { api, endpoints } from '../api'
import type { Flight, UserSettings } from '../types'

interface FlightState {
  flights: Flight[]
  selectedFlight: Flight | null
  selectFlight: (f: Flight | null) => void
  refreshFlights: () => Promise<void>
}

const FlightContext = createContext<FlightState>(null!)

export function useFlight() {
  return useContext(FlightContext)
}

export function FlightProvider({ children }: { children: ReactNode }) {
  const [flights, setFlights] = useState<Flight[]>([])
  const [selectedFlight, setSelectedFlight] = useState<Flight | null>(null)

  const refreshFlights = useCallback(async () => {
    try {
      const data = await api.get<{ items: Flight[] }>(endpoints.flights.collection('pageSize=1000'))
      setFlights(data.items ?? [])
    } catch {}
  }, [])

  useEffect(() => {
    refreshFlights()
    api.get<UserSettings>(endpoints.annotations.settingsUser())
      .then(settings => {
        if (settings?.selectedFlightId) {
          api.get<Flight>(endpoints.flights.flight(settings.selectedFlightId))
            .then(f => setSelectedFlight(f))
            .catch(() => {})
        }
      })
      .catch(() => {})
  }, [refreshFlights])

  const selectFlight = useCallback((f: Flight | null) => {
    setSelectedFlight(f)
    api.put(endpoints.annotations.settingsUser(), { selectedFlightId: f?.id ?? null }).catch(() => {})
  }, [])

  return (
    <FlightContext.Provider value={{ flights, selectedFlight, selectFlight, refreshFlights }}>
      {children}
    </FlightContext.Provider>
  )
}
