import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { randomUUID } from 'expo-crypto';
import type { WatchListItem, Exposure } from '@/types';

/**
 * TODO: Wire store operations to @shieldai/mobile-api-client for production.
 * Current implementation is local-only (AsyncStorage) for offline-first MVP.
 */

interface DarkWatchState {
  watchList: WatchListItem[];
  exposures: Exposure[];
  isLoading: boolean;
  addWatchItem: (item: Omit<WatchListItem, 'id' | 'lastChecked'>) => Promise<void>;
  removeWatchItem: (id: string) => void;
  toggleAlert: (id: string) => void;
  refreshExposures: () => Promise<void>;
}

export const useDarkWatchStore = create<DarkWatchState>()(
  persist(
    (set, get) => ({
      watchList: [],
      exposures: [],
      isLoading: false,

      addWatchItem: async (item) => {
        const newItem: WatchListItem = {
          ...item,
          id: randomUUID(),
          lastChecked: new Date().toISOString(),
        };
        set((state) => ({ watchList: [...state.watchList, newItem] }));
      },

      removeWatchItem: (id) => {
        set((state) => ({
          watchList: state.watchList.filter((item) => item.id !== id),
        }));
      },

      toggleAlert: (id) => {
        set((state) => ({
          watchList: state.watchList.map((item) =>
            item.id === id ? { ...item, alertEnabled: !item.alertEnabled } : item
          ),
        }));
      },

      refreshExposures: async () => {
        set({ isLoading: true });
        try {
          // TODO: Wire to @shieldai/mobile-api-client for production
          set({ isLoading: false });
        } catch (error) {
          console.error('[DarkWatch] Failed to refresh exposures:', error);
          set({ isLoading: false });
        }
      },
    }),
    {
      name: '@shieldai_darkwatch',
      storage: createJSONStorage(() => AsyncStorage),
    }
  )
);
