<script setup>
import AdminLayout from '@/Layouts/AdminLayout.vue';
import { Head, Link, router, useForm } from '@inertiajs/vue3';
import { ref } from 'vue';

const props = defineProps({
    foods: Object,
    categories: Array,
    mealTypes: Object,
    filters: Object,
});

const search = ref(props.filters.search || '');
const category = ref(props.filters.category || '');
const mealType = ref(props.filters.meal_type || '');
const isActive = ref(props.filters.is_active || '');

// Import/Export
const showImportModal = ref(false);
const showExportModal = ref(false);
const importForm = useForm({
    file: null,
});

const applyFilters = () => {
    router.get(route('admin.foods.index'), {
        search: search.value,
        category: category.value,
        meal_type: mealType.value,
        is_active: isActive.value,
    }, { preserveState: true });
};

const clearFilters = () => {
    search.value = '';
    category.value = '';
    mealType.value = '';
    isActive.value = '';
    applyFilters();
};

const deleteFood = (food) => {
    if (confirm(`¿Eliminar "${food.name}"?`)) {
        router.delete(route('admin.foods.destroy', food.id));
    }
};

const getMealTypeLabel = (type) => {
    return props.mealTypes?.[type] || type || '-';
};

// Import functions
const handleFileChange = (e) => {
    importForm.file = e.target.files[0];
};

const submitImport = () => {
    importForm.post(route('admin.foods.import'), {
        preserveScroll: true,
        forceFormData: true,
        onSuccess: () => {
            showImportModal.value = false;
            importForm.reset();
        },
    });
};

// Export functions
const exportFoods = (format) => {
    window.location.href = route('admin.foods.export', { format });
    showExportModal.value = false;
};
</script>

