<script setup>
import { ref, computed } from 'vue';
import Modal from '@Holos/Modal.vue';
import GoogleIcon from '@Shared/GoogleIcon.vue';

/** Props */
const props = defineProps({
    show: {
        type: Boolean,
        default: false
    },
    cashRegister: {
        type: Object,
        default: null
    }
});

/** Emits */
const emit = defineEmits(['close', 'confirm']);

/** Estado */
const finalCash = ref(0);
const notes = ref('');
const loading = ref(false);

/** Computed */
const initialCash = computed(() => parseFloat(props.cashRegister?.initial_cash || 0));
const totalSales = computed(() => parseFloat(props.cashRegister?.total_sales || 0));
const cashSales = computed(() => parseFloat(props.cashRegister?.cash_sales || 0));
const cardSales = computed(() => parseFloat(props.cashRegister?.card_sales || 0));
const transactionCount = computed(() => parseInt(props.cashRegister?.transaction_count || 0));

// Devoluciones
const totalReturns = computed(() => parseFloat(props.cashRegister?.total_returns || 0));
const cashReturns = computed(() => parseFloat(props.cashRegister?.cash_returns || 0));
const cardReturns = computed(() => parseFloat(props.cashRegister?.card_returns || 0));
const hasReturns = computed(() => totalReturns.value > 0);

// Ventas netas (ventas - devoluciones)
const netSales = computed(() => totalSales.value - totalReturns.value);
const netCashSales = computed(() => cashSales.value - cashReturns.value);

const expectedCash = computed(() => initialCash.value + netCashSales.value);
const difference = computed(() => finalCash.value - expectedCash.value);
const hasDifference = computed(() => Math.abs(difference.value) > 0.01);

const totalCashReceived = computed(() => 
    parseFloat(props.cashRegister?.total_cash_received || 0)
);

const totalChangeGiven = computed(() => 
    parseFloat(props.cashRegister?.total_change_given || 0)
);

/** Métodos */
const handleSubmit = () => {
    emit('confirm', {
        final_cash: finalCash.value,
        notes: notes.value
    });
};

const handleClose = () => {
    finalCash.value = 0;
    notes.value = '';
    loading.value = false;
    emit('close');
};
</script>

