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

/** Propiedades */
const props = defineProps({
    show: Boolean,
    product: Object,
    equivalences: {
        type: Array,
        default: () => []
    },
    baseUnit: Object
});

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

/** Estado */
const selectedOption = ref(null);

/** Todas las opciones: unidad base + equivalencias activas */
const options = computed(() => {
    const basePrice = parseFloat(props.product?.price?.retail_price || 0);
    const baseName = props.baseUnit?.name || props.product?.unit_of_measure?.name || 'Unidad base';
    const baseAbbr = props.baseUnit?.abbreviation || props.product?.unit_of_measure?.abbreviation || '';

    const base = {
        unit_of_measure_id: null,
        unit_name: baseName,
        unit_abbreviation: baseAbbr,
        unit_price: basePrice,
        conversion_factor: 1,
        label: `${baseName}${baseAbbr ? ` (${baseAbbr})` : ''}`,
        priceLabel: `$${basePrice.toFixed(2)}`
    };

    const equivalenceOptions = props.equivalences.map(eq => ({
        unit_of_measure_id: eq.unit_of_measure_id,
        unit_name: eq.unit_name,
        unit_abbreviation: eq.unit_abbreviation,
        unit_price: parseFloat(eq.retail_price),
        conversion_factor: parseFloat(eq.conversion_factor),
        label: `${eq.unit_name}${eq.unit_abbreviation ? ` (${eq.unit_abbreviation})` : ''}`,
        priceLabel: `$${parseFloat(eq.retail_price).toFixed(2)}`
    }));

    return [base, ...equivalenceOptions];
});

/** Métodos */
const selectOption = (option) => {
    selectedOption.value = option;
};

const confirmSelection = () => {
    if (!selectedOption.value) return;
    emit('confirm', {
        unit_of_measure_id: selectedOption.value.unit_of_measure_id,
        unit_price: selectedOption.value.unit_price,
        unit_name: selectedOption.value.unit_of_measure_id ? selectedOption.value.unit_name : null,
        conversion_factor: selectedOption.value.conversion_factor
    });
    selectedOption.value = null;
};

const handleClose = () => {
    selectedOption.value = null;
    emit('close');
};
</script>

<template>
    <Modal :show="show" max-width="sm" @close="handleClose">
        <div class="p-6">
            <!-- Header -->
            <div class="flex items-center justify-between mb-5">
                <div>
                    <h3 class="text-base font-bold text-gray-900 dark:text-gray-100">
                        Seleccionar unidad
                    </h3>
                    <p class="text-sm text-gray-500 dark:text-gray-400 mt-0.5 truncate max-w-xs">
                        {{ product?.name }}
                    </p>
                </div>
                <button
                    @click="handleClose"
                    class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                >
                    <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>

            <!-- Opciones de unidad -->
            <div class="space-y-2 mb-5">
                <button
                    v-for="option in options"
                    :key="option.unit_of_measure_id ?? 'base'"
                    type="button"
                    @click="selectOption(option)"
                    :class="[
                        'w-full flex items-center justify-between p-3 rounded-lg border-2 text-left transition-all',
                        selectedOption?.unit_of_measure_id === option.unit_of_measure_id
                            ? 'border-indigo-500 bg-indigo-50 dark:bg-indigo-950 dark:border-indigo-400'
                            : 'border-gray-200 hover:border-gray-300 dark:border-gray-700 dark:hover:border-gray-500'
                    ]"
                >
                    <div class="flex items-center gap-3">
                        <!-- Check indicator -->
                        <div
                            :class="[
                                'w-4 h-4 rounded-full border-2 flex items-center justify-center flex-shrink-0',
                                selectedOption?.unit_of_measure_id === option.unit_of_measure_id
                                    ? 'border-indigo-500 bg-indigo-500'
                                    : 'border-gray-300 dark:border-gray-600'
                            ]"
                        >
                            <div
                                v-if="selectedOption?.unit_of_measure_id === option.unit_of_measure_id"
                                class="w-1.5 h-1.5 rounded-full bg-white"
                            ></div>
                        </div>

                        <!-- Info -->
                        <div>
                            <p class="text-sm font-semibold text-gray-900 dark:text-gray-100">
                                {{ option.label }}
                            </p>
                            <p
                                v-if="option.unit_of_measure_id !== null"
                                class="text-xs text-gray-500 dark:text-gray-400 mt-0.5"
                            >
                                1 {{ option.unit_name }} = {{ option.conversion_factor }} {{ baseUnit?.abbreviation || '' }}
                            </p>
                        </div>
                    </div>

                    <!-- Precio -->
                    <span class="text-sm font-bold text-gray-900 dark:text-gray-100 ml-2">
                        {{ option.priceLabel }}
                    </span>
                </button>
            </div>

            <!-- Botones -->
            <div class="flex items-center justify-end gap-3">
                <button
                    type="button"
                    @click="handleClose"
                    class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors dark:bg-gray-800 dark:text-gray-300 dark:border-gray-600 dark:hover:bg-gray-700"
                >
                    Cancelar
                </button>
                <button
                    type="button"
                    @click="confirmSelection"
                    :disabled="!selectedOption"
                    class="px-4 py-2 text-sm font-semibold text-white bg-indigo-600 rounded-lg hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                >
                    Agregar al carrito
                </button>
            </div>
        </div>
    </Modal>
</template>
