import { create } from 'zustand';
import { AdminUser } from '@/types';
import axios from 'axios';

const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000';

interface AuthState {
  user: AdminUser | null;
  token: string | null;
  isAuthenticated: boolean;
  login: (email: string, password: string) => Promise<void>;
  logout: () => void;
  setUser: (user: AdminUser, token: string) => void;
  initialize: () => void;
}

export const useAuthStore = create<AuthState>((set) => ({
  user: null,
  token: null,
  isAuthenticated: false,

  initialize: () => {
    if (typeof window === 'undefined') return;
    const token = localStorage.getItem('auth_token');
    const userStr = localStorage.getItem('auth_user');
    if (token && userStr) {
      try {
        const user = JSON.parse(userStr);
        set({ user, token, isAuthenticated: true });
      } catch (e) {
        localStorage.removeItem('auth_token');
        localStorage.removeItem('auth_user');
      }
    }
  },

  login: async (email: string, password: string) => {
    try {
      console.log('Attempting login to:', `${API_URL}/auth/login`);
      const response = await axios.post(`${API_URL}/auth/login`, { email, password });
      console.log('Full response:', response.data);
      
      // Backend wraps response in { success, data: { token, user }, timestamp }
      const responseData = response.data.data || response.data;
      
      if (!responseData || !responseData.token || !responseData.user) {
        console.error('Invalid response structure:', response.data);
        throw new Error('Invalid response from server');
      }
      
      const { token, user: apiUser } = responseData;
      
      const user: AdminUser = {
        id: apiUser.id,
        email: apiUser.email,
        fullName: apiUser.fullName,
        role: apiUser.role,
        active: true,
      };
      
      console.log('Login successful! User:', user);
      
      localStorage.setItem('auth_token', token);
      localStorage.setItem('auth_user', JSON.stringify(user));
      
      set({ user, token, isAuthenticated: true });
    } catch (error: any) {
      console.error('Login error details:', {
        message: error.message,
        response: error.response?.data,
        status: error.response?.status,
      });
      throw error;
    }
  },

  logout: () => {
    localStorage.removeItem('auth_token');
    localStorage.removeItem('auth_user');
    set({ user: null, token: null, isAuthenticated: false });
  },

  setUser: (user: AdminUser, token: string) => {
    set({ user, token, isAuthenticated: true });
  },
}));