<template>
    <Modal :show="show" max-width="2xl" @close="handleClose">
        <div class="p-6">
            <!-- Header -->
            <div class="flex items-center justify-between mb-6">
                <div class="flex items-center gap-3">
                    <div class="flex items-center justify-center w-12 h-12 rounded-full bg-orange-100 dark:bg-orange-900/30">
                        <GoogleIcon name="lock" class="text-2xl text-orange-600 dark:text-orange-400" />
                    </div>
                    <h3 class="text-lg font-bold text-gray-900 dark:text-gray-100">
                        Cerrar Caja Registradora - Corte de Caja
                    </h3>
                </div>
                <button
                    @click="handleClose"
                    class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
                >
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                    </svg>
                </button>
            </div>

            <!-- Content -->
            <form @submit.prevent="handleSubmit" class="space-y-6">
                <!-- Resumen de Ventas -->
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <!-- Total Ventas -->
                    <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-4">
                        <div class="flex items-center gap-2 mb-2">
                            <GoogleIcon name="shopping_cart" class="text-blue-600 dark:text-blue-400" />
                            <p class="text-xs font-semibold text-blue-700 dark:text-blue-300 uppercase">Total Ventas</p>
                        </div>
                        <p class="text-2xl font-bold text-blue-900 dark:text-blue-100">
                            ${{ (totalSales || 0).toLocaleString('es-MX', { minimumFractionDigits: 2 }) }}
                        </p>
                        <p class="text-xs text-blue-600 dark:text-blue-400 mt-1">
                            {{ transactionCount }} transacciones
                        </p>
                    </div>

                    <!-- Ventas 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-4">
                        <div class="flex items-center gap-2 mb-2">
                            <GoogleIcon name="payments" class="text-green-600 dark:text-green-400" />
                            <p class="text-xs font-semibold text-green-700 dark:text-green-300 uppercase">Efectivo</p>
                        </div>
                        <p class="text-2xl font-bold text-green-900 dark:text-green-100">
                            ${{ (cashSales || 0).toLocaleString('es-MX', { minimumFractionDigits: 2 }) }}
                        </p>
                        <p class="text-xs text-green-600 dark:text-green-400 mt-1">
                            Ventas en efectivo
                        </p>
                    </div>

                    <!-- Ventas 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-4">
                        <div class="flex items-center gap-2 mb-2">
                            <GoogleIcon name="credit_card" class="text-purple-600 dark:text-purple-400" />
                            <p class="text-xs font-semibold text-purple-700 dark:text-purple-300 uppercase">Tarjeta</p>
                        </div>
                        <p class="text-2xl font-bold text-purple-900 dark:text-purple-100">
                            ${{ (cardSales || 0).toLocaleString('es-MX', { minimumFractionDigits: 2 }) }}
                        </p>
                        <p class="text-xs text-purple-600 dark:text-purple-400 mt-1">
                            Ventas con tarjeta
                        </p>
                    </div>
                </div>

                <!-- Devoluciones (si existen) -->
                <div v-if="hasReturns" class="bg-orange-50 dark:bg-orange-900/20 border border-orange-200 dark:border-orange-800 rounded-xl p-4">
                    <div class="flex items-center gap-2 mb-3">
                        <GoogleIcon name="assignment_return" class="text-orange-600 dark:text-orange-400" />
                        <h4 class="text-sm font-bold text-orange-900 dark:text-orange-100">
                            Devoluciones
                        </h4>
                    </div>
                    <div class="grid grid-cols-3 gap-4">
                        <div>
                            <p class="text-xs text-orange-700 dark:text-orange-300 uppercase mb-1">Total Devoluciones</p>
                            <p class="text-lg font-bold text-orange-900 dark:text-orange-100">
                                -${{ (totalReturns || 0).toLocaleString('es-MX', { minimumFractionDigits: 2 }) }}
                            </p>
                        </div>
                        <div>
                            <p class="text-xs text-orange-700 dark:text-orange-300 uppercase mb-1">Efectivo</p>
                            <p class="text-lg font-bold text-orange-900 dark:text-orange-100">
                                -${{ (cashReturns || 0).toLocaleString('es-MX', { minimumFractionDigits: 2 }) }}
                            </p>
                        </div>
                        <div>
                            <p class="text-xs text-orange-700 dark:text-orange-300 uppercase mb-1">Tarjeta</p>
                            <p class="text-lg font-bold text-orange-900 dark:text-orange-100">
                                -${{ (cardReturns || 0).toLocaleString('es-MX', { minimumFractionDigits: 2 }) }}
                            </p>
                        </div>
                    </div>
                    <div class="mt-3 pt-3 border-t border-orange-300 dark:border-orange-700">
                        <div class="flex justify-between items-center">
                            <span class="text-sm font-semibold text-orange-900 dark:text-orange-100">Ventas Netas:</span>
                            <span class="text-xl font-bold text-orange-900 dark:text-orange-100">
                                ${{ (netSales || 0).toLocaleString('es-MX', { minimumFractionDigits: 2 }) }}
                            </span>
                        </div>
                    </div>
                </div>

                <!-- Cálculo de Efectivo -->
                <div class="bg-gray-50 dark:bg-gray-800 rounded-xl p-5 space-y-4">
                    <h4 class="text-sm font-bold text-gray-900 dark:text-gray-100">
                        Resumen de Efectivo
                    </h4>

                    <div class="space-y-3">
                        <div class="flex justify-between items-center">
                            <span class="text-sm text-gray-600 dark:text-gray-400">Efectivo Inicial:</span>
                            <span class="text-base font-semibold text-gray-900 dark:text-gray-100">
                                ${{ (initialCash || 0).toLocaleString('es-MX', { minimumFractionDigits: 2 }) }}
                            </span>
                        </div>
                        
                        <!-- Desglose de flujo de efectivo -->
                        <div class="pl-4 border-l-2 border-green-500 space-y-2">
                            <div class="flex justify-between items-center text-sm">
                                <span class="text-gray-600 dark:text-gray-400">Efectivo Recibido:</span>
                                <span class="text-green-600 dark:text-green-400 font-semibold">
                                    + ${{ (totalCashReceived || 0).toLocaleString('es-MX', { minimumFractionDigits: 2 }) }}
                                </span>
                            </div>
                            <div class="flex justify-between items-center text-sm">
                                <span class="text-gray-600 dark:text-gray-400">Cambio Devuelto:</span>
                                <span class="text-red-600 dark:text-red-400 font-semibold">
                                    - ${{ (totalChangeGiven || 0).toLocaleString('es-MX', { minimumFractionDigits: 2 }) }}
                                </span>
                            </div>
                        </div>

                        <div class="flex justify-between items-center pt-2 border-t border-gray-300">
                            <span class="text-sm text-gray-600 dark:text-gray-400">Ventas en Efectivo:</span>
                            <span class="text-base font-semibold text-green-600 dark:text-green-400">
                                = ${{ (cashSales || 0).toLocaleString('es-MX', { minimumFractionDigits: 2 }) }}
                            </span>
                        </div>

                        <!-- Devoluciones en Efectivo -->
                        <div v-if="hasReturns" class="flex justify-between items-center text-sm">
                            <span class="text-gray-600 dark:text-gray-400">Devoluciones en Efectivo:</span>
                            <span class="text-orange-600 dark:text-orange-400 font-semibold">
                                - ${{ (cashReturns || 0).toLocaleString('es-MX', { minimumFractionDigits: 2 }) }}
                            </span>
                        </div>

                        <!-- Ventas Netas en Efectivo -->
                        <div v-if="hasReturns" class="flex justify-between items-center pt-2 border-t border-gray-300">
                            <span class="text-sm font-bold text-gray-900 dark:text-gray-100">Ventas Netas en Efectivo:</span>
                            <span class="text-base font-bold text-green-600 dark:text-green-400">
                                = ${{ (netCashSales || 0).toLocaleString('es-MX', { minimumFractionDigits: 2 }) }}
                            </span>
                        </div>
                    </div>

                    <div class="border-t-2 border-gray-300 dark:border-gray-600 pt-3">
                        <div class="flex justify-between items-center">
                            <span class="text-base font-bold text-gray-900 dark:text-gray-100">
                                Efectivo Esperado:
                            </span>
                            <span class="text-xl font-bold text-blue-600 dark:text-blue-400">
                                ${{ (expectedCash || 0).toLocaleString('es-MX', { minimumFractionDigits: 2 }) }}
                            </span>
                        </div>
                    </div>
                </div>

                <!-- Ingresar Efectivo Final -->
                <div>
                    <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-2">
                        Efectivo Real en Caja *
                    </label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                            <span class="text-gray-500 dark:text-gray-400 text-lg font-semibold">$</span>
                        </div>
                        <input
                            v-model.number="finalCash"
                            type="number"
                            min="0"
                            step="0.01"
                            placeholder="0.00"
                            class="w-full pl-7 pr-4 py-2.5 text-lg font-semibold border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 placeholder-gray-400"
                            required
                            autofocus
                        />
                    </div>
                    <p class="mt-1.5 text-xs text-gray-500 dark:text-gray-400">
                        Cuenta el efectivo real que tienes en caja ahora
                    </p>
                </div>

                <!-- Diferencia -->
                <div v-if="finalCash > 0" class="bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-800 dark:to-gray-900 border border-gray-200 dark:border-gray-700 rounded-xl p-5">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1">Diferencia</p>
                            <p
                                class="text-3xl font-bold"
                                :class="{
                                    'text-green-600 dark:text-green-400': difference > 0,
                                    'text-red-600 dark:text-red-400': difference < 0,
                                    'text-gray-600 dark:text-gray-400': difference === 0
                                }"
                            >
                                {{ difference >= 0 ? '+' : '' }}${{ Math.abs(difference || 0).toLocaleString('es-MX', { minimumFractionDigits: 2 }) }}
                            </p>
                        </div>
                        <div class="text-right">
                            <div v-if="!hasDifference" class="flex items-center gap-2 text-green-600 dark:text-green-400">
                                <GoogleIcon name="check_circle" class="text-3xl" />
                                <span class="text-sm font-semibold">Cuadra</span>
                            </div>
                            <div v-else-if="difference > 0" class="flex items-center gap-2 text-green-600 dark:text-green-400">
                                <GoogleIcon name="trending_up" class="text-3xl" />
                                <span class="text-sm font-semibold">Sobrante</span>
                            </div>
                            <div v-else class="flex items-center gap-2 text-red-600 dark:text-red-400">
                                <GoogleIcon name="trending_down" class="text-3xl" />
                                <span class="text-sm font-semibold">Faltante</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Advertencia si hay diferencia -->
                <div v-if="hasDifference && finalCash > 0" class="bg-orange-50 dark:bg-orange-900/20 border border-orange-200 dark:border-orange-800 rounded-lg p-4">
                    <div class="flex items-start gap-2">
                        <GoogleIcon name="warning" class="text-orange-600 dark:text-orange-400 text-xl shrink-0 mt-0.5" />
                        <div>
                            <p class="text-sm text-orange-800 dark:text-orange-300 font-medium">
                                Se detectó una diferencia en el efectivo
                            </p>
                            <p class="text-xs text-orange-700 dark:text-orange-400 mt-1">
                                Por favor verifica el conteo antes de cerrar la caja. Puedes agregar una nota explicativa abajo.
                            </p>
                        </div>
                    </div>
                </div>

                <!-- Notas -->
                <div>
                    <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-2">
                        Notas / Observaciones
                    </label>
                    <textarea
                        v-model="notes"
                        rows="3"
                        maxlength="500"
                        class="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500 dark:bg-gray-800 dark:text-gray-100 resize-none"
                        placeholder="Agrega cualquier observación sobre el turno (opcional)"
                    ></textarea>
                    <p class="text-xs text-gray-500 dark:text-gray-400 mt-1 text-right">
                        {{ notes.length }}/500 caracteres
                    </p>
                </div>

                <!-- Footer -->
                <div class="flex items-center justify-end gap-3 pt-4 border-t border-gray-200 dark:border-gray-700">
                    <button
                        type="button"
                        @click="handleClose"
                        class="px-5 py-2.5 text-sm font-semibold 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 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 transition-colors"
                    >
                        Cancelar
                    </button>
                    <button
                        type="submit"
                        :disabled="loading || finalCash <= 0"
                        class="flex items-center gap-2 px-5 py-2.5 bg-orange-600 hover:bg-orange-700 text-white text-sm font-semibold rounded-lg focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-orange-600 disabled:opacity-50 disabled:cursor-not-allowed shadow-lg shadow-orange-600/30 transition-all"
                    >
                        <GoogleIcon name="lock" class="text-xl" />
                        <span v-if="loading">Cerrando...</span>
                        <span v-else>Cerrar Caja</span>
                    </button>
                </div>
            </form>
        </div>
    </Modal>
</template>
