import { createContext, useContext, useState, useEffect, useCallback, type ReactNode } from 'react'
import { api } 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[] }>('/api/flights?pageSize=1000')
      setFlights(data.items ?? [])
    } catch {}
  }, [])

  useEffect(() => {
    refreshFlights()
    api.get<UserSettings>('/api/annotations/settings/user')
      .then(settings => {
        if (settings?.selectedFlightId) {
          api.get<Flight>(`/api/flights/${settings.selectedFlightId}`)
            .then(f => setSelectedFlight(f))
            .catch(() => {})
        }
      })
      .catch(() => {})
  }, [refreshFlights])

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

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