<script setup>
import { ref, watch, computed } from 'vue';
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';
import CategoryCreateModal from '@Pages/POS/Category/CreateModal.vue';
import SubcategoryCreateModal from '@Pages/POS/Category/Subcategories/CreateModal.vue';

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

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

/** Estado */
const categories = ref([]);
const subcategories = ref([]);
const units = ref([]);
const showCategoryCreate = ref(false);
const showSubcategoryCreate = ref(false);

const api = useApi();

/** Formulario */
const form = useForm({
    name: '',
    key_sat: '',
    sku: '',
    barcode: '',
    category_id: '',
    subcategory_id: '',
    unit_of_measure_id: null,
    retail_price: 0,
    tax: 16,
    track_serials: false
});

/** Computed */
const selectedUnit = computed(() => {
    if (!form.unit_of_measure_id) return null;
    return units.value.find(u => u.id === form.unit_of_measure_id);
});

const canUseSerials = computed(() => {
    if (!selectedUnit.value) return true;
    return !selectedUnit.value.allows_decimals;
});

/** Métodos */
const loadCategories = async () => {
    try {
        const response = await fetch(apiURL('categorias'), {
            headers: {
                'Authorization': `Bearer ${sessionStorage.token}`,
                'Accept': 'application/json'
            }
        });
        const result = await response.json();
        if (result.data && result.data.categories && result.data.categories.data) {
            categories.value = result.data.categories.data;
        }
    } catch (error) {
        console.error('Error loading categories:', error);
    }
};

const onCategoryChange = () => {
    form.subcategory_id = '';
    subcategories.value = [];
    if (!form.category_id) return;
    api.get(apiURL(`categorias/${form.category_id}/subcategorias`), {
        onSuccess: (data) => {
            subcategories.value = data.subcategories?.data || data.subcategories || [];
        }
    });
};

const loadUnits = async () => {
    try {
        const response = await fetch(apiURL('unidades-medida/active'), {
            headers: {
                'Authorization': `Bearer ${sessionStorage.token}`,
                'Accept': 'application/json'
            }
        });
        const result = await response.json();
        if (result.data && result.data.units) {
            units.value = result.data.units;

            // Pre-seleccionar "Pieza" si existe
            const defaultUnit = units.value.find(u => u.abbreviation === 'u');
            if (defaultUnit && !form.unit_of_measure_id) {
                form.unit_of_measure_id = defaultUnit.id;
            }
        }
    } catch (error) {
        console.error('Error loading units:', error);
    }
};

const validateSerialsAndUnit = () => {
    if (!selectedUnit.value) return;

    if (selectedUnit.value.allows_decimals) {
        if (form.track_serials) {
            Notify.warning('No se pueden usar números de serie con esta unidad de medida.');
        }
        form.track_serials = false;
        return;
    }

    const unitName = (selectedUnit.value.name || '').toLowerCase();
    const unitAbbr = (selectedUnit.value.abbreviation || '').toLowerCase();
    if (unitName.includes('serial') || unitAbbr.includes('serial')) {
        form.track_serials = true;
    }
};

const createProduct = () => {
    form.transform((data) => ({
        ...data,
        track_serials: selectedUnit.value ? !selectedUnit.value.allows_decimals && !!data.track_serials : false,
        category_id: data.category_id || null,
        subcategory_id: data.category_id ? (data.subcategory_id || null) : null,
    })).post(apiURL('inventario'), {
        onSuccess: () => {
            Notify.success('Producto creado exitosamente');
            emit('created');
            closeModal();
        },
        onError: () => {
            Notify.error('Error al crear el producto');
        }
    });
};

const onCategoryCreated = async (newCategory) => {
    if (newCategory) {
        form.category_id = newCategory.id;
    }
    await loadCategories();
};

const onSubcategoryCreated = (newSubcategory) => {
    if (newSubcategory) {
        subcategories.value.push(newSubcategory);
        form.subcategory_id = newSubcategory.id;
    }
};

const closeModal = () => {
    form.reset();
    subcategories.value = [];
    emit('close');
};

/** Observadores */
watch(() => props.show, (newValue) => {
    if (newValue) {
        loadCategories();
        loadUnits();
    }
});

watch(() => form.unit_of_measure_id, () => {
    validateSerialsAndUnit();
});

watch(() => form.track_serials, () => {
    validateSerialsAndUnit();
});
</script>

