import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import { User, LoginRequest, PhoneLoginRequest, LoginResponse } from '@api/modules/auth'
import { authApi } from '@api'

interface AuthState {
  user: User | null
  token: string | null
  refreshToken: string | null
  isAuthenticated: boolean
  isLoading: boolean
  error: string | null
}

interface AuthActions {
  login: (credentials: LoginRequest) => Promise<void>
  loginByPhone: (credentials: PhoneLoginRequest) => Promise<void>
  logout: () => void
  refreshToken: () => Promise<void>
  getUserInfo: () => Promise<void>
  updateUserInfo: (data: Partial<User>) => Promise<void>
  clearError: () => void
  setLoading: (loading: boolean) => void
}

export const useAuthStore = create<AuthState & AuthActions>()(
  persist(
    (set, get) => ({
      // State
      user: null,
      token: null,
      refreshToken: null,
      isAuthenticated: false,
      isLoading: false,
      error: null,

      // Actions
      login: async (credentials) => {
        try {
          set({ isLoading: true, error: null })
          const response = await authApi.login(credentials)
          const { token, refreshToken, user } = response.data

          localStorage.setItem('token', token)
          localStorage.setItem('refreshToken', refreshToken)

          set({
            user,
            token,
            refreshToken,
            isAuthenticated: true,
            isLoading: false
          })
        } catch (error) {
          set({
            error: error instanceof Error ? error.message : '登录失败',
            isLoading: false
          })
        }
      },

      loginByPhone: async (credentials) => {
        try {
          set({ isLoading: true, error: null })
          const response = await authApi.loginByPhone(credentials)
          const { token, refreshToken, user } = response.data

          localStorage.setItem('token', token)
          localStorage.setItem('refreshToken', refreshToken)

          set({
            user,
            token,
            refreshToken,
            isAuthenticated: true,
            isLoading: false
          })
        } catch (error) {
          set({
            error: error instanceof Error ? error.message : '登录失败',
            isLoading: false
          })
        }
      },

      logout: () => {
        localStorage.removeItem('token')
        localStorage.removeItem('refreshToken')
        set({
          user: null,
          token: null,
          refreshToken: null,
          isAuthenticated: false,
          error: null
        })
      },

      refreshToken: async () => {
        try {
          const { refreshToken } = get()
          if (!refreshToken) {
            get().logout()
            return
          }

          const response = await authApi.refreshToken(refreshToken)
          const { token } = response.data

          localStorage.setItem('token', token)
          set({ token })
        } catch (error) {
          get().logout()
        }
      },

      getUserInfo: async () => {
        try {
          const response = await authApi.getUserInfo()
          set({ user: response.data })
        } catch (error) {
          console.error('获取用户信息失败:', error)
        }
      },

      updateUserInfo: async (data) => {
        try {
          const response = await authApi.updateUserInfo(data)
          set({ user: response.data })
        } catch (error) {
          set({
            error: error instanceof Error ? error.message : '更新用户信息失败'
          })
        }
      },

      clearError: () => set({ error: null }),

      setLoading: (loading) => set({ isLoading: loading })
    }),
    {
      name: 'auth-storage',
      partialize: (state) => ({
        user: state.user,
        token: state.token,
        refreshToken: state.refreshToken,
        isAuthenticated: state.isAuthenticated
      })
    }
  )
)