import { create } from 'zustand'
import api from './api.js'
import toast from 'react-hot-toast'

const useStore = create((set, get) => ({
  // Auth state
  isAuthenticated: false,
  authUser: null,
  authRole: null,
  authId: null,

  // Data state
  clients: [],
  cars: [],
  rentals: [],
  dashboardStats: null,
  clientDashboardStats: null,

  // Check auth
  checkAuth: async () => {
    try {
      const res = await api.get("/auth/check")
      if (res.status === 200) {
        set({
          isAuthenticated: true,
          authUser: res.data.fullName,
          authRole: res.data.role,
          authId: res.data.id
        })
      } else {
        set({ isAuthenticated: false, authUser: null, authRole: null, authId: null })
      }
    } catch (error) {
      set({ isAuthenticated: false, authUser: null, authRole: null, authId: null })
    }
  },

  // Login
  login: async (email, password) => {
    try {
      const res = await api.post("/auth/login", { email, password })
      if (res.status === 200) {
        await get().checkAuth()
        toast.success('Login successful!')
        const redirectPath = res.data.role === 'admin' ? '/admin/dashboard' : '/client/dashboard'
        return { success: true, redirectPath }
      }
      return { success: false, message: res.data.message || "Login failed" }
    } catch (error) {
      const msg = error.response?.data?.message || "Invalid credentials"
      toast.error(msg)
      return { success: false, message: msg }
    }
  },

  // Register
  register: async (userData) => {
    try {
      const res = await api.post("/auth/register", userData)
      if (res.status === 201) {
        await get().checkAuth()
        toast.success('Registration successful!')
        const redirectPath = userData.role === 'admin' ? '/admin/dashboard' : '/client/dashboard'
        return { success: true, redirectPath }
      }
      return { success: false, message: res.data.message || "Registration failed" }
    } catch (error) {
      const msg = error.response?.data?.message || "Registration failed"
      toast.error(msg)
      return { success: false, message: msg }
    }
  },

  // Logout
  logout: async () => {
    try {
      await api.post("/auth/logout")
    } catch (error) {
      // Continue with logout even if API fails
    }
    set({ isAuthenticated: false, authUser: null, authRole: null, authId: null, clients: [], cars: [], rentals: [], dashboardStats: null, clientDashboardStats: null })
    toast.success('Logged out successfully')
  },

  // ============ CLIENTS ============
  getClients: async (params = {}) => {
    try {
      const res = await api.get("/users", { params })
      set({ clients: res.data.clients })
      return res.data
    } catch (error) {
      toast.error('Failed to load clients')
      return null
    }
  },

  createClient: async (clientData) => {
    try {
      const res = await api.post("/users", clientData)
      if (res.status === 201) {
        await get().getClients()
        toast.success('Client created successfully')
        return { success: true }
      }
      return { success: false }
    } catch (error) {
      toast.error(error.response?.data?.message || 'Failed to create client')
      return { success: false }
    }
  },

  updateClient: async (id, clientData) => {
    try {
      const res = await api.put(`/users/${id}`, clientData)
      if (res.status === 200) {
        await get().getClients()
        toast.success('Client updated successfully')
        return { success: true }
      }
      return { success: false }
    } catch (error) {
      toast.error(error.response?.data?.message || 'Failed to update client')
      return { success: false }
    }
  },

  deleteClient: async (id) => {
    try {
      const res = await api.delete(`/users/${id}`)
      if (res.status === 200) {
        await get().getClients()
        toast.success('Client deleted successfully')
        return { success: true }
      }
      return { success: false }
    } catch (error) {
      toast.error(error.response?.data?.message || 'Failed to delete client')
      return { success: false }
    }
  },

  // ============ CARS ============
  getCars: async (params = {}) => {
    try {
      const res = await api.get("/cars", { params })
      set({ cars: res.data.cars })
      return res.data
    } catch (error) {
      toast.error('Failed to load cars')
      return null
    }
  },

  createCar: async (carData) => {
    try {
      const res = await api.post("/cars", carData)
      if (res.status === 201) {
        await get().getCars()
        toast.success('Car created successfully')
        return { success: true }
      }
      return { success: false }
    } catch (error) {
      toast.error(error.response?.data?.message || 'Failed to create car')
      return { success: false }
    }
  },

  updateCar: async (id, carData) => {
    try {
      const res = await api.put(`/cars/${id}`, carData)
      if (res.status === 200) {
        await get().getCars()
        toast.success('Car updated successfully')
        return { success: true }
      }
      return { success: false }
    } catch (error) {
      toast.error(error.response?.data?.message || 'Failed to update car')
      return { success: false }
    }
  },

  deleteCar: async (id) => {
    try {
      const res = await api.delete(`/cars/${id}`)
      if (res.status === 200) {
        await get().getCars()
        toast.success('Car deleted successfully')
        return { success: true }
      }
      return { success: false }
    } catch (error) {
      toast.error(error.response?.data?.message || 'Failed to delete car')
      return { success: false }
    }
  },

  // ============ RENTALS ============
  getRentals: async (params = {}) => {
    try {
      const res = await api.get("/rentals", { params })
      set({ rentals: res.data.rentals })
      return res.data
    } catch (error) {
      toast.error('Failed to load rentals')
      return null
    }
  },

  createRental: async (rentalData) => {
    try {
      const res = await api.post("/rentals", rentalData)
      if (res.status === 201) {
        await get().getRentals()
        await get().getCars()
        toast.success('Rental created successfully')
        return { success: true }
      }
      return { success: false }
    } catch (error) {
      toast.error(error.response?.data?.message || 'Failed to create rental')
      return { success: false }
    }
  },

  returnRental: async (id) => {
    try {
      const res = await api.put(`/rentals/${id}/return`)
      if (res.status === 200) {
        await get().getRentals()
        await get().getCars()
        toast.success('Car returned successfully')
        return { success: true }
      }
      return { success: false }
    } catch (error) {
      toast.error(error.response?.data?.message || 'Failed to return car')
      return { success: false }
    }
  },

  deleteRental: async (id) => {
    try {
      const res = await api.delete(`/rentals/${id}`)
      if (res.status === 200) {
        await get().getRentals()
        await get().getCars()
        toast.success('Rental deleted successfully')
        return { success: true }
      }
      return { success: false }
    } catch (error) {
      toast.error(error.response?.data?.message || 'Failed to delete rental')
      return { success: false }
    }
  },

  // ============ DASHBOARD ============
  getDashboardStats: async () => {
    try {
      const res = await api.get("/dashboard")
      set({ dashboardStats: res.data })
      return res.data
    } catch (error) {
      toast.error('Failed to load dashboard stats')
      return null
    }
  },

  getClientDashboardStats: async () => {
    try {
      const res = await api.get("/dashboard/client/stats")
      set({ clientDashboardStats: res.data })
      return res.data
    } catch (error) {
      toast.error('Failed to load dashboard stats')
      return null
    }
  }
}))

export default useStore