<template>
  <div class="space-y-4">
    <!-- Filters and Search -->
    <div class="flex flex-col sm:flex-row gap-3">
      <UInput
        v-model="search"
        placeholder="Buscar por nombre o ID..."
        icon="i-heroicons-magnifying-glass"
        class="flex-1"
        :ui="{
          base: 'bg-[var(--brand-bg)] text-[var(--brand-text)] border border-[var(--brand-border)] focus:ring-2 focus:ring-[var(--brand-primary-strong)] focus:border-[var(--brand-primary-strong)]',
          placeholder: 'placeholder-[var(--brand-text-muted)]',
          icon: {
            base: 'text-[var(--brand-text-muted)]'
          }
        }"
      />
      <USelectMenu
        v-model="selectedFilter"
        :options="filterOptions"
        placeholder="Filtrar..."
        class="w-full sm:w-auto"
      />
    </div>

    <!-- Table -->
    <UTable
      :data="filteredCards"
      :columns="columns"
      :loading="loading"
      @select="(row, event) => selectCard(row.original)"
    />

    <!-- Results Modal -->
    <UModal v-model:open="showResults">
      <template #header>
        <div class="flex justify-between items-center">
          <h3 class="text-lg font-semibold">Resultados: {{ selectedCardForResults?.name }}</h3>
          <UButton
            color="gray"
            variant="ghost"
            icon="i-heroicons-x-mark"
            @click="showResults = false"
          />
        </div>
      </template>

      <div v-if="currentResult" class="space-y-3 p-4">
        <div class="flex flex-wrap gap-4 text-sm">
          <div>
            <span class="font-medium text-gray-500 dark:text-gray-400">Filas:</span>
            <span class="ml-2">{{ currentResult.data?.rows?.length || 0 }}</span>
          </div>
          <div>
            <span class="font-medium text-gray-500 dark:text-gray-400">Tiempo:</span>
            <span class="ml-2">{{ currentResult.running_time || 0 }}ms</span>
          </div>
          <div>
            <span class="font-medium text-gray-500 dark:text-gray-400">Estado:</span>
            <UBadge :color="currentResult.status === 'completed' ? 'green' : 'yellow'">
              {{ currentResult.status }}
            </UBadge>
          </div>
        </div>

        <!-- Empty State -->
        <div v-if="!currentResult.data?.rows || currentResult.data.rows.length === 0" class="p-8 text-center rounded-lg border dark:border-gray-700 bg-gray-50 dark:bg-gray-800">
          <div class="mx-auto w-16 h-16 mb-4 flex items-center justify-center bg-gray-200 dark:bg-gray-700 rounded-full">
            <svg class="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4"></path>
            </svg>
          </div>
          <h3 class="text-sm font-medium mb-1">No hay datos</h3>
          <p class="text-xs text-gray-500 dark:text-gray-400">La consulta se ejecutó correctamente pero no devolvió resultados.</p>
        </div>

        <!-- Data Display -->
        <div v-else class="overflow-x-auto max-h-96">
          <pre class="p-3 rounded-lg border dark:border-gray-700 bg-gray-50 dark:bg-gray-800 text-xs whitespace-pre-wrap break-words">{{ JSON.stringify(currentResult.data, null, 2) }}</pre>
        </div>
      </div>

      <UAlert
        v-if="currentError"
        color="red"
        variant="soft"
        :title="currentError"
        class="m-4"
      />
    </UModal>
  </div>
</template>

<script setup lang="ts">
import { h, resolveComponent } from 'vue'
import type { TableColumn } from '@nuxt/ui'

const props = defineProps<{
  cards: any[]
  loading?: boolean
}>()

const emit = defineEmits<{
  select: [card: any]
}>()

const UButton = resolveComponent('UButton')
const UBadge = resolveComponent('UBadge')
const UDropdownMenu = resolveComponent('UDropdownMenu')

const search = ref('')
const selectedFilter = ref('all')
const executingCards = ref(new Set<number>())
const executingCachedCards = ref(new Set<number>())
const showResults = ref(false)
const currentResult = ref<any>(null)
const currentError = ref<string | null>(null)
const selectedCardForResults = ref<any>(null)

const filterOptions = [
  { value: 'all', label: 'Todas' },
  { value: 'native', label: 'SQL Nativo' },
  { value: 'query', label: 'Query Builder' }
]