<template>
    <Modal :show="show" max-width="md" @close="closeModal">
        <div class="p-6">
            <!-- Header -->
            <div class="flex items-center justify-between mb-6">
                <h3 class="text-lg font-bold text-gray-900 dark:text-gray-100">
                    Crear Producto
                </h3>
                <button
                    @click="closeModal"
                    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>

            <!-- Formulario -->
            <form @submit.prevent="createProduct" class="space-y-4">
                <div class="grid grid-cols-2 gap-4">
                    <!-- Nombre -->
                    <div class="col-span-2">
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            NOMBRE
                        </label>
                        <FormInput
                            v-model="form.name"
                            type="text"
                            placeholder="Nombre del producto"
                            required
                        />
                        <FormError :message="form.errors?.name" />
                    </div>

                    <!-- Clave SAT -->
                    <div class="col-span-2">
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            CLAVE SAT
                        </label>
                        <FormInput
                            v-model="form.key_sat"
                            type="string"
                            placeholder="Clave SAT del producto"
                            maxlength="8"
                        />
                        <FormError :message="form.errors?.key_sat" />
                    </div>

                    <!-- SKU -->
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            SKU
                        </label>
                        <FormInput
                            v-model="form.sku"
                            type="text"
                            placeholder="SKU"
                            required
                        />
                        <FormError :message="form.errors?.sku" />
                    </div>

                    <!-- Código de Barras -->
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            CÓDIGO DE BARRAS
                        </label>
                        <FormInput
                            v-model="form.barcode"
                            type="text"
                            placeholder="1234567890123"
                            maxlength="14"
                        />
                        <FormError :message="form.errors?.barcode" />
                    </div>

                    <!-- Clasificación -->
                    <div class="col-span-2">
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            CLASIFICACIÓN
                        </label>
                        <div class="flex gap-2">
                            <select
                                v-model="form.category_id"
                                class="flex-1 px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-100"
                                @change="onCategoryChange"
                            >
                                <option value="">Seleccionar clasificación</option>
                                <option
                                    v-for="category in categories"
                                    :key="category.id"
                                    :value="category.id"
                                >
                                    {{ category.name }}
                                </option>
                            </select>
                            <button
                                type="button"
                                @click="showCategoryCreate = true"
                                class="flex items-center justify-center w-9 h-9 rounded-lg bg-indigo-50 hover:bg-indigo-100 text-indigo-600 border border-indigo-200 dark:bg-indigo-900/20 dark:hover:bg-indigo-900/40 dark:text-indigo-400 dark:border-indigo-800 transition-colors shrink-0"
                                title="Crear nueva clasificación"
                            >
                                <GoogleIcon name="add" class="text-xl" />
                            </button>
                        </div>
                        <FormError :message="form.errors?.category_id" />
                    </div>

                    <!-- Subclasificación -->
                    <div class="col-span-2">
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            SUBCLASIFICACIÓN
                        </label>
                        <div class="flex gap-2">
                            <select
                                v-model="form.subcategory_id"
                                class="flex-1 px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"
                                :disabled="!form.category_id || !subcategories.length"
                                :required="!!form.category_id"
                            >
                                <option value="">
                                    {{ !form.category_id ? 'Selecciona una clasificación primero' : subcategories.length ? 'Seleccionar subclasificación...' : 'Sin subclasificaciones disponibles' }}
                                </option>
                                <option
                                    v-for="subcategory in subcategories"
                                    :key="subcategory.id"
                                    :value="subcategory.id"
                                >
                                    {{ subcategory.name }}
                                </option>
                            </select>
                            <button
                                type="button"
                                @click="showSubcategoryCreate = true"
                                :disabled="!form.category_id"
                                class="flex items-center justify-center w-9 h-9 rounded-lg bg-indigo-50 hover:bg-indigo-100 text-indigo-600 border border-indigo-200 dark:bg-indigo-900/20 dark:hover:bg-indigo-900/40 dark:text-indigo-400 dark:border-indigo-800 transition-colors shrink-0 disabled:opacity-40 disabled:cursor-not-allowed"
                                title="Crear nueva subclasificación"
                            >
                                <GoogleIcon name="add" class="text-xl" />
                            </button>
                        </div>
                        <FormError :message="form.errors?.subcategory_id" />
                    </div>

                    <!-- Unidad de Medida -->
                    <div class="col-span-2">
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            UNIDAD DE MEDIDA *
                        </label>
                        <select
                            v-model="form.unit_of_measure_id"
                            class="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-100"
                            required
                        >
                            <option :value="null">Seleccionar unidad</option>
                            <option
                                v-for="unit in units"
                                :key="unit.id"
                                :value="unit.id"
                            >
                                {{ unit.name }} ({{ unit.abbreviation }})
                            </option>
                        </select>
                        <FormError :message="form.errors?.unit_of_measure_id" />
                        <p v-if="selectedUnit" class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                            <span v-if="selectedUnit.allows_decimals">Esta unidad permite cantidades decimales (ej: 25.750)</span>
                            <span v-else>Esta unidad solo permite cantidades enteras</span>
                        </p>
                    </div>

                    <!-- Precio de Venta -->
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            PRECIO VENTA <span class="text-gray-500 dark:text-gray-400">(Subtotal)</span>
                        </label>
                        <FormInput
                            v-model.number="form.retail_price"
                            type="number"
                            min="0"
                            step="0.01"
                            placeholder="0.00"
                            required
                        />
                        <FormError :message="form.errors?.retail_price" />
                    </div>

                    <!-- Impuesto/Tax -->
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            IMPUESTO (%)
                        </label>
                        <FormInput
                            v-model.number="form.tax"
                            type="number"
                            min="0"
                            max="100"
                            step="0.01"
                            placeholder="16.00"
                            required
                        />
                        <FormError :message="form.errors?.tax" />
                    </div>
                </div>

                <!-- Botones -->
                <div class="flex items-center justify-end gap-3 mt-6">
                    <button
                        type="button"
                        @click="closeModal"
                        class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 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="px-4 py-2 text-sm font-semibold text-white bg-gray-900 rounded-lg hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                    >
                        <span v-if="form.processing">Guardando...</span>
                        <span v-else>Guardar</span>
                    </button>
                </div>
            </form>
        </div>
    </Modal>

    <CategoryCreateModal
        :show="showCategoryCreate"
        @close="showCategoryCreate = false"
        @created="onCategoryCreated"
    />

    <SubcategoryCreateModal
        :show="showSubcategoryCreate"
        :category-id="form.category_id"
        @close="showSubcategoryCreate = false"
        @created="onSubcategoryCreated"
    />
</template>
