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

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

    books: [],
    borrows: [],
    members: [],

    checkAuth: async () => {
        try {
            const res = await api.get("/auth/check")
            if (res.status === 200) {
                set({
                    isAuthenticated: true,
                    authUser: res.data.username,
                    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: async (username, password) => {
        try {
            const res = await api.post("/auth/login", { username, password })
            if (res.status === 200) {
                await get().checkAuth()
                toast.success('Login successful!')
                return { success: true }
            }
            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: async (username, password, age, role) => {
        try {
            const res = await api.post("/auth/register", { username, password, age, role })
            if (res.status === 201) {
                await get().checkAuth()
                toast.success('Account created successfully!')
                return { success: true }
            }
            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: async () => {
        try {
            const res = await api.post("/auth/logout")
            if (res.status === 200) {
                set({ isAuthenticated: false, authUser: null, authRole: null, authId: null, books: [], borrows: [], members: [] })
            }
        } catch (error) {
            // Still clear state even on error
        }
        set({ isAuthenticated: false, authUser: null, authRole: null, authId: null, books: [], borrows: [], members: [] })
        toast.success('Logged out successfully')
    },

    getBooks: async () => {
        try {
            const res = await api.get("/books")
            if (res.status === 200) {
                set({ books: res.data })
            }
        } catch (error) {
            toast.error('Failed to load books')
        }
    },

    addBook: async (title, author, description) => {
        try {
            const res = await api.post("/books/add", { title, author, description })
            if (res.status === 201) {
                await get().getBooks()
                toast.success(res.data.message || 'Book added successfully')
                return { success: true }
            }
            return { success: false }
        } catch (error) {
            toast.error(error.response?.data?.message || 'Failed to add book')
            return { success: false }
        }
    },

    updateBook: async (id, title, author, description) => {
        try {
            const res = await api.put(`/books/${id}`, { title, author, description })
            if (res.status === 200) {
                await get().getBooks()
                toast.success(res.data.message || 'Book updated successfully')
                return { success: true }
            }
            return { success: false }
        } catch (error) {
            toast.error(error.response?.data?.message || 'Failed to update book')
            return { success: false }
        }
    },

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

    getBorrows: async () => {
        try {
            const res = await api.get("/borrows")
            if (res.status === 200) {
                set({ borrows: res.data })
            }
        } catch (error) {
            toast.error('Failed to load borrow records')
        }
    },

    addBorrow: async (bookId, clientId, dueDate) => {
        try {
            const res = await api.post("/borrows/add", { bookId, clientId, dueDate })
            if (res.status === 201) {
                await get().getBorrows()
                toast.success(res.data.message || 'Borrow record added')
                return { success: true }
            }
            return { success: false }
        } catch (error) {
            toast.error(error.response?.data?.message || 'Failed to add borrow record')
            return { success: false }
        }
    },

    updateBorrow: async (id, bookId, clientId, dueDate) => {
        try {
            const res = await api.put(`/borrows/${id}`, { bookId, clientId, dueDate })
            if (res.status === 200) {
                await get().getBorrows()
                toast.success(res.data.message || 'Borrow record updated')
                return { success: true }
            }
            return { success: false }
        } catch (error) {
            toast.error(error.response?.data?.message || 'Failed to update borrow record')
            return { success: false }
        }
    },

    deleteBorrow: async (id) => {
        try {
            const res = await api.delete(`/borrows/${id}`)
            if (res.status === 200) {
                await get().getBorrows()
                toast.success(res.data.message || 'Borrow record deleted')
                return { success: true }
            }
            return { success: false }
        } catch (error) {
            toast.error(error.response?.data?.message || 'Failed to delete borrow record')
            return { success: false }
        }
    },

    getMembers: async () => {
        try {
            const res = await api.get("/members")
            if (res.status === 200) {
                set({ members: res.data })
            }
        } catch (error) {
            toast.error('Failed to load members')
        }
    },

    returnBook: async (borrowId) => {
        try {
            const res = await api.delete(`/borrows/${borrowId}`)
            if (res.status === 200) {
                await get().getBorrows()
                await get().getBooks()
                toast.success(res.data.message || 'Book returned successfully')
                return { success: true }
            }
            return { success: false }
        } catch (error) {
            toast.error(error.response?.data?.message || 'Failed to return book')
            return { success: false }
        }
    }
}))

export default useStore