const columns = computed((): TableColumn<Record<string, any>>[] => [
  {
    accessorKey: 'id',
    header: 'ID',
    cell: ({ row }) => {
      return h(UBadge, {
        color: 'gray',
        variant: 'subtle',
        label: row.original.id.toString()
      })
    }
  },
  {
    accessorKey: 'name',
    header: 'Nombre',
    cell: ({ row }) => {
      return h('div', {}, [
        h('div', {
          class: 'font-medium text-[var(--brand-text)]'
        }, row.original.name),
        row.original.description && h('div', {
          class: 'text-xs text-[var(--brand-text-muted)] truncate max-w-md'
        }, row.original.description)
      ])
    }
  },
  {
    accessorKey: 'query_type',
    header: 'Tipo',
    cell: ({ row }) => {
      const type = row.original.query_type || row.original.dataset_query?.type || 'N/A'
      return h(UBadge, {
        color: getQueryTypeColor(type),
        label: type
      })
    }
  },
  {
    accessorKey: 'database_id',
    header: 'DB',
    cell: ({ row }) => {
      return h('span', {
        class: 'text-sm text-[var(--brand-text)]'
      }, row.original.database_id?.toString() || 'N/A')
    }
  },
  {
    accessorKey: 'actions',
    header: 'Acciones',
    cell: ({ row }) => {
      return h('div', {
        class: 'flex flex-wrap gap-1'
      }, [
        h(UButton, {
          onClick: (e: Event) => {
            e.stopPropagation()
            executeCard(row.original)
          },
          loading: executingCards.value.has(row.original.id),
          ui: { base: 'bg-[var(--brand-primary-strong)] text-[var(--brand-bg)] border border-[var(--brand-primary)] hover:bg-[var(--brand-primary)] hover:border-[var(--brand-accent)] disabled:opacity-50 disabled:cursor-not-allowed' },
          size: 'xs',
          label: 'Ejecutar'
        }),
        h(UButton, {
          onClick: (e: Event) => {
            e.stopPropagation()
            executeCachedCard(row.original)
          },
          loading: executingCachedCards.value.has(row.original.id),
          color: 'gray',
          variant: 'ghost',
          size: 'xs',
          label: 'Caché'
        }),
        h(UDropdownMenu, {
          items: getExportItems(row.original)
        }, {
          default: () => h(UButton, {
            color: 'gray',
            variant: 'ghost',
            size: 'xs',
            icon: 'i-heroicons-arrow-down-tray',
            onClick: (e: Event) => e.stopPropagation()
          })
        })
      ])
    }
  }
])

const filteredCards = computed(() => {
  let result = props.cards

  // Filter by search
  if (search.value) {
    const searchLower = search.value.toLowerCase()
    result = result.filter(card =>
      card.name?.toLowerCase().includes(searchLower) ||
      card.id?.toString().includes(searchLower) ||
      card.description?.toLowerCase().includes(searchLower)
    )
  }

  // Filter by type
  if (selectedFilter.value !== 'all') {
    result = result.filter(card => {
      const type = card.query_type || card.dataset_query?.type
      return type === selectedFilter.value
    })
  }

  return result
})

function getQueryTypeColor(type: string) {
  switch (type) {
    case 'native':
      return 'blue'
    case 'query':
      return 'green'
    default:
      return 'gray'
  }
}

function selectCard(card: any) {
  emit('select', card)
}

async function executeCard(card: any) {
  executingCards.value.add(card.id)
  currentError.value = null
  currentResult.value = null
  selectedCardForResults.value = card

  try {
    const result = await $fetch(`/api/metabase/cards/${card.id}/query`, {
      method: 'POST',
      body: {
        parameters: [
          { type: 'category', target: ['variable', ['template-tag', 'incluir_anulados']], value: [false] },
          { type: 'date/single', target: ['variable', ['template-tag', 'fecha_desde']], value: null },
          { type: 'date/single', target: ['variable', ['template-tag', 'fecha_hasta']], value: null }
        ]
      }
    })
    currentResult.value = result
    showResults.value = true
  } catch (e: any) {
    currentError.value = e.message || 'Error al ejecutar la query'
    showResults.value = true
  } finally {
    executingCards.value.delete(card.id)
  }
}

async function executeCachedCard(card: any) {
  executingCachedCards.value.add(card.id)
  currentError.value = null
  currentResult.value = null
  selectedCardForResults.value = card

  try {
    const result = await $fetch(`/api/metabase/cards/${card.id}/query`)
    currentResult.value = result
    showResults.value = true
  } catch (e: any) {
    currentError.value = e.message || 'Error al ejecutar la query con caché'
    showResults.value = true
  } finally {
    executingCachedCards.value.delete(card.id)
  }
}

function getExportItems(card: any) {
  return [[
    {
      label: 'CSV',
      icon: 'i-heroicons-document-text',
      click: () => downloadExport(card, 'csv')
    },
    {
      label: 'JSON',
      icon: 'i-heroicons-code-bracket',
      click: () => downloadExport(card, 'json')
    },
    {
      label: 'XLSX',
      icon: 'i-heroicons-table-cells',
      click: () => downloadExport(card, 'xlsx')
    }
  ]]
}

function downloadExport(card: any, format: 'csv' | 'json' | 'xlsx') {
  const url = `${window.location.origin}/api/metabase/cards/${card.id}/query/${format}`
  window.open(url, '_blank')
}
</script>
