<script setup>
import { ref, watch, computed } from 'vue';
import { formatCurrency } from '@/utils/formatters';
import { useForm, useApi, apiURL } from '@Services/Api';

import Modal from '@Holos/Modal.vue';
import FormInput from '@Holos/Form/Input.vue';
import FormError from '@Holos/Form/Elements/Error.vue';
import GoogleIcon from '@Shared/GoogleIcon.vue';

/** Eventos */
const emit = defineEmits(['close', 'updated']);

/** Propiedades */
const props = defineProps({
    show: Boolean,
    movement: Object
});

/** Estado */
const warehouses = ref([]);
const suppliers = ref([]);
const loading = ref(false);
const api = useApi();

/** Formulario */
const form = useForm({
    quantity: 0,
    unit_cost: 0,
    warehouse_id: '',
    supplier_id: null,
    origin_warehouse_id: '',
    destination_warehouse_id: '',
    invoice_reference: '',
    notes: ''
});

/** Computed */
const movementTypeInfo = computed(() => {
    const types = {
        entry: {
            label: 'Entrada',
            icon: 'add_circle',
            color: 'green',
            bgClass: 'bg-green-100 dark:bg-green-900/30',
            textClass: 'text-green-800 dark:text-green-300'
        },
        exit: {
            label: 'Salida',
            icon: 'remove_circle',
            color: 'red',
            bgClass: 'bg-red-100 dark:bg-red-900/30',
            textClass: 'text-red-800 dark:text-red-300'
        },
        transfer: {
            label: 'Traspaso',
            icon: 'swap_horiz',
            color: 'blue',
            bgClass: 'bg-blue-100 dark:bg-blue-900/30',
            textClass: 'text-blue-800 dark:text-blue-300'
        },
    };
    return types[props.movement?.movement_type] || types.entry;
});

const totalCost = computed(() => {
    return form.quantity * form.unit_cost;
});

const allowsDecimals = computed(() => {
    return props.movement?.inventory?.unit_of_measure?.allows_decimals || false;
});

/** Métodos */
const loadWarehouses = () => {
    loading.value = true;
    Promise.all([
        api.get(apiURL('almacenes'), {
            onSuccess: (data) => {
                warehouses.value = data.warehouses?.data || data.data || [];
            }
        }),
        api.get(apiURL('proveedores'), {
            onSuccess: (data) => {
                suppliers.value = data.suppliers?.data || data.suppliers || [];
            }
        })
    ]).finally(() => {
        loading.value = false;
    });
};

const updateMovement = () => {
    // Preparar datos según el tipo de movimiento
    const data = {
        quantity: Number(form.quantity),  // Común para todos los tipos
        notes: form.notes || null
    };

    // Campos específicos por tipo
    if (props.movement.movement_type === 'entry') {
        data.unit_cost = Number(form.unit_cost);
        data.warehouse_to_id = form.destination_warehouse_id;
        data.supplier_id = form.supplier_id || null;
        data.invoice_reference = form.invoice_reference || null;
    } else if (props.movement.movement_type === 'exit') {
        data.warehouse_from_id = form.origin_warehouse_id;
    } else if (props.movement.movement_type === 'transfer') {
        data.warehouse_from_id = form.origin_warehouse_id;
        data.warehouse_to_id = form.destination_warehouse_id;
    }

    api.put(apiURL(`movimientos/${props.movement.id}`), {
        data,
        onSuccess: () => {
            window.Notify.success('Movimiento actualizado correctamente');
            emit('updated');
            closeModal();
        },
        onFail: (response) => {
            window.Notify.error(response.message || 'Error al actualizar el movimiento');
        },
        onError: () => {
            window.Notify.error('Error al actualizar el movimiento');
        }
    });
};

const closeModal = () => {
    form.reset();
    emit('close');
};

/** Observadores */
watch(() => props.show, (isShown) => {
    if (isShown) {
        loadWarehouses();

        if (props.movement) {
            // Cargar datos del movimiento
            form.quantity = props.movement.quantity || 0;
            form.unit_cost = props.movement.unit_cost || 0;
            form.supplier_id = props.movement.supplier_id || null;
            form.invoice_reference = props.movement.invoice_reference || '';
            form.notes = props.movement.notes || '';

            // Almacenes según tipo
            if (props.movement.movement_type === 'entry') {
                form.destination_warehouse_id = props.movement.warehouse_id || '';
            } else if (props.movement.movement_type === 'exit') {
                form.origin_warehouse_id = props.movement.warehouse_id || '';
            } else if (props.movement.movement_type === 'transfer') {
                form.origin_warehouse_id = props.movement.origin_warehouse_id || '';
                form.destination_warehouse_id = props.movement.destination_warehouse_id || '';
            }
        }
    }
}, { immediate: true });
</script>

