import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import AsyncStorage from '@react-native-async-storage/async-storage';

interface User {
  token: string;
  user: {
    id: number;
    email: string;
    first_name?: string;
    last_name?: string;
    phone?: string;
    address?: string;
    username?: string;
    email_verified_at?: string | null;
    avatar?: string;
  };
}

interface AuthState {
  user: User | null;
  isLoading: boolean;
  login: (userData: User) => void;
  updateUser: (updates: Partial<User['user']>) => void;
  logout: () => void;
  setLoading: (loading: boolean) => void;
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set) => ({
      user: null,
      isLoading: true,
      login: (userData) => set({ user: userData }),
      updateUser: (updates) =>
        set((state) => ({
          user: state.user
            ? { ...state.user, user: { ...state.user.user, ...updates } }
            : null,
        })),
      logout: () => set({ user: null }),
      setLoading: (loading) => set({ isLoading: loading }),
    }),
    {
      name: 'auth-storage',
      storage: createJSONStorage(() => AsyncStorage),
      onRehydrateStorage: () => (state) => {
        state?.setLoading(false);
      },
    }
  )
);
