<script setup lang="ts">
import { computed } from 'vue'
import type { QueryResult } from '../../types'
import { useTableSort } from '../../composables/useTableSort'
import { useCSVDownload } from '../../composables/useCSVDownload'

const props = defineProps<{ results: QueryResult; messageId: string }>()

const { sortColumn, sortDirection, toggleSort, sorted } = useTableSort(
  () => props.results.rows
)
const { downloadCSV } = useCSVDownload()

const displayRows = computed(() => sorted.value.slice(0, 100))
</script>

<template>
  <div>
    <!-- Toolbar -->
    <div class="flex items-center justify-between px-3 py-2 bg-dark-900 border-b border-dark-600">
      <span class="text-xs text-dark-500">{{ results.row_count }} rows{{ results.row_count > 100 ? ' (showing first 100)' : '' }}</span>
      <button @click="downloadCSV(messageId)" class="text-xs text-primary-400 hover:text-primary-300">
        Download CSV
      </button>
    </div>

    <!-- Table -->
    <div class="overflow-x-auto">
      <table class="w-full text-xs">
        <thead>
          <tr class="bg-dark-900">
            <th
              v-for="col in results.columns"
              :key="col"
              @click="toggleSort(col)"
              class="px-3 py-2 text-left text-dark-400 font-medium cursor-pointer hover:text-dark-200 whitespace-nowrap"
            >
              {{ col }}
              <span v-if="sortColumn === col" class="ml-1">
                {{ sortDirection === 'asc' ? '\u2191' : '\u2193' }}
              </span>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(row, i) in displayRows" :key="i" class="border-t border-dark-700 hover:bg-dark-800">
            <td v-for="col in results.columns" :key="col" class="px-3 py-1.5 text-dark-300 whitespace-nowrap max-w-xs truncate">
              {{ row[col] ?? '' }}
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>