<template>
    <Modal :show="show" max-width="lg" @close="closeModal">
        <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-10 h-10 rounded-full',
                            movementTypeInfo.bgClass
                        ]"
                    >
                        <GoogleIcon :name="movementTypeInfo.icon" :class="['text-xl', movementTypeInfo.textClass]" />
                    </div>
                    <div>
                        <h3 class="text-lg font-bold text-gray-900 dark:text-gray-100">
                            Editar {{ movementTypeInfo.label }}
                        </h3>
                        <p class="text-xs text-gray-500 dark:text-gray-400">
                            Movimiento #{{ movement?.id }}
                        </p>
                    </div>
                </div>
                <button
                    @click="closeModal"
                    class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                >
                    <GoogleIcon name="close" class="text-xl" />
                </button>
            </div>

            <!-- Información del producto -->
            <div class="mb-4 p-3 bg-gray-50 dark:bg-gray-800/50 border border-gray-200 dark:border-gray-700 rounded-lg">
                <div class="flex items-center gap-2 mb-1">
                    <GoogleIcon name="inventory_2" class="text-gray-500 dark:text-gray-400 text-sm" />
                    <p class="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase">Producto</p>
                </div>
                <p class="text-sm font-semibold text-gray-900 dark:text-gray-100">
                    {{ movement?.inventory?.name || 'N/A' }}
                </p>
                <p class="text-xs text-gray-500 dark:text-gray-400">
                    SKU: {{ movement?.inventory?.sku || 'N/A' }}
                </p>
            </div>

            <!-- Formulario -->
            <form @submit.prevent="updateMovement" class="space-y-4">
                <div class="space-y-4">
                    <!-- Cantidad -->
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            CANTIDAD
                        </label>
                        <FormInput
                            v-model="form.quantity"
                            type="number"
                            :min="allowsDecimals ? '0.001' : '1'"
                            :step="allowsDecimals ? '0.001' : '1'"
                            :placeholder="allowsDecimals ? '0.000' : '0'"
                            required
                        />
                        <FormError :message="form.errors?.quantity" />
                    </div>

                    <!-- Costo unitario (solo para entradas) -->
                    <div v-if="movement?.movement_type === 'entry'">
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            COSTO UNITARIO
                        </label>
                        <FormInput
                            v-model="form.unit_cost"
                            type="number"
                            min="0"
                            step="0.01"
                            placeholder="0.00"
                                                        required
                        />
                        <FormError :message="form.errors?.unit_cost" />

                        <!-- Mostrar costo total -->
                        <p v-if="form.quantity && form.unit_cost" class="mt-1.5 text-xs text-gray-600 dark:text-gray-400">
                            Costo total:
                            <span class="font-semibold text-gray-900 dark:text-gray-100">
                                {{ formatCurrency(totalCost) }}
                            </span>
                        </p>
                    </div>

                    <!-- Almacén destino (para entradas) -->
                    <div v-if="movement?.movement_type === 'entry'">
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            ALMACÉN DESTINO
                        </label>
                        <select
                            v-model="form.destination_warehouse_id"
                                                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 text-sm focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed"
                            required
                        >
                            <option value="">Seleccionar almacén...</option>
                            <option v-for="wh in warehouses" :key="wh.id" :value="wh.id">
                                {{ wh.name }} ({{ wh.code }})
                            </option>
                        </select>
                        <FormError :message="form.errors?.warehouse_id" />
                    </div>

                    <!-- Almacén origen (para salidas) -->
                    <div v-if="movement?.movement_type === 'exit'">
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            ALMACÉN ORIGEN
                        </label>
                        <select
                            v-model="form.origin_warehouse_id"
                                                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 text-sm focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed"
                            required
                        >
                            <option value="">Seleccionar almacén...</option>
                            <option v-for="wh in warehouses" :key="wh.id" :value="wh.id">
                                {{ wh.name }} ({{ wh.code }})
                            </option>
                        </select>
                        <FormError :message="form.errors?.warehouse_id" />
                    </div>

                    <!-- Almacenes origen y destino (para traspasos) -->
                    <div v-if="movement?.movement_type === 'transfer'" class="grid grid-cols-2 gap-3">
                        <div>
                            <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                                ALMACÉN ORIGEN
                            </label>
                            <select
                                v-model="form.origin_warehouse_id"
                                                                class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 text-sm focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed"
                                required
                            >
                                <option value="">Seleccionar...</option>
                                <option
                                    v-for="wh in warehouses"
                                    :key="wh.id"
                                    :value="wh.id"
                                    :disabled="wh.id === form.destination_warehouse_id"
                                >
                                    {{ wh.name }} ({{ wh.code }})
                                </option>
                            </select>
                            <FormError :message="form.errors?.origin_warehouse_id" />
                        </div>
                        <div>
                            <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                                ALMACÉN DESTINO
                            </label>
                            <select
                                v-model="form.destination_warehouse_id"
                                                                class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 text-sm focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed"
                                required
                            >
                                <option value="">Seleccionar...</option>
                                <option
                                    v-for="wh in warehouses"
                                    :key="wh.id"
                                    :value="wh.id"
                                    :disabled="wh.id === form.origin_warehouse_id"
                                >
                                    {{ wh.name }} ({{ wh.code }})
                                </option>
                            </select>
                            <FormError :message="form.errors?.destination_warehouse_id" />
                        </div>
                    </div>

                    <!-- Proveedor y Referencia (solo para entradas) -->
                    <div v-if="movement?.movement_type === 'entry'" class="space-y-4">
                        <!-- Proveedor -->
                        <div>
                            <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                                PROVEEDOR <span class="text-gray-400 text-xs normal-case">(opcional)</span>
                            </label>
                            <select
                                v-model="form.supplier_id"
                                class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 text-sm focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                            >
                                <option :value="null">Seleccionar proveedor...</option>
                                <option v-for="supplier in suppliers" :key="supplier.id" :value="supplier.id">
                                    {{ supplier.business_name }}
                                </option>
                            </select>
                            <FormError :message="form.errors?.supplier_id" />
                        </div>

                        <!-- Referencia de factura -->
                        <div>
                            <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                                REFERENCIA DE FACTURA
                            </label>
                            <FormInput
                                v-model="form.invoice_reference"
                                type="text"
                                placeholder="Ej: FAC-2026-001"
                            />
                            <FormError :message="form.errors?.invoice_reference" />
                        </div>
                    </div>

                    <!-- Notas -->
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            NOTAS <span class="text-gray-400 text-xs normal-case">(opcional)</span>
                        </label>
                        <textarea
                            v-model="form.notes"
                            rows="2"
                            placeholder="Notas adicionales..."
                                                        class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 text-sm focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 resize-none disabled:opacity-50 disabled:cursor-not-allowed"
                        ></textarea>
                        <FormError :message="form.errors?.notes" />
                    </div>
                </div>

                <!-- Botones -->
                <div class="flex items-center justify-end gap-3 mt-6 pt-4 border-t border-gray-200 dark:border-gray-700">
                    <button
                        type="button"
                        @click="closeModal"
                        class="px-4 py-2 text-sm font-medium 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-indigo-500 transition-colors"
                    >
                        Cancelar
                    </button>
                    <button
                        type="submit"
                        :disabled="form.processing"
                        class="flex items-center gap-2 px-4 py-2 text-sm font-semibold text-white rounded-lg focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                        :class="{
                            'bg-green-600 hover:bg-green-700 focus:ring-green-600': movement?.movement_type === 'entry',
                            'bg-red-600 hover:bg-red-700 focus:ring-red-600': movement?.movement_type === 'exit',
                            'bg-blue-600 hover:bg-blue-700 focus:ring-blue-600': movement?.movement_type === 'transfer'
                        }"
                    >
                        <GoogleIcon name="check_circle" class="text-lg" />
                        <span v-if="form.processing">Actualizando...</span>
                        <span v-else>Actualizar Movimiento</span>
                    </button>
                </div>
            </form>
        </div>
    </Modal>
</template>
