<script setup>
import { ref, watch } from 'vue';
import { useForm, 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';

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

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

/** Estado */
const categories = ref([]);

/** Formulario */
const form = useForm({
    name: '',
    sku: '',
    barcode: '',
    category_id: '',
    stock: 0,
    cost: 0,
    retail_price: 0,
    tax: 16
});

/** 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 createProduct = () => {
    form.post(apiURL('inventario'), {
        onSuccess: () => {
            Notify.success('Producto creado exitosamente');
            emit('created');
            closeModal();
        },
        onError: () => {
            Notify.error('Error al crear el producto');
        }
    });
};

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

/** Observadores */
watch(() => props.show, (newValue) => {
    if (newValue) {
        loadCategories();
    }
});
</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>

                    <!-- 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="100"
                        />
                        <FormError :message="form.errors?.barcode" />
                    </div>

                    <!-- Categoría -->
                    <div class="col-span-2">
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            CATEGORÍA
                        </label>
                        <select
                            v-model="form.category_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="">Seleccionar categoría</option>
                            <option
                                v-for="category in categories"
                                :key="category.id"
                                :value="category.id"
                            >
                                {{ category.name }}
                            </option>
                        </select>
                        <FormError :message="form.errors?.category_id" />
                    </div>

                    <!-- Stock Inicial -->
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            STOCK INICIAL
                        </label>
                        <FormInput
                            v-model.number="form.stock"
                            type="number"
                            min="0"
                            placeholder="0"
                            required
                        />
                        <FormError :message="form.errors?.stock" />
                    </div>

                    <!-- Costo -->
                    <div>
                        <label class="block text-xs font-semibold text-gray-700 dark:text-gray-300 uppercase mb-1.5">
                            COSTO
                        </label>
                        <FormInput
                            v-model.number="form.cost"
                            type="number"
                            min="0"
                            step="0.01"
                            placeholder="0.00"
                            required
                        />
                        <FormError :message="form.errors?.cost" />
                    </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
                        </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>
</template>
