import AsyncStorage from '@react-native-async-storage/async-storage';
import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState,
  type ReactNode,
} from 'react';
import {
  APPEARANCE_OPTIONS,
  getThemeColors,
  type AppearanceId,
  type ThemeColors,
} from '@/src/theme/appearance';

const STORAGE_KEY = 'dailymeals.appearance';

interface AppearanceContextValue {
  appearanceId: AppearanceId;
  colors: ThemeColors;
  setAppearance: (id: AppearanceId) => Promise<void>;
}

const AppearanceContext = createContext<AppearanceContextValue | null>(null);

export function AppearanceProvider({ children }: { children: ReactNode }) {
  const [appearanceId, setAppearanceId] = useState<AppearanceId>('forest');

  useEffect(() => {
    (async () => {
      const stored = await AsyncStorage.getItem(STORAGE_KEY);
      if (stored && APPEARANCE_OPTIONS.some((o) => o.id === stored)) {
        setAppearanceId(stored as AppearanceId);
      }
    })();
  }, []);

  const setAppearance = useCallback(async (id: AppearanceId) => {
    setAppearanceId(id);
    await AsyncStorage.setItem(STORAGE_KEY, id);
  }, []);

  const value = useMemo(
    () => ({
      appearanceId,
      colors: getThemeColors(appearanceId),
      setAppearance,
    }),
    [appearanceId, setAppearance],
  );

  return <AppearanceContext.Provider value={value}>{children}</AppearanceContext.Provider>;
}

export function useAppearance() {
  const ctx = useContext(AppearanceContext);
  if (!ctx) throw new Error('useAppearance must be used within AppearanceProvider');
  return ctx;
}
