import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import type { User } from '@/types'
import { authApi, type RegisterData, type LoginData } from '@/api/auth'

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

  login: (data: LoginData) => Promise<void>
  register: (data: RegisterData) => Promise<void>
  logout: () => void
  clearError: () => void
  setPendingInviteCode: (code: string | null) => void
  consumePendingInviteCode: () => string | null
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      user: null,
      token: null,
      isAuthenticated: false,
      isLoading: false,
      error: null,
      pendingInviteCode: null,

      login: async (data) => {
        set({ isLoading: true, error: null })
        try {
          const response = await authApi.login(data)
          localStorage.setItem('token', response.access_token)
          set({
            user: response.user,
            token: response.access_token,
            isAuthenticated: true,
            isLoading: false,
          })
        } catch (err: unknown) {
          const error = err as { response?: { data?: { detail?: string } } }
          set({
            error: error.response?.data?.detail || 'Login failed',
            isLoading: false,
          })
          throw err
        }
      },

      register: async (data) => {
        set({ isLoading: true, error: null })
        try {
          const response = await authApi.register(data)
          localStorage.setItem('token', response.access_token)
          set({
            user: response.user,
            token: response.access_token,
            isAuthenticated: true,
            isLoading: false,
          })
        } catch (err: unknown) {
          const error = err as { response?: { data?: { detail?: string } } }
          set({
            error: error.response?.data?.detail || 'Registration failed',
            isLoading: false,
          })
          throw err
        }
      },

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

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

      setPendingInviteCode: (code) => set({ pendingInviteCode: code }),

      consumePendingInviteCode: () => {
        const code = get().pendingInviteCode
        set({ pendingInviteCode: null })
        return code
      },
    }),
    {
      name: 'auth-storage',
      partialize: (state) => ({
        user: state.user,
        token: state.token,
        isAuthenticated: state.isAuthenticated,
        pendingInviteCode: state.pendingInviteCode,
      }),
    }
  )
)