<template>
    <Head title="Gestión de Alimentos" />

    <AdminLayout>
        <template #header>
            <div class="flex justify-between items-center">
                <h2 class="text-xl font-semibold leading-tight text-gray-800 dark:text-gray-200">
                    Gestión de Alimentos
                </h2>
                <div class="flex gap-2">
                    <!-- Export Button -->
                    <button 
                        @click="showExportModal = true"
                        class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 flex items-center gap-2"
                    >
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                        </svg>
                        Exportar
                    </button>
                    <!-- Import Button -->
                    <button 
                        @click="showImportModal = true"
                        class="px-4 py-2 bg-amber-600 text-white rounded-md hover:bg-amber-700 flex items-center gap-2"
                    >
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />
                        </svg>
                        Importar
                    </button>
                    <Link :href="route('admin.foods.create')" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
                        + Nuevo Alimento
                    </Link>
                </div>
            </div>
        </template>

        <div class="py-12">
            <div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
                <!-- Filters -->
                <div class="mb-6 p-4 bg-white dark:bg-gray-800 rounded-lg shadow">
                    <div class="flex flex-wrap gap-4 items-end">
                        <div class="flex-1 min-w-[200px]">
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Buscar</label>
                            <input
                                v-model="search"
                                type="text"
                                placeholder="Buscar alimento..."
                                class="w-full rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                @keyup.enter="applyFilters"
                            />
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Categoría</label>
                            <select
                                v-model="category"
                                class="rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                @change="applyFilters"
                            >
                                <option value="">Todas las categorías</option>
                                <option v-for="cat in categories" :key="cat" :value="cat">{{ cat }}</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Tipo de Comida</label>
                            <select
                                v-model="mealType"
                                class="rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                @change="applyFilters"
                            >
                                <option value="">Todos los tipos</option>
                                <option v-for="(label, key) in mealTypes" :key="key" :value="key">{{ label }}</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Estado</label>
                            <select
                                v-model="isActive"
                                class="rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                @change="applyFilters"
                            >
                                <option value="">Todos</option>
                                <option value="true">Activos</option>
                                <option value="false">Inactivos</option>
                            </select>
                        </div>
                        <div class="flex gap-2">
                            <button
                                @click="applyFilters"
                                class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
                            >
                                Buscar
                            </button>
                            <button
                                @click="clearFilters"
                                class="px-4 py-2 bg-gray-200 dark:bg-gray-600 text-gray-700 dark:text-gray-200 rounded-md hover:bg-gray-300 dark:hover:bg-gray-500"
                            >
                                Limpiar
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Foods Table -->
                <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-sm sm:rounded-lg">
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                            <thead class="bg-gray-50 dark:bg-gray-900">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Alimento</th>
                                    <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Porción</th>
                                    <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Calorías</th>
                                    <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Proteínas</th>
                                    <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Carbos</th>
                                    <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Grasas</th>
                                    <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Fibra</th>
                                    <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Estado</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Acciones</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                                <tr v-for="food in foods.data" :key="food.id" :class="{ 'bg-gray-50 dark:bg-gray-900 opacity-60': !food.is_active }">
                                    <td class="px-6 py-4">
                                        <div>
                                            <div class="text-sm font-medium text-gray-900 dark:text-gray-100">{{ food.name }}</div>
                                            <div class="text-xs text-gray-500 dark:text-gray-400">{{ food.category || 'Sin categoría' }}</div>
                                            <div v-if="food.meal_type" class="text-xs text-blue-600 dark:text-blue-400">{{ getMealTypeLabel(food.meal_type) }}</div>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4 text-center text-sm">
                                        <div v-if="food.serving_size">
                                            <div class="text-gray-900 dark:text-gray-100">{{ food.serving_size }}</div>
                                            <div v-if="food.serving_weight" class="text-xs text-gray-500 dark:text-gray-400">{{ food.serving_weight }}g</div>
                                        </div>
                                        <span v-else class="text-gray-400 dark:text-gray-500">-</span>
                                    </td>
                                    <td class="px-6 py-4 text-center text-sm">
                                        <span class="text-purple-600 dark:text-purple-400 font-medium">{{ food.calories }} kcal</span>
                                    </td>
                                    <td class="px-6 py-4 text-center text-sm">
                                        <span class="text-blue-600 dark:text-blue-400 font-medium">{{ food.proteins }}g</span>
                                    </td>
                                    <td class="px-6 py-4 text-center text-sm">
                                        <span class="text-yellow-600 dark:text-yellow-400 font-medium">{{ food.carbs }}g</span>
                                    </td>
                                    <td class="px-6 py-4 text-center text-sm">
                                        <span class="text-orange-600 dark:text-orange-400 font-medium">{{ food.fats }}g</span>
                                    </td>
                                    <td class="px-6 py-4 text-center text-sm">
                                        <span class="text-green-600 dark:text-green-400">{{ food.fiber || 0 }}g</span>
                                    </td>
                                    <td class="px-6 py-4 text-center">
                                        <span 
                                            :class="[
                                                'inline-flex px-2 py-1 text-xs font-semibold rounded-full',
                                                food.is_active 
                                                    ? 'bg-green-100 dark:bg-green-900/50 text-green-800 dark:text-green-300' 
                                                    : 'bg-red-100 dark:bg-red-900/50 text-red-800 dark:text-red-300'
                                            ]"
                                        >
                                            {{ food.is_active ? 'Activo' : 'Inactivo' }}
                                        </span>
                                    </td>
                                    <td class="px-6 py-4 text-right text-sm font-medium space-x-2">
                                        <Link :href="route('admin.foods.edit', food.id)" class="text-blue-600 dark:text-blue-400 hover:text-blue-900 dark:hover:text-blue-300">
                                            Editar
                                        </Link>
                                        <button @click="deleteFood(food)" class="text-red-600 dark:text-red-400 hover:text-red-900 dark:hover:text-red-300">
                                            Eliminar
                                        </button>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination -->
                    <div v-if="foods.links" class="px-6 py-4 border-t dark:border-gray-700">
                        <div class="flex justify-between items-center">
                            <span class="text-sm text-gray-700 dark:text-gray-300">
                                Mostrando {{ foods.from }} a {{ foods.to }} de {{ foods.total }} alimentos
                            </span>
                            <div class="flex gap-2">
                                <Link
                                    v-for="link in foods.links"
                                    :key="link.label"
                                    :href="link.url"
                                    :class="[
                                        'px-3 py-1 rounded text-sm',
                                        link.active ? 'bg-blue-600 text-white' : 'bg-gray-100 dark:bg-gray-700 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-gray-600',
                                        !link.url && 'opacity-50 cursor-not-allowed'
                                    ]"
                                    v-html="link.label"
                                />
                            </div>
                        </div>
                    </div>

                    <!-- Empty State -->
                    <div v-if="!foods.data?.length" class="p-12 text-center text-gray-500 dark:text-gray-400">
                        <div class="text-6xl mb-4">🍎</div>
                        <p>No hay alimentos registrados.</p>
                        <Link :href="route('admin.foods.create')" class="text-blue-600 dark:text-blue-400 hover:underline mt-2 inline-block">
                            Crear el primer alimento
                        </Link>
                    </div>
                </div>
            </div>
        </div>

        <!-- Import Modal -->
        <Teleport to="body">
            <div v-if="showImportModal" class="fixed inset-0 z-50 overflow-y-auto">
                <div class="flex items-center justify-center min-h-screen px-4">
                    <div class="fixed inset-0 bg-black/50" @click="showImportModal = false"></div>
                    <div class="relative bg-white dark:bg-gray-800 rounded-xl shadow-xl max-w-md w-full p-6">
                        <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                            📥 Importar Alimentos
                        </h3>
                        <p class="text-sm text-gray-500 dark:text-gray-400 mb-4">
                            Sube un archivo CSV, TXT o JSON con los alimentos a importar. Los duplicados serán omitidos automáticamente.
                        </p>
                        
                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                                Archivo
                            </label>
                            <input 
                                type="file" 
                                @change="handleFileChange"
                                accept=".csv,.txt,.json"
                                class="w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100"
                            />
                        </div>

                        <div class="bg-gray-50 dark:bg-gray-700 rounded-lg p-3 mb-4 text-xs text-gray-600 dark:text-gray-300">
                            <p class="font-semibold mb-1">Formatos aceptados:</p>
                            <ul class="list-disc ml-4 space-y-1">
                                <li><strong>CSV:</strong> Nombre, Categoría, Proteínas, Carbos, Grasas, Fibra, Calorías</li>
                                <li><strong>TXT:</strong> Un alimento por línea (solo nombres)</li>
                                <li><strong>JSON:</strong> Array con objetos {name, proteins, carbs, fats...}</li>
                            </ul>
                        </div>

                        <div class="flex justify-end gap-3">
                            <button 
                                @click="showImportModal = false"
                                class="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg"
                            >
                                Cancelar
                            </button>
                            <button 
                                @click="submitImport"
                                :disabled="!importForm.file || importForm.processing"
                                class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
                            >
                                {{ importForm.processing ? 'Importando...' : 'Importar' }}
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </Teleport>

        <!-- Export Modal -->
        <Teleport to="body">
            <div v-if="showExportModal" class="fixed inset-0 z-50 overflow-y-auto">
                <div class="flex items-center justify-center min-h-screen px-4">
                    <div class="fixed inset-0 bg-black/50" @click="showExportModal = false"></div>
                    <div class="relative bg-white dark:bg-gray-800 rounded-xl shadow-xl max-w-md w-full p-6">
                        <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                            📤 Exportar Alimentos
                        </h3>
                        <p class="text-sm text-gray-500 dark:text-gray-400 mb-4">
                            Selecciona el formato en el que deseas exportar la lista de alimentos.
                        </p>
                        
                        <div class="grid grid-cols-2 gap-3 mb-4">
                            <button 
                                @click="exportFoods('csv')"
                                class="flex flex-col items-center p-4 border-2 border-gray-200 dark:border-gray-600 rounded-xl hover:border-blue-500 hover:bg-blue-50 dark:hover:bg-blue-900/20 transition-all"
                            >
                                <span class="text-3xl mb-2">📊</span>
                                <span class="font-medium text-gray-900 dark:text-white">CSV</span>
                                <span class="text-xs text-gray-500">Excel, Google Sheets</span>
                            </button>
                            <button 
                                @click="exportFoods('excel')"
                                class="flex flex-col items-center p-4 border-2 border-gray-200 dark:border-gray-600 rounded-xl hover:border-green-500 hover:bg-green-50 dark:hover:bg-green-900/20 transition-all"
                            >
                                <span class="text-3xl mb-2">📗</span>
                                <span class="font-medium text-gray-900 dark:text-white">Excel</span>
                                <span class="text-xs text-gray-500">Microsoft Excel</span>
                            </button>
                            <button 
                                @click="exportFoods('txt')"
                                class="flex flex-col items-center p-4 border-2 border-gray-200 dark:border-gray-600 rounded-xl hover:border-amber-500 hover:bg-amber-50 dark:hover:bg-amber-900/20 transition-all"
                            >
                                <span class="text-3xl mb-2">📄</span>
                                <span class="font-medium text-gray-900 dark:text-white">TXT</span>
                                <span class="text-xs text-gray-500">Solo nombres</span>
                            </button>
                            <button 
                                @click="exportFoods('json')"
                                class="flex flex-col items-center p-4 border-2 border-gray-200 dark:border-gray-600 rounded-xl hover:border-purple-500 hover:bg-purple-50 dark:hover:bg-purple-900/20 transition-all"
                            >
                                <span class="text-3xl mb-2">🔧</span>
                                <span class="font-medium text-gray-900 dark:text-white">JSON</span>
                                <span class="text-xs text-gray-500">Datos completos</span>
                            </button>
                        </div>

                        <div class="flex justify-end">
                            <button 
                                @click="showExportModal = false"
                                class="px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg"
                            >
                                Cerrar
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </Teleport>
    </AdminLayout>
</template>
