import React, { createContext, useState, useEffect, useContext, ReactNode } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { cities } from '../utils/prayerTimeCalculator';

type City = keyof typeof cities;

interface CityContextType {
  selectedCity: City;
  setSelectedCity: (city: City) => void;
}

const CityContext = createContext<CityContextType | undefined>(undefined);

export const CityProvider = ({ children }: { children: ReactNode }) => {
  const [selectedCity, setSelectedCityState] = useState<City>('Makkah');

  useEffect(() => {
    const loadSelectedCity = async () => {
      try {
        const city = await AsyncStorage.getItem('selectedCity') as City;
        if (city) {
          setSelectedCityState(city);
        }
      } catch (error) {
        console.error('Failed to load selected city:', error);
      }
    };

    loadSelectedCity();
  }, []);

  const handleSetSelectedCity = async (city: City) => {
    setSelectedCityState(city);
    try {
      await AsyncStorage.setItem('selectedCity', city);
    } catch (error) {
      console.error('Failed to save selected city:', error);
    }
  };

  return (
    <CityContext.Provider value={{ selectedCity, setSelectedCity: handleSetSelectedCity }}>
      {children}
    </CityContext.Provider>
  );
};

export const useCity = () => {
  const context = useContext(CityContext);
  if (context === undefined) {
    throw new Error('useCity must be used within a CityProvider');
  }
  return context;
};
