<script setup>
import { onMounted, ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import useCashRegister from '@Stores/cashRegister';
import GoogleIcon from '@Shared/GoogleIcon.vue';
import OpenModal from './OpenModal.vue';
import CloseModal from './CloseModal.vue';

/** Router */
const router = useRouter();

/** Store */
const cashRegisterStore = useCashRegister();

/** Estado */
const showOpenModal = ref(false);
const showCloseModal = ref(false);
const refreshing = ref(false);

/** Computed */
const isOpen = computed(() => cashRegisterStore.hasOpenRegister);
const currentRegister = computed(() => cashRegisterStore.currentRegister);
const loading = computed(() => cashRegisterStore.loading);

/** M\u00e9todos */
const openCashRegister = async (initialCash) => {
    const result = await cashRegisterStore.openRegister(initialCash);

    if (result.success) {
        Notify.success('Caja abierta exitosamente');
        showOpenModal.value = false;
    } else {
        Notify.error(result.error || 'Error al abrir la caja');
    }
};

const closeCashRegister = async (closeData) => {
    const result = await cashRegisterStore.closeRegister(closeData);

    if (result.success) {
        Notify.success('Caja cerrada exitosamente - Corte generado');
        showCloseModal.value = false;

        // Opcional: Redirigir al historial o mostrar el resumen
        setTimeout(() => {
            router.push({ name: 'pos.cashRegister.history' });
        }, 1500);
    } else {
        Notify.error(result.error || 'Error al cerrar la caja');
    }
};

const refreshData = async () => {
    refreshing.value = true;
    await cashRegisterStore.refreshCurrentRegister();
    refreshing.value = false;
};

const goToHistory = () => {
    router.push({ name: 'pos.cashRegister.history' });
};

const goToPoint = () => {
    router.push({ name: 'pos.point' });
};

/** Ciclos */
onMounted(async () => {
    await cashRegisterStore.loadCurrentRegister();
});
</script>

<template>
    <div class="min-h-screen bg-gray-50 dark:bg-gray-900 p-6">
        <!-- Header -->
        <div class="max-w-7xl mx-auto mb-6">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900 dark:text-gray-100 flex items-center gap-3">
                        <GoogleIcon name="point_of_sale" class="text-4xl" />
                        Caja Registradora
                    </h1>
                    <p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
                        Gestión de apertura y cierre de caja
                    </p>
                </div>
                <div class="flex items-center gap-3">
                    <button
                        @click="refreshData"
                        :disabled="refreshing"
                        class="flex items-center gap-2 px-4 py-2 text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
                        title="Actualizar"
                    >
                        <GoogleIcon :name="refreshing ? 'sync' : 'refresh'" :class="{ 'animate-spin': refreshing }" />
                    </button>
                    <button
                        @click="goToHistory"
                        class="flex items-center gap-2 px-4 py-2 text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
                    >
                        <GoogleIcon name="history" />
                        Historial
                    </button>
                </div>
            </div>
        </div>

        <!-- Loading State -->
        <div v-if="loading && !currentRegister" class="max-w-7xl mx-auto">
            <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-12">
                <div class="flex flex-col items-center justify-center">
                    <GoogleIcon name="sync" class="text-6xl text-gray-400 animate-spin mb-4" />
                    <p class="text-gray-600 dark:text-gray-400">Cargando información de caja...</p>
                </div>
            </div>
        </div>

        <!-- Caja Cerrada - Mostrar opción para abrir -->
        <div v-else-if="!isOpen" class="max-w-4xl mx-auto">
            <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
                <!-- Estado -->
                <div class="bg-gradient-to-r from-red-500 to-red-600 p-6">
                    <div class="flex items-center gap-4 text-white">
                        <div class="w-16 h-16 bg-white/20 rounded-full flex items-center justify-center">
                            <GoogleIcon name="lock" class="text-4xl" />
                        </div>
                        <div>
                            <h2 class="text-2xl font-bold">Caja Cerrada</h2>
                            <p class="text-red-100 mt-1">No hay ninguna caja abierta actualmente</p>
                        </div>
                    </div>
                </div>

                <!-- Contenido -->
                <div class="p-8">
                    <div class="text-center mb-8">
                        <GoogleIcon name="info" class="text-6xl text-gray-300 dark:text-gray-600 mx-auto mb-4" />
                        <h3 class="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-2">
                            Necesitas abrir la caja para comenzar
                        </h3>
                        <p class="text-gray-600 dark:text-gray-400">
                            Al abrir la caja podrás registrar ventas y realizar transacciones.
                            Ingresa el monto inicial en efectivo para comenzar tu turno.
                        </p>
                    </div>

                    <div class="flex justify-center gap-4">
                        <button
                            @click="goToHistory"
                            class="flex items-center gap-2 px-6 py-3 text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
                        >
                            <GoogleIcon name="history" class="text-xl" />
                            Ver Historial
                        </button>
                        <button
                            @click="showOpenModal = true"
                            class="flex items-center gap-2 px-6 py-3 bg-green-600 hover:bg-green-700 text-white font-semibold rounded-lg shadow-lg shadow-green-600/30 transition-all"
                        >
                            <GoogleIcon name="lock_open" class="text-xl" />
                            Abrir Caja
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Caja Abierta - Mostrar resumen -->
        <div v-else class="max-w-7xl mx-auto space-y-6">
            <!-- Estado Actual -->
            <div class="bg-white dark:bg-gray-800 rounded-xl shadow-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
                <!-- Header -->
                <div class="bg-gradient-to-r from-green-500 to-green-600 p-6">
                    <div class="flex items-center justify-between text-white">
                        <div class="flex items-center gap-4">
                            <div class="w-16 h-16 bg-white/20 rounded-full flex items-center justify-center">
                                <GoogleIcon name="lock_open" class="text-4xl" />
                            </div>
                            <div>
                                <h2 class="text-2xl font-bold">Caja Abierta</h2>
                                <p class="text-green-100 mt-1">Operando normalmente</p>
                            </div>
                        </div>
                        <div class="text-right">
                            <p class="text-green-100 text-sm">Abierta por</p>
                            <p class="text-xl font-semibold">{{ cashRegisterStore.openedBy }}</p>
                        </div>
                    </div>
                </div>

                <!-- Información de la Caja -->
                <div class="p-6">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <!-- Información General -->
                        <div class="space-y-4">
                            <h3 class="text-sm font-bold text-gray-900 dark:text-gray-100 uppercase tracking-wide border-b border-gray-200 dark:border-gray-700 pb-2">
                                Información General
                            </h3>
                            <div class="space-y-3">
                                <div class="flex justify-between items-center">
                                    <span class="text-sm text-gray-600 dark:text-gray-400">ID de Caja:</span>
                                    <span class="text-base font-semibold text-gray-900 dark:text-gray-100">
                                        #{{ cashRegisterStore.currentRegisterId }}
                                    </span>
                                </div>
                                <div class="flex justify-between items-center">
                                    <span class="text-sm text-gray-600 dark:text-gray-400">Fecha de Apertura:</span>
                                    <span class="text-base font-semibold text-gray-900 dark:text-gray-100">
                                        {{ new Date(cashRegisterStore.openedAt).toLocaleString('es-MX', {
                                            year: 'numeric',
                                            month: 'short',
                                            day: 'numeric',
                                            hour: '2-digit',
                                            minute: '2-digit'
                                        }) }}
                                    </span>
                                </div>
                                <div class="flex justify-between items-center">
                                    <span class="text-sm text-gray-600 dark:text-gray-400">Efectivo Inicial:</span>
                                    <span class="text-lg font-bold text-green-600 dark:text-green-400">
                                        ${{ cashRegisterStore.initialCash.toLocaleString('es-MX', { minimumFractionDigits: 2 }) }}
                                    </span>
                                </div>
                            </div>
                        </div>

                        <!-- Estadísticas de Ventas -->
                        <div class="space-y-4">
                            <h3 class="text-sm font-bold text-gray-900 dark:text-gray-100 uppercase tracking-wide border-b border-gray-200 dark:border-gray-700 pb-2">
                                Resumen de Ventas
                            </h3>
                            <div class="space-y-3">
                                <div class="flex justify-between items-center">
                                    <span class="text-sm text-gray-600 dark:text-gray-400">Total de Transacciones:</span>
                                    <span class="text-base font-semibold text-gray-900 dark:text-gray-100">
                                        {{ cashRegisterStore.transactionCount }}
                                    </span>
                                </div>
                                <div class="flex justify-between items-center">
                                    <span class="text-sm text-gray-600 dark:text-gray-400">Total Vendido:</span>
                                    <span class="text-lg font-bold text-blue-600 dark:text-blue-400">
                                        ${{ cashRegisterStore.totalSales.toLocaleString('es-MX', { minimumFractionDigits: 2 }) }}
                                    </span>
                                </div>
                                <div class="flex justify-between items-center">
                                    <span class="text-sm text-gray-600 dark:text-gray-400">Balance Estimado:</span>
                                    <span class="text-xl font-bold text-green-600 dark:text-green-400">
                                        ${{ cashRegisterStore.currentBalance.toLocaleString('es-MX', { minimumFractionDigits: 2 }) }}
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Tarjetas de Resumen -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <!-- Ventas en Efectivo -->
                <div class="bg-gradient-to-br from-green-50 to-green-100 dark:from-green-900/20 dark:to-green-800/20 border border-green-200 dark:border-green-800 rounded-xl p-6">
                    <div class="flex items-center gap-3 mb-3">
                        <div class="w-12 h-12 bg-green-500 rounded-lg flex items-center justify-center text-white">
                            <GoogleIcon name="payments" class="text-2xl" />
                        </div>
                        <div>
                            <p class="text-xs font-semibold text-green-700 dark:text-green-300 uppercase">Efectivo</p>
                            <p class="text-2xl font-bold text-green-900 dark:text-green-100">
                                ${{ cashRegisterStore.expectedCash.toLocaleString('es-MX', { minimumFractionDigits: 2 }) }}
                            </p>
                        </div>
                    </div>
                    <p class="text-xs text-green-600 dark:text-green-400">
                        Efectivo esperado en caja
                    </p>
                </div>

                <!-- Ventas con Tarjeta -->
                <div class="bg-gradient-to-br from-purple-50 to-purple-100 dark:from-purple-900/20 dark:to-purple-800/20 border border-purple-200 dark:border-purple-800 rounded-xl p-6">
                    <div class="flex items-center gap-3 mb-3">
                        <div class="w-12 h-12 bg-purple-500 rounded-lg flex items-center justify-center text-white">
                            <GoogleIcon name="credit_card" class="text-2xl" />
                        </div>
                        <div>
                            <p class="text-xs font-semibold text-purple-700 dark:text-purple-300 uppercase">Tarjeta</p>
                            <p class="text-2xl font-bold text-purple-900 dark:text-purple-100">
                                ${{ cashRegisterStore.cardSales.toLocaleString('es-MX', { minimumFractionDigits: 2 }) }}
                            </p>
                        </div>
                    </div>
                    <p class="text-xs text-purple-600 dark:text-purple-400">
                        Pagos con tarjeta
                    </p>
                </div>

                <!-- Total General -->
                <div class="bg-gradient-to-br from-blue-50 to-blue-100 dark:from-blue-900/20 dark:to-blue-800/20 border border-blue-200 dark:border-blue-800 rounded-xl p-6">
                    <div class="flex items-center gap-3 mb-3">
                        <div class="w-12 h-12 bg-blue-500 rounded-lg flex items-center justify-center text-white">
                            <GoogleIcon name="shopping_cart" class="text-2xl" />
                        </div>
                        <div>
                            <p class="text-xs font-semibold text-blue-700 dark:text-blue-300 uppercase">Total</p>
                            <p class="text-2xl font-bold text-blue-900 dark:text-blue-100">
                                ${{ cashRegisterStore.totalSales.toLocaleString('es-MX', { minimumFractionDigits: 2 }) }}
                            </p>
                        </div>
                    </div>
                    <p class="text-xs text-blue-600 dark:text-blue-400">
                        {{ cashRegisterStore.transactionCount }} transacciones
                    </p>
                </div>
            </div>

            <!-- Acciones -->
            <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-6">
                <h3 class="text-lg font-bold text-gray-900 dark:text-gray-100 mb-4">Acciones Rápidas</h3>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <button
                        @click="goToPoint"
                        class="flex items-center justify-center gap-2 px-6 py-4 bg-indigo-600 hover:bg-indigo-700 text-white font-semibold rounded-lg shadow-md transition-colors"
                    >
                        <GoogleIcon name="storefront" class="text-2xl" />
                        <span>Ir al Punto de Venta</span>
                    </button>
                    <button
                        @click="goToHistory"
                        class="flex items-center justify-center gap-2 px-6 py-4 bg-gray-600 hover:bg-gray-700 text-white font-semibold rounded-lg shadow-md transition-colors"
                    >
                        <GoogleIcon name="history" class="text-2xl" />
                        <span>Ver Historial</span>
                    </button>
                    <button
                        @click="showCloseModal = true"
                        class="flex items-center justify-center gap-2 px-6 py-4 bg-orange-600 hover:bg-orange-700 text-white font-semibold rounded-lg shadow-md transition-colors"
                    >
                        <GoogleIcon name="lock" class="text-2xl" />
                        <span>Cerrar Caja</span>
                    </button>
                </div>
            </div>
        </div>

        <!-- Modales -->
        <OpenModal
            :show="showOpenModal"
            @close="showOpenModal = false"
            @confirm="openCashRegister"
        />

        <CloseModal
            :show="showCloseModal"
            :cash-register="currentRegister"
            @close="showCloseModal = false"
            @confirm="closeCashRegister"
        />
    </div>
</template>
