<script setup lang="ts">
import { ref, onMounted } from 'vue'
import type { Message, QueryResult, ChartConfig } from '../../types'
import { chatApi } from '../../services/chatApi'
import DataTable from './DataTable.vue'
import SQLViewer from './SQLViewer.vue'
import ChartView from './ChartView.vue'

const props = defineProps<{ message: Message }>()

const activeTab = ref<'data' | 'sql' | 'chart'>('data')
const results = ref<QueryResult | null>(null)
const loading = ref(false)

onMounted(async () => {
  if (props.message.has_results) {
    loading.value = true
    try {
      const { data } = await chatApi.getResults(props.message.id)
      results.value = data
    } catch { /* results may not be available yet */ }
    finally { loading.value = false }
  }
})
</script>

<template>
  <div class="border border-dark-600 rounded-lg overflow-hidden">
    <!-- Tabs -->
    <div class="flex border-b border-dark-600 bg-dark-900">
      <button
        @click="activeTab = 'data'"
        :class="['px-4 py-2 text-xs font-medium', activeTab === 'data' ? 'text-primary-400 border-b-2 border-primary-400' : 'text-dark-400 hover:text-dark-200']"
      >DATA <span v-if="message.row_count" class="ml-1 text-dark-500">({{ message.row_count }})</span></button>
      <button
        v-if="message.sql_query"
        @click="activeTab = 'sql'"
        :class="['px-4 py-2 text-xs font-medium', activeTab === 'sql' ? 'text-primary-400 border-b-2 border-primary-400' : 'text-dark-400 hover:text-dark-200']"
      >SQL</button>
      <button
        v-if="message.chart_config"
        @click="activeTab = 'chart'"
        :class="['px-4 py-2 text-xs font-medium', activeTab === 'chart' ? 'text-primary-400 border-b-2 border-primary-400' : 'text-dark-400 hover:text-dark-200']"
      >CHART</button>
    </div>

    <!-- Content -->
    <div class="max-h-96 overflow-auto">
      <div v-if="loading" class="p-8 text-center text-dark-500">Loading results...</div>

      <template v-else>
        <DataTable v-if="activeTab === 'data' && results" :results="results" :message-id="message.id" />
        <SQLViewer v-if="activeTab === 'sql'" :sql="message.sql_query || ''" />
        <ChartView v-if="activeTab === 'chart' && results" :results="results" :config="message.chart_config!" />
      </template>
    </div>
  </div>
</template>
