<script setup>
import { computed } from 'vue';
import Icon from './Icon.vue';

/**
 * Data Table component.
 * 
 * A reusable table component with sorting, custom columns, and empty states.
 * 
 * @example
 * <DataTable
 *   :columns="[
 *     { key: 'name', label: 'Nombre', sortable: true },
 *     { key: 'email', label: 'Email' },
 *     { key: 'status', label: 'Estado' },
 *   ]"
 *   :data="users"
 *   :sort-by="sortField"
 *   :sort-direction="sortDirection"
 *   @sort="handleSort"
 * >
 *   <template #cell-status="{ item }">
 *     <StatusBadge :active="item.is_active" />
 *   </template>
 *   <template #cell-actions="{ item }">
 *     <button @click="edit(item)">Editar</button>
 *   </template>
 * </DataTable>
 */

const props = defineProps({
    columns: {
        type: Array,
        required: true,
        // Each column: { key, label, sortable?, class?, headerClass? }
    },
    data: {
        type: Array,
        required: true,
    },
    sortBy: {
        type: String,
        default: null,
    },
    sortDirection: {
        type: String,
        default: 'asc',
        validator: (value) => ['asc', 'desc'].includes(value),
    },
    loading: {
        type: Boolean,
        default: false,
    },
    emptyMessage: {
        type: String,
        default: 'No hay datos para mostrar',
    },
    striped: {
        type: Boolean,
        default: false,
    },
    hoverable: {
        type: Boolean,
        default: true,
    },
});

const emit = defineEmits(['sort', 'row-click']);

const handleSort = (column) => {
    if (!column.sortable) return;
    
    const newDirection = props.sortBy === column.key && props.sortDirection === 'asc'
        ? 'desc'
        : 'asc';
    
    emit('sort', { key: column.key, direction: newDirection });
};

const getSortIcon = (column) => {
    if (!column.sortable) return null;
    if (props.sortBy !== column.key) return 'chevron-up-down';
    return props.sortDirection === 'asc' ? 'chevron-up' : 'chevron-down';
};

const rowClasses = computed(() => {
    const classes = [];
    if (props.hoverable) classes.push('hover:bg-gray-50');
    return classes.join(' ');
});
</script>

<template>
    <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
                <tr>
                    <th
                        v-for="column in columns"
                        :key="column.key"
                        :class="[
                            'px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider',
                            column.sortable ? 'cursor-pointer select-none hover:bg-gray-100' : '',
                            column.headerClass || ''
                        ]"
                        @click="handleSort(column)"
                    >
                        <div class="flex items-center gap-1">
                            <slot :name="`header-${column.key}`" :column="column">
                                {{ column.label }}
                            </slot>
                            <Icon
                                v-if="column.sortable"
                                :name="getSortIcon(column)"
                                :class="[
                                    'h-4 w-4',
                                    sortBy === column.key ? 'text-gray-700' : 'text-gray-400'
                                ]"
                            />
                        </div>
                    </th>
                </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
                <!-- Loading state -->
                <tr v-if="loading">
                    <td
                        :colspan="columns.length"
                        class="px-6 py-12 text-center"
                    >
                        <div class="flex items-center justify-center gap-2 text-gray-500">
                            <svg class="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
                                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                            </svg>
                            <span>Cargando...</span>
                        </div>
                    </td>
                </tr>

                <!-- Empty state -->
                <tr v-else-if="!data || data.length === 0">
                    <td
                        :colspan="columns.length"
                        class="px-6 py-12 text-center text-gray-500"
                    >
                        <slot name="empty">
                            <div class="flex flex-col items-center gap-2">
                                <Icon name="inbox" class="h-12 w-12 text-gray-300" />
                                <p>{{ emptyMessage }}</p>
                            </div>
                        </slot>
                    </td>
                </tr>

                <!-- Data rows -->
                <tr
                    v-else
                    v-for="(item, index) in data"
                    :key="item.id || index"
                    :class="[
                        rowClasses,
                        striped && index % 2 === 1 ? 'bg-gray-50' : ''
                    ]"
                    @click="$emit('row-click', item)"
                >
                    <td
                        v-for="column in columns"
                        :key="column.key"
                        :class="[
                            'px-6 py-4 whitespace-nowrap text-sm text-gray-900',
                            column.class || ''
                        ]"
                    >
                        <slot
                            :name="`cell-${column.key}`"
                            :item="item"
                            :value="item[column.key]"
                            :index="index"
                        >
                            {{ item[column.key] }}
                        </slot>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</template>
