import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"
import Cookies from 'js-cookie'
import axios from 'axios'

interface CartItem {
    uuid: string | null,
    id: string | null,
    price: number,
    quantity: number
    variant: ProductVariant

}

interface CartState {
    items: CartItem[];
    totalQuantity: number;
    totalPrice: number;
    stockout: boolean;
    discountAmount: number
    discountCode?: string
}

const isAuthenticated = (): boolean => {

    return !!localStorage.getItem('authenticated')
}


export const fetchCartFromBackend = createAsyncThunk('cart/fetchCart', async () => {

    const response = await axios.get('/api/cart')

    return response.data.mssg

})

export const sendCartToBackend = createAsyncThunk('cart/sendCart', async (items: CartItem[]) => {

    const response = await axios.post('/api/cart', {
        items: items
    })

    return response.data
})

export const addItemToBackendCart = createAsyncThunk('cart/addItemToBackend', async (variant_id: number) => {

    const response = await axios.post(`/api/cart/addItem/${variant_id}`)

    return response.data

})
export const removeItemFromBackendCart = createAsyncThunk('cart/removeItemFromBackend', async (variant_id: number) => {
    const response = await axios.delete(`/api/cart/removeItem/${variant_id}`)

    return response.data
})

export const decreaseItemFromBackendCart = createAsyncThunk('cart/decreaseItemFromBackend', async (variant_id: number) => {

    const response = await axios.post(`/api/cart/removeItem/${variant_id}`)

    return response.data

})


export const mergeCartWithBackend = createAsyncThunk('cart/mergeCart', async (items: CartItem[]) => {

    const response = await axios.post('/api/cart/mergeCart', {
        items: items
    })
    return response.data.mssg
})



const loadCartFromCookies = () => {


    if (typeof window === 'undefined') {
        return {
            items: [],
            totalQuantity: 0,
            totalPrice: 0,
            stockout: false,
            discountAmount: 0
        }
    }


    const cookieData = localStorage.getItem('cart')

    if (!cookieData) {
        return {
            items: [],
            totalQuantity: 0,
            totalPrice: 0,
            stockout: false,
            discountAmount: 0
        }
    }

    const parsed = JSON.parse(cookieData)

    console.log(parsed)
    console.log(`Items length - ${parsed.items.length}`)

    let totalQuantity = 0
    let totalPrice = 0

    parsed.items.forEach((item: CartItem) => {
        totalQuantity += item.quantity
        totalPrice += item.quantity * item.price
    })

    return {
        items: parsed.items,
        totalQuantity: totalQuantity,
        totalPrice: totalPrice,
        stockout: false,
        discountAmount: 0
    }
}


const initialState: CartState = loadCartFromCookies()

