import { create } from 'zustand';
import type { User, UserRole } from '@/types';
import { authApi } from '@/lib/apiClient';

interface AuthState {
  token: string | null;
  user: User | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  login: (role: UserRole, username: string, password: string) => Promise<boolean>;
  logout: () => void;
  checkSession: () => void;
}

export const useAuthStore = create<AuthState>((set, get) => ({
  token: localStorage.getItem('skatepro_token'),
  user: (() => {
    const u = localStorage.getItem('skatepro_user');
    try { return u ? JSON.parse(u) : null; } catch { return null; }
  })(),
  isAuthenticated: !!localStorage.getItem('skatepro_token'),
  isLoading: false,

  login: async (role, username, password) => {
    set({ isLoading: true });
    try {
      const result = await authApi.login(username, password);
      if (result.success && result.token) {
        localStorage.setItem('skatepro_token', result.token);
        localStorage.setItem('skatepro_user', JSON.stringify(result.user));
        set({ token: result.token, user: result.user, isAuthenticated: true, isLoading: false });
        return true;
      }
      set({ isLoading: false });
      return false;
    } catch {
      // Fallback: allow admin and assistant demo login without backend
      const demoUsers: Record<string, { password: string; user: User }> = {
        admin: { password: 'admin123', user: { id: 1, name: 'Admin User', username: 'admin', role: 'admin' } },
        assistant: { password: 'assistant123', user: { id: 2, name: 'Coach Rahul', username: 'assistant', role: 'assistant' } },
      };
      const key = role === 'admin' ? 'admin' : role === 'assistant' ? 'assistant' : '';
      const demoUser = key ? demoUsers[key] : null;
      if (demoUser && username === key && password === demoUser.password) {
        const token = `demo_${role}_${Date.now()}`;
        localStorage.setItem('skatepro_token', token);
        localStorage.setItem('skatepro_user', JSON.stringify(demoUser.user));
        set({ token, user: demoUser.user, isAuthenticated: true, isLoading: false });
        return true;
      }
      set({ isLoading: false });
      return false;
    }
  },

  logout: () => {
    localStorage.removeItem('skatepro_token');
    localStorage.removeItem('skatepro_user');
    set({ token: null, user: null, isAuthenticated: false });
    window.location.hash = '#/admin';
    window.location.reload();
  },

  checkSession: () => {
    const token = localStorage.getItem('skatepro_token');
    const userStr = localStorage.getItem('skatepro_user');
    if (token && userStr) {
      try {
        set({ token, user: JSON.parse(userStr), isAuthenticated: true });
      } catch {
        set({ token: null, user: null, isAuthenticated: false });
      }
    }
  },
}));
