import React, { useCallback, useEffect, useMemo, useState } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { COLORS, FONTS, SPACING, SHADOWS } from './theme';
import type { ColorScheme, ThemeContextValue, ThemeTokens } from './types';

export const ThemeContext = React.createContext<ThemeContextValue | undefined>(undefined);

const STORAGE_KEY = 'theme.scheme';

const getInitialScheme = async (): Promise<ColorScheme> => {
  try {
    const stored = await AsyncStorage.getItem(STORAGE_KEY);
    if (stored === 'dark' || stored === 'light') {
      return stored;
    }
  } catch (_) {
    // ignore read errors
  }
  return 'light';
};

const buildTokens = (_scheme: ColorScheme): ThemeTokens => {
  // For now, we use the same token set for both schemes.
  return {
    colors: COLORS,
    spacing: SPACING,
    fonts: FONTS,
    shadows: SHADOWS,
  };
};

export const ThemeProvider: React.FC<React.PropsWithChildren> = ({ children }) => {
  const [scheme, setSchemeState] = useState<ColorScheme>('light');

  useEffect(() => {
    // Hydrate theme on mount
    getInitialScheme().then(setSchemeState);
  }, []);

  const setScheme = useCallback((next: ColorScheme) => {
    setSchemeState(next);
    AsyncStorage.setItem(STORAGE_KEY, next).catch(() => undefined);
  }, []);

  const tokens = useMemo(() => buildTokens(scheme), [scheme]);

  const value: ThemeContextValue = useMemo(
    () => ({ ...tokens, isDark: scheme === 'dark', setScheme }),
    [tokens, scheme, setScheme],
  );

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

export default ThemeProvider;


