// contexts/StationsContext.tsx
'use client'

import { createContext, useContext, useEffect, useState, ReactNode, useCallback } from 'react'
import {
  Station,
  PaginatedStations,
  getStations,
  createStation,
  updateStation,
  deleteStation,
} from '@/lib/stations'

// Type pour les erreurs d'API
interface ApiError {
  response?: {
    status?: number;
    data?: { message?: string };
  };
  message?: string;
}

interface StationsContextType {
  stations: Station[]
  meta: PaginatedStations['meta']
  loading: boolean
  error: string | null
  fetchStations: (opts?: { page?: number; perPage?: number; q?: string }) => Promise<void>
  addStation: (station: { name: string; address: string; cityId: number; companyId?: number }) => Promise<void>
  editStation: (id: number, station: { name?: string; address?: string; cityId?: number; companyId?: number }) => Promise<void>
  removeStation: (id: number) => Promise<void>
}

const StationsContext = createContext<StationsContextType | undefined>(undefined)

export const StationsProvider = ({ children }: { children: ReactNode }) => {
  const [stations, setStations] = useState<Station[]>([])
  const [meta, setMeta] = useState<PaginatedStations['meta']>({ total: 0, perPage: 25, page: 1, lastPage: 1 })
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const fetchStations = useCallback(
    async ({ page = 1, perPage = 25, q = '' } = {}) => {
      setLoading(true)
      setError(null)
      try {
        const res = await getStations({ page, perPage, q })
        setStations(res.data)
        setMeta(res.meta)
      } catch (err: unknown) {
        const error = err as ApiError;
        setError(error.message || 'Erreur lors du chargement des stations')
      } finally {
        setLoading(false)
      }
    },
    []
  )

  const addStation = async (station: { name: string; address: string; cityId: number; companyId?: number }) => {
    setLoading(true)
    try {
      await createStation(station)
      await fetchStations({ page: meta.page })
    } catch (err: unknown) {
      throw err
    } finally {
      setLoading(false)
    }
  }

  const editStation = async (id: number, station: { name?: string; address?: string; cityId?: number; companyId?: number }) => {
    setLoading(true)
    try {
      await updateStation(id, station)
      await fetchStations({ page: meta.page })
    } catch (err: unknown) {
      throw err
    } finally {
      setLoading(false)
    }
  }

  const removeStation = async (id: number) => {
    setLoading(true)
    try {
      await deleteStation(id)
      const newPage = stations.length === 1 && meta.page > 1 ? meta.page - 1 : meta.page
      await fetchStations({ page: newPage })
    } catch (err: unknown) {
      const error = err as ApiError;
      setError(error.message || 'Erreur lors de la suppression de la station')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchStations()
  }, [fetchStations])

  return (
    <StationsContext.Provider
      value={{
        stations,
        meta,
        loading,
        error,
        fetchStations,
        addStation,
        editStation,
        removeStation,
      }}
    >
      {children}
    </StationsContext.Provider>
  )
}

export const useStations = () => {
  const ctx = useContext(StationsContext)
  if (!ctx) throw new Error('useStations must be used within a StationsProvider')
  return ctx
}
