<script setup>
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'
import { usePageTitle } from '../composables/Core/usePageTitle'
import { useNavigate } from '../composables/Core/useNavigate'
import { useModal } from '../composables/Core/useModal'
import LoadingSpinner from '../Components/LoadingSpinner.vue'
import BackButton from '../Components/Core/BackButton.vue'

usePageTitle('My Cart')
const { navigate } = useNavigate()
const modal = useModal()

const cart = ref(null)
const items = ref([])
const isLoading = ref(true)
const isUpdating = ref(false)

const cartTotal = computed(() => {
    return items.value.reduce((sum, item) => sum + (item.price * item.quantity), 0)
})

const fetchCart = async () => {
    isLoading.value = true
    try {
        const response = await axios.post('/cart/get')
        if (response.data && response.data.success) {
            cart.value = response.data.cart
            items.value = response.data.items || []
        }
    } catch (error) {
        console.error('Error fetching cart:', error)
    } finally {
        isLoading.value = false
    }
}

const updateQuantity = async (item, delta) => {
    const newQuantity = item.quantity + delta
    if (newQuantity < 1) return
    
    isUpdating.value = true
    try {
        const response = await axios.post('/cart/update', {
            item_hash: item.hashkey,
            quantity: newQuantity
        })
        if (response.data.success) {
            item.quantity = newQuantity
        }
    } catch (error) {
        console.error('Error updating quantity:', error)
    } finally {
        isUpdating.value = false
    }
}

const removeItem = async (itemHash) => {
    modal.yesNoModal({
        title: 'Remove Item',
        body: 'Are you sure you want to remove this item from your cart?',
        onYes: async () => {
            try {
                const response = await axios.post('/cart/remove', { item_hash: itemHash })
                if (response.data.success) {
                    items.value = items.value.filter(i => i.hashkey !== itemHash)
                }
            } catch (error) {
                console.error('Error removing item:', error)
            }
        }
    })
}

const clearCart = async () => {
    modal.yesNoModal({
        title: 'Clear Cart',
        body: 'Are you sure you want to clear all items from your cart?',
        onYes: async () => {
            try {
                const response = await axios.post('/cart/clear')
                if (response.data.success) {
                    items.value = []
                }
            } catch (error) {
                console.error('Error clearing cart:', error)
            }
        }
    })
}

const checkout = () => {
    // Navigate to checkout or transaction creation page
    navigate({ page: 'AddTransaction', props: { scope: 'cart' } })
}

onMounted(() => {
    fetchCart()
})
</script>

<template>
    <div class="cart-page pb-5">
        <div class="tf-container mt-4 mb-3">
            <div class="d-flex align-items-center justify-content-between">
                <div class="d-flex align-items-center">
                    <BackButton />
                    <h2 class="fw_8 ms-3 mb-0 premium-title">Shopping Cart</h2>
                </div>
                <button v-if="items.length > 0" @click="clearCart" class="btn-clear text-danger">
                    <i class="far fa-trash-alt me-1"></i> Clear All
                </button>
            </div>
        </div>

        <div v-if="isLoading" class="tf-container text-center py-5 mt-5">
            <LoadingSpinner size="large" />
            <p class="text-muted mt-3">Loading your cart...</p>
        </div>

        <div v-else-if="items.length === 0" class="tf-container text-center py-5 mt-5">
            <div class="empty-cart-illustration mb-4">
                <i class="fas fa-shopping-basket text-light" style="font-size: 5rem;"></i>
            </div>
            <h3 class="fw_7">Your cart is empty</h3>
            <p class="text-muted">Looks like you haven't added anything to your cart yet.</p>
            <button @click="navigate({ page: 'MarketProduct' })" class="btn btn-primary rounded-pill px-4 py-2 mt-3 fw_6">
                Continue Shopping
            </button>
        </div>

        <div v-else class="tf-container">
            <div class="cart-items-list mb-4">
                <div v-for="item in items" :key="item.hashkey" class="cart-item-card animate-fade-in">
                    <div class="item-image-wrapper">
                        <img v-if="item.product?.photourl && item.product.photourl.length > 0" 
                             :src="'/RequestData/File/' + item.product.photourl[0]" 
                             class="item-img"
                             @error="$event.target.style.display = 'none'">
                        <div v-else class="item-img-placeholder">
                            <i class="fas fa-box"></i>
                        </div>
                    </div>
                    
                    <div class="item-details">
                        <h5 class="fw_7 mb-1">{{ item.product?.name || 'Unknown Product' }}</h5>
                        <p class="text-muted small mb-2">{{ item.product?.category || 'General' }}</p>
                        <div class="item-price fw_7 text-primary">₱{{ item.price.toLocaleString() }}</div>
                    </div>

                    <div class="item-actions">
                        <div class="quantity-control shadow-sm rounded-pill">
                            <button @click="updateQuantity(item, -1)" class="btn-qty" :disabled="item.quantity <= 1 || isUpdating">
                                <i class="fas fa-minus"></i>
                            </button>
                            <span class="qty-num fw_7">{{ item.quantity }}</span>
                            <button @click="updateQuantity(item, 1)" class="btn-qty" :disabled="isUpdating">
                                <i class="fas fa-plus"></i>
                            </button>
                        </div>
                        <button @click="removeItem(item.hashkey)" class="btn-remove" :disabled="isUpdating">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                </div>
            </div>

            <!-- Cart Summary Panel -->
            <div class="cart-summary-panel glass-card shadow-lg p-4 mb-5">
                <div class="d-flex justify-content-between mb-2">
                    <span class="text-muted">Subtotal ({{ items.length }} items)</span>
                    <span class="fw_6">₱{{ cartTotal.toLocaleString() }}</span>
                </div>
                <div class="d-flex justify-content-between mb-3 pb-3 border-bottom">
                    <span class="text-muted">Processing Fee</span>
                    <span class="text-success fw_6">FREE</span>
                </div>
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <span class="fw_8 fs-5">Order Total</span>
                    <span class="fw_8 fs-4 text-primary">₱{{ cartTotal.toLocaleString() }}</span>
                </div>
                
                <button @click="checkout" class="btn btn-primary w-100 py-3 rounded-xl fw_8 fs-5 glow-button">
                    Proceed to Checkout <i class="fas fa-arrow-right ms-2 opacity-50"></i>
                </button>
            </div>
        </div>
    </div>
