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'
export type GetUserHistoryParams = {
  userId?: string
  page?: number
  size?: number
  sortBy?: string
  direction?: 'asc' | 'desc'
}

type AuthStore = {
  authData: AuthenticationResponseBo | null
  loading: boolean
  error: string | null
  login: (credentials: AuthenticationRequest) => Promise<void>
  logout: () => Promise<void>
  getUserHistory: (params?: GetUserHistoryParams) => 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)
      localStorage.setItem("userUuid", token.sub)
      
      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 (params = {}): Promise<Pageable<UserConnectionHistoryDto>> => {
    set({ loading: true, error: null })
  
    const {
      page = 0,
      size = 10,
      userId,
      sortBy = 'loginDateTime',
      direction = 'desc'
    } = params
  
    try {
      const id = userId ?? localStorage.getItem("userId")
      if (!id) throw new Error("Missing userId")
  
      const response = await axiosInstance.get<Pageable<UserConnectionHistoryDto>>(
        `${userEndpoints.user.auth.history}/${id}`,
        {
          params: { page, size, sortBy, direction }
        }
      )
  
      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
      }
    }
  }
  
  
  
}))
