import { create } from 'zustand';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { updateColors, type AppColors } from '../theme/colors';

const STORAGE_KEY = '@fitcrm/theme_id';
const API_BASE = 'https://api.myfitcrm.ru/v1';
const POLL_INTERVAL = 30_000;

interface ThemeColors {
  '--primary': string;
  '--primary-foreground': string;
  '--background': string;
  '--card': string;
  '--error': string;
  '--success': string;
  '--warning': string;
  '--muted': string;
  '--border': string;
  '--sidebar-bg': string;
  '--sidebar-text': string;
  '--sidebar-active': string;
  '--text': string;
}

interface ThemeResponse {
  themeId: string;
  theme: {
    id: string;
    colors: ThemeColors;
    fonts: { heading: string; body: string; importUrl?: string };
    isDark: boolean;
    primaryColor: string;
  };
}

/** Map API theme colors to app color tokens */
function mapThemeToColors(theme: ThemeResponse['theme']): AppColors {
  const c = theme.colors;
  return {
    primary: c['--primary'],
    primaryLight: c['--sidebar-active'],
    background: c['--background'],
    card: c['--card'],
    text: c['--text'],
    textSecondary: c['--muted'],
    textMuted: c['--muted'],
    error: c['--error'],
    success: c['--success'],
    warning: c['--warning'],
    border: c['--border'],
    salesCard: c['--sidebar-bg'],
    white: '#FFFFFF',
    black: '#000000',
  };
}

interface ThemeState {
  themeId: string;
  isDark: boolean;
  isLoaded: boolean;
  fetchTheme: () => Promise<void>;
  startPolling: () => () => void;
  restoreTheme: () => Promise<void>;
}

export const useThemeStore = create<ThemeState>((set, get) => ({
  themeId: 'fitpulse-orange',
  isDark: false,
  isLoaded: false,

  fetchTheme: async () => {
    try {
      const res = await fetch(`${API_BASE}/theme/current`);
      if (!res.ok) return;
      const data = (await res.json()) as ThemeResponse;
      if (!data.themeId || !data.theme) return;

      const prev = get().themeId;
      if (prev === data.themeId && get().isLoaded) return;

      const appColors = mapThemeToColors(data.theme);
      updateColors(appColors);

      await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify({
        themeId: data.themeId,
        colors: appColors,
        isDark: data.theme.isDark,
      }));

      set({ themeId: data.themeId, isDark: data.theme.isDark, isLoaded: true });
    } catch {
      // Silently fail — app works with default colors
    }
  },

  startPolling: () => {
    const interval = setInterval(() => {
      void get().fetchTheme();
    }, POLL_INTERVAL);
    return () => clearInterval(interval);
  },

  restoreTheme: async () => {
    try {
      const stored = await AsyncStorage.getItem(STORAGE_KEY);
      if (stored) {
        const data = JSON.parse(stored) as {
          themeId: string;
          colors: AppColors;
          isDark: boolean;
        };
        updateColors(data.colors);
        set({ themeId: data.themeId, isDark: data.isDark, isLoaded: true });
      }
    } catch {
      // Use defaults
    }
    // Always fetch fresh from API after restoring cache
    void get().fetchTheme();
  },
}));
