import { create } from 'zustand'
import type { User } from '@shared/types'

interface AuthState {
  user: User | null
  token: string | null
  isAuthenticated: boolean
  isLoading: boolean
  error: string | null
  // 2FA state
  requires2fa: boolean
  twoFactorSessionId: number | null

  login: (login: string, password: string) => Promise<boolean>
  verify2fa: (code: string) => Promise<boolean>
  logout: () => Promise<void>
  syncUser: () => Promise<void>
  clearError: () => void
  reset2fa: () => void
}

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

  login: async (login: string, password: string) => {
    set({ isLoading: true, error: null, requires2fa: false, twoFactorSessionId: null })

    const result = await window.electronAPI.apiLogin(login, password)

    if (!result.success) {
      set({
        isLoading: false,
        error: typeof result.error === 'string' ? result.error : 'Ошибка авторизации',
      })
      return false
    }

    const response = result.data!

    if (response.requires_2fa && response.two_factor_session_id) {
      set({
        isLoading: false,
        requires2fa: true,
        twoFactorSessionId: response.two_factor_session_id,
      })
      return false // Not fully logged in yet
    }

    if (response.access_token && response.user) {
      set({
        user: response.user,
        token: response.access_token,
        isAuthenticated: true,
        isLoading: false,
      })
      return true
    }

    set({ isLoading: false })
    return false
  },

  verify2fa: async (code: string) => {
    const sessionId = get().twoFactorSessionId
    if (!sessionId) {
      set({ error: 'Нет активной сессии 2FA' })
      return false
    }

    set({ isLoading: true, error: null })

    const result = await window.electronAPI.api2faVerify(sessionId, code)

    if (!result.success) {
      set({
        isLoading: false,
        error: typeof result.error === 'string' ? result.error : 'Неверный код',
      })
      return false
    }

    const response = result.data!

    if (response.access_token && response.user) {
      set({
        user: response.user,
        token: response.access_token,
        isAuthenticated: true,
        isLoading: false,
        requires2fa: false,
        twoFactorSessionId: null,
      })
      return true
    }

    set({ isLoading: false })
    return false
  },

  reset2fa: () => set({ requires2fa: false, twoFactorSessionId: null, error: null }),

  logout: async () => {
    await window.electronAPI.clearToken()
    set({
      user: null,
      token: null,
      isAuthenticated: false,
      error: null,
    })
  },

  syncUser: async () => {
    set({ isLoading: true })

    const token = await window.electronAPI.getToken()
    if (!token) {
      set({ isLoading: false, isAuthenticated: false })
      return
    }

    const result = await window.electronAPI.apiGetMe()

    if (!result.success) {
      await window.electronAPI.clearToken()
      set({
        user: null,
        token: null,
        isAuthenticated: false,
        isLoading: false,
      })
      return
    }

    set({
      user: result.data!,
      token,
      isAuthenticated: true,
      isLoading: false,
    })
  },

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