import { OddsSettings, storage } from "@/lib/storage";
import React, {
  createContext,
  ReactNode,
  useContext,
  useEffect,
  useState,
} from "react";

interface AppState {
  selectedSportId: number | null;
  selectedDate: Date;
  selectedLeagueKey: string | null;
  timezone: string;
  oddsSettings: OddsSettings;
}

interface AppStateContextType {
  state: AppState;
  updateSportId: (sportId: number | null) => void;
  updateDate: (date: Date) => void;
  updateLeagueKey: (leagueKey: string | null) => void;
  updateTimezone: (timezone: string) => void;
  updateOddsSettings: (settings: OddsSettings) => void;
}

const AppStateContext = createContext<AppStateContextType | undefined>(
  undefined,
);

export function AppStateProvider({ children }: { children: ReactNode }) {
  const [state, setState] = useState<AppState>({
    selectedSportId: 1, // 默认足球
    selectedDate: new Date(),
    selectedLeagueKey: null,
    timezone: "UTC",
    oddsSettings: { enabled: false, selectedBookmakers: [] },
  });

  useEffect(() => {
    // Initial load of odds settings
    storage.getOddsSettings().then((settings) => {
      setState((prev) => ({ ...prev, oddsSettings: settings }));
    });
  }, []);

  const updateSportId = (sportId: number | null) => {
    setState((prev) => ({ ...prev, selectedSportId: sportId }));
  };

  const updateDate = (date: Date) => {
    setState((prev) => ({ ...prev, selectedDate: date }));
  };

  const updateLeagueKey = (leagueKey: string | null) => {
    setState((prev) => ({ ...prev, selectedLeagueKey: leagueKey }));
  };

  const updateTimezone = (timezone: string) => {
    setState((prev) => ({ ...prev, timezone }));
  };

  const updateOddsSettings = (settings: OddsSettings) => {
    setState((prev) => ({ ...prev, oddsSettings: settings }));
    storage.setOddsSettings(settings);
  };

  return (
    <AppStateContext.Provider
      value={{
        state,
        updateSportId,
        updateDate,
        updateLeagueKey,
        updateTimezone,
        updateOddsSettings,
      }}
    >
      {children}
    </AppStateContext.Provider>
  );
}

export function useAppState() {
  const context = useContext(AppStateContext);
  if (!context) {
    throw new Error("useAppState must be used within AppStateProvider");
  }
  return context;
}
