import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import type { User, AuthResponse } from '../types/auth';
import { refreshAuthToken } from '../services/auth-api';
import { axiosInstance } from '../services/axios';
import { useThemeStore } from './use-theme';

interface AuthState {
  user: User | null;
  isAuthenticated: boolean;
  accessToken: string | null;
  isInitializing: boolean;
  setAuth: (data: AuthResponse) => void;
  logout: () => void;
  checkAuth: () => Promise<void>;
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      user: null,
      isAuthenticated: false,
      accessToken: null,
      isInitializing: true,
      setAuth: (data) => {
        if (data.user?.defaultTheme) {
          useThemeStore.getState().setTheme(data.user.defaultTheme as any);
        }
        set({
          user: data.user,
          accessToken: data.accessToken,
          isAuthenticated: true,
          isInitializing: false,
        });
      },
      logout: () => set({
        user: null,
        accessToken: null,
        isAuthenticated: false,
        isInitializing: false,
      }),
      checkAuth: async () => {
        // If we have an existing token, validate it by fetching current user details
        const state = get();
        if (state.accessToken && state.user) {
          try {
            const res = await axiosInstance.get('/auth/me');
            if (res.data?.defaultTheme) {
              useThemeStore.getState().setTheme(res.data.defaultTheme as any);
            }
            set({
              user: res.data,
              isAuthenticated: true,
              isInitializing: false,
            });
            return;
          } catch (err: any) {
            console.error('Session validation failed, trying refresh token...', err);
            // If it failed due to network error and not 401/403, we don't clear the session immediately
            if (err.response && err.response.status !== 401 && err.response.status !== 403) {
              set({ isInitializing: false });
              return;
            }
          }
        }

        // Try refreshing token
        try {
          const data = await refreshAuthToken();
          if (data.user?.defaultTheme) {
            useThemeStore.getState().setTheme(data.user.defaultTheme as any);
          }
          set({
            user: data.user,
            accessToken: data.accessToken,
            isAuthenticated: true,
            isInitializing: false,
          });
        } catch (err) {
          set({
            user: null,
            accessToken: null,
            isAuthenticated: false,
            isInitializing: false,
          });
        }
      }
    }),
    {
      name: 't4b_auth_store',
      storage: createJSONStorage(() => localStorage),
      partialize: (state) => ({
        user: state.user,
        accessToken: state.accessToken,
        isAuthenticated: state.isAuthenticated,
      }),
    }
  )
);
