import { create } from 'zustand';
import * as identityService from '../services/identityService';
import { calculateCurrentDay } from '../utils/date';
import useAuthStore from './useAuthStore';
import useHabitStore from './useHabitStore';
import { trackIdentityCreated } from '../services/analytics';

const useIdentityStore = create((set, get) => ({
  identity: null,
  currentDay: 0,
  loading: false,
  error: null,

  fetchIdentity: async () => {
    const user = useAuthStore.getState().user;
    if (!user) return;

    set({ loading: true, error: null });
    try {
      const data = await identityService.getIdentity(user.id);
      if (data) {
        const day = calculateCurrentDay(data.start_date);
        set({ identity: data, currentDay: day, loading: false });
        // Also load habits into habit store
        await useHabitStore.getState().fetchHabits(data.id);
      } else {
        set({ identity: null, currentDay: 0, loading: false });
      }
    } catch (e) {
      set({ loading: false, error: e.message });
    }
  },

  createIdentity: async (title, description, customHabits, storyText) => {
    const user = useAuthStore.getState().user;
    if (!user) throw new Error('Not authenticated');

    set({ loading: true, error: null });
    try {
      const { identity, habits } = await identityService.createIdentity(
        user.id, title, description, customHabits, storyText
      );
      set({ identity, currentDay: 1, loading: false });
      trackIdentityCreated(title, customHabits ? 'custom' : 'auto');
      useHabitStore.getState().setHabits(habits);
      return identity;
    } catch (e) {
      set({ loading: false, error: e.message });
      throw e;
    }
  },

  // Daily logs
  saveDailyLog: async (identityCheck, note) => {
    const { identity, currentDay } = get();
    if (!identity) return;
    await identityService.saveDailyLog(identity.id, currentDay, identityCheck, note);
  },

  loadDailyLogs: async () => {
    const { identity } = get();
    if (!identity) return [];
    return identityService.getDailyLogs(identity.id);
  },

  // Stats
  loadStats: async () => {
    const { identity } = get();
    if (!identity) return null;
    return identityService.getStats(identity.id);
  },

  // Game
  saveGameScore: async (gameType, score) => {
    const { identity } = get();
    if (!identity) return;
    await identityService.saveGameScore(identity.id, gameType, score);
  },

  // Reset journey (with reason)
  resetJourney: async (reason) => {
    const { identity } = get();
    if (!identity) return;
    await identityService.resetJourney(identity.id, reason);
    set({ identity: null, currentDay: 0 });
    useHabitStore.getState().reset();
  },

  // Reset on logout
  reset: () => set({ identity: null, currentDay: 0, loading: false, error: null }),
}));

export default useIdentityStore;