const cartSlice = createSlice({
    name: 'cart',
    initialState,
    reducers: {
        addItemToCart: (state, action: { payload: ProductVariant }) => {

            const newItem = action.payload

            console.log(newItem)

            const cartItem: CartItem = {
                uuid: newItem.uuid,
                id: newItem.id,
                variant: newItem,
                price: newItem.special_price,
                quantity: 1
            }

            const existingItemIndex = state.items.findIndex(item => item.variant.uuid === newItem.uuid)

            if (existingItemIndex !== -1) {

                state.items[existingItemIndex].quantity += 1
            }
            else {
                console.log("ADDING NEW ITEM TO CART")
                state.items.push(cartItem)
                console.log(state.items)
            }
            state.totalQuantity += 1
            state.totalPrice += cartItem.price


            // console.log(state.items.length, "LENGTH")

            var itms = state.items.map(item => ({
                uuid: item.variant.uuid,
                quantity: item.quantity,
                price: item.price,
                variant: item.variant
            }))

            localStorage.setItem(
                'cart',
                JSON.stringify({
                    items: itms
                })
            )

            console.log(Cookies.get('cart'))


        },
        removeItemFromCart: (state, action: { payload: string }) => {
            const uuid = action.payload

            const removedItem = state.items.find((item) => item.variant.uuid == uuid)

            if (removedItem) {
                state.totalPrice -= removedItem.quantity * removedItem.price
                state.totalQuantity -= removedItem.quantity

                state.items = state.items.filter((item) => item.variant.uuid != uuid)
            }


            localStorage.setItem(
                'cart',
                JSON.stringify({
                    items: state.items.map(item => ({
                        uuid: item.variant.uuid,
                        quantity: item.quantity,
                        price: item.price,
                        variant: item.variant

                    }))
                })
            )
        },
        decreaseCartItemCount: (state, action: { payload: string }) => {
            const uuid = action.payload

            const existingItem = state.items.find((item) => item.variant.uuid == uuid)
            const existingItemIndex = state.items.findIndex((item) => item.variant.uuid == uuid)

            if (existingItem && existingItem.quantity > 1) {
                state.items[existingItemIndex].quantity = state.items[existingItemIndex].quantity - 1

            }
            else {
                state.items = state.items.filter((item) => item.variant.uuid != uuid)

            }

            state.totalQuantity -= 1
            if (existingItem) {
                state.totalPrice -= existingItem.price
            }


            localStorage.setItem(
                'cart',
                JSON.stringify({
                    items: state.items.map(item => ({
                        uuid: item.variant.uuid,
                        quantity: item.quantity,
                        price: item.price,
                        variant: item.variant
                    }))
                })
            )

        },
        increaseCartItemCount: (state, action: { payload: string }) => {
            const uuid = action.payload

            const existingItemIndex = state.items.findIndex((item) => item.variant.uuid === uuid)
            const existingItem = state.items.find((item) => item.variant.uuid === uuid)


            state.items[existingItemIndex].quantity = state.items[existingItemIndex].quantity + 1


            if (existingItem) {
                state.totalPrice += existingItem.price
                state.totalQuantity += 1
            }

            localStorage.setItem(
                'cart',
                JSON.stringify({
                    items: state.items.map(item => ({
                        uuid: item.variant.uuid,
                        quantity: item.quantity,
                        price: item.price,
                        variant: item.variant
                    }))
                })
            )

        }
    },
    extraReducers: (builder) => {
        builder.addCase(fetchCartFromBackend.fulfilled, (state, action) => {
            // console.log('CART DETAILES FETCHED')
            state.totalPrice = action.payload.totalPrice
            state.totalQuantity = action.payload.totalQuantity
            state.items = action.payload.cart.CartItem.slice()
            state.stockout = action.payload.stockOut
            state.discountAmount = action.payload.cart.discountAmount || 0
            state.discountCode = action.payload.cart.discountCode || undefined

            localStorage.setItem(
                'cart',
                JSON.stringify({
                    items: state.items.map(item => ({
                        uuid: item.variant.uuid,
                        quantity: item.quantity,
                        price: item.price,
                        variant: item.variant
                    }))
                })
            )

        }),

            builder.addCase(sendCartToBackend.fulfilled, (state, action) => {
                console.log('cart synced successfully', action.payload)


            }),

            builder.addCase(addItemToBackendCart.fulfilled, (state, action) => {
                console.log('Item has been added to backend cart')
                console.log(action.payload)

                const updatedCart = action.payload.updatedCart


                state.totalQuantity = updatedCart.totalQuantity
                state.totalPrice = updatedCart.totalPrice

                state.items = updatedCart.CartItem



            }),
            builder.addCase(removeItemFromBackendCart.fulfilled, (state, action) => {
                console.log('Item has been removed from backend cart')
                console.log(action.payload)
                const updatedCart = action.payload.updatedCart

                state.totalQuantity = updatedCart.totalQuantity
                state.totalPrice = updatedCart.totalPrice
                state.items = updatedCart.CartItem
                state.stockout = action.payload.stockout

            }),
            builder.addCase(decreaseItemFromBackendCart.fulfilled, (state, action) => {
                console.log('Item quantity has been reduced from backend cart')
                console.log(action.payload)

                const updatedCart = action.payload.updatedCart
                state.totalQuantity = updatedCart.totalQuantity
                state.totalPrice = updatedCart.totalPrice
                state.items = updatedCart.CartItem

                // if (action.payload.cartItem){
                //      const itemIndex = state.items.findIndex(item => item.variant.id === action.payload.cartItem.variant.id)
                //      state.items[itemIndex] = action.payload.cartItem
                // }

            }),
            builder.addCase(mergeCartWithBackend.fulfilled, (state, action) => {
                console.log('CART MERGED WITH BACKEND')
                console.log(action.payload)
            })


    }
})





export const { addItemToCart, removeItemFromCart, decreaseCartItemCount, increaseCartItemCount } = cartSlice.actions
export default cartSlice.reducer