</template>

<style scoped>
.premium-title {
    font-family: 'Outfit', sans-serif;
    color: #1a202c;
    letter-spacing: -0.025em;
}

:global(.dark-mode) .premium-title {
    color: #f7fafc;
}

.btn-clear {
    background: transparent;
    border: none;
    font-size: 0.85rem;
    font-weight: 600;
    padding: 5px 10px;
}

.cart-items-list {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.cart-item-card {
    display: flex;
    align-items: center;
    background: white;
    border-radius: 16px;
    padding: 12px;
    box-shadow: 0 4px 15px rgba(0,0,0,0.05);
    border: 1px solid rgba(0,0,0,0.03);
    transition: transform 0.2s;
}

:global(.dark-mode) .cart-item-card {
    background: #2d3748;
    border-color: rgba(255,255,255,0.05);
    box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}

.cart-item-card:hover {
    transform: translateY(-2px);
}

.item-image-wrapper {
    width: 80px;
    height: 80px;
    border-radius: 12px;
    overflow: hidden;
    background: #f7fafc;
    flex-shrink: 0;
}

:global(.dark-mode) .item-image-wrapper {
    background: #1a202c;
}

.item-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.item-img-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #cbd5e0;
    font-size: 1.5rem;
}

.item-details {
    flex-grow: 1;
    padding-left: 16px;
}

.item-actions {
    display: flex;
    align-items: center;
    gap: 12px;
}

.quantity-control {
    display: flex;
    align-items: center;
    background: #f8fafc;
    padding: 2px;
}

:global(.dark-mode) .quantity-control {
    background: #1a202c;
}

.btn-qty {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    border: none;
    background: white;
    color: #4a5568;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.8rem;
    transition: all 0.2s;
}

:global(.dark-mode) .btn-qty {
    background: #2d3748;
    color: #e2e8f0;
}

.btn-qty:hover:not(:disabled) {
    background: #edf2f7;
    color: #2b6cb0;
}

.qty-num {
    width: 32px;
    text-align: center;
}

.btn-remove {
    background: #fff5f5;
    color: #f56565;
    border: none;
    width: 32px;
    height: 32px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.9rem;
}

:global(.dark-mode) .btn-remove {
    background: rgba(245, 101, 101, 0.1);
}

.cart-summary-panel {
    border-radius: 24px;
    background: white;
}

:global(.dark-mode) .cart-summary-panel {
    background: #2d3748;
}

.rounded-xl {
    border-radius: 16px;
}

.glow-button {
    box-shadow: 0 4px 14px 0 rgba(70, 107, 255, 0.39);
    transition: all 0.2s;
}

.glow-button:hover {
    box-shadow: 0 6px 20px rgba(70, 107, 255, 0.45);
    background-color: #3b82f6;
    transform: scale(1.01);
}

.animate-fade-in {
    animation: fadeIn 0.4s ease-out;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
}
</style>
