import { create } from 'zustand'
import axiosInstance from '@/utils/axios'
import { userEndpoints } from '../endpoints/user'
import {
  AuthenticationRequest,
  AuthenticationResponseBo,
  UserConnectionHistoryDto
} from '@/shared/types/auth'
import { Pageable } from '@/shared/types/client'
import { getTokenInfo } from '@/utils/token'

type AuthStore = {
  authData: AuthenticationResponseBo | null
  loading: boolean
  error: string | null
  login: (credentials: AuthenticationRequest) => Promise<void>
  logout: () => Promise<void>
  getUserHistory: (page?: number, size?: number) => Promise<Pageable<UserConnectionHistoryDto>>
}

export const useAuthStore = create<AuthStore>((set) => ({
  authData: null,
  loading: false,
  error: null,

  login: async (credentials) => {
    set({ loading: true, error: null })
    try {
      const response = await axiosInstance.post<AuthenticationResponseBo>(
        userEndpoints.user.auth.login,
        credentials
      )
      const token = getTokenInfo(response.data.token)
      localStorage.setItem("token", response.data.token)
      localStorage.setItem("refreshToken", response.data.refreshToken)
      localStorage.setItem("expirationDurationInSec", response.data.expirationDurationInSec.toString())
      localStorage.setItem("userId", response.data.userId.toString())
      localStorage.setItem("userConnectionHistoryId", response.data.userConnectionHistoryId.toString())
      localStorage.setItem("userEmail", credentials.username)
      localStorage.setItem("userName", token.name)
      
      set({ authData: response.data, loading: false })
    } catch (error: any) {
      set({ error: error.message || 'Login failed', loading: false })
    }
  },

  logout: async () => {
    set({ loading: true, error: null })
    try {
      const email = localStorage.getItem("userEmail")
      const connectionHistoryId = localStorage.getItem("userConnectionHistoryId")

      if (!email || !connectionHistoryId) {
        throw new Error("Missing email or connectionHistoryId in localStorage")
      }

      await axiosInstance.post(
        `${userEndpoints.user.auth.logout}?email=${email}&connectionHistoryId=${connectionHistoryId}`
      )

      // Nettoyage du localStorage
      localStorage.removeItem("token")
      localStorage.removeItem("refreshToken")
      localStorage.removeItem("expirationDurationInSec")
      localStorage.removeItem("userId")
      localStorage.removeItem("userConnectionHistoryId")
      localStorage.removeItem("userEmail")
      localStorage.removeItem("userName")

      set({ authData: null, loading: false })
    } catch (error: any) {
      set({ error: error.message || 'Logout failed', loading: false })
    }
  },

  getUserHistory: async (page = 0, size = 10) => {
    set({ loading: true, error: null })
    try {
      const userId = localStorage.getItem("userId")
      if (!userId) throw new Error("Missing userId in localStorage")

      const response = await axiosInstance.get<Pageable<UserConnectionHistoryDto>>(
        `${userEndpoints.user.auth.history}/${userId}`,
        { params: { page, size } }
      )

      set({ loading: false })
      return response.data
    } catch (error: any) {
      set({ error: error.message || 'Failed to fetch history', loading: false })

      return {
        content: [],
        totalElements: 0,
        totalPages: 0,
        size,
        number: page,
        first: true,
        last: true,
        empty: true,
        sort: {
          empty: true,
          sorted: false,
          unsorted: true
        },
        offset: 0,
        pageNumber: page,
        pageSize: size,
        paged: true,
        unpaged: false,
        numberOfElements: 0
      }
    }
  }
}))
