<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useDatabaseApi, useDataTable, useQueryExecutor } from '@/composables/database'
import {
  DatabaseSidebar,
  DataTable,
  FilterBar,
  SchemaInfo,
  QueryEditor,
  QueryColumnsBar,
  DatabaseStats,
  TablePagination
} from '@/components/database'

// API
const {
  tables,
  tableSchema,
  tableData,
  dbStats,
  loading,
  error,
  totalRecords,
  fetchTables,
  fetchDbStats,
  fetchTableSchema,
  fetchTableData
} = useDatabaseApi()

// Table data management
const tableDataTable = useDataTable({ data: tableData })

// Query executor
const query = useQueryExecutor()

// Query result data management
const queryDataTable = useDataTable({ data: computed(() => query.queryResult.value || []) })

// Local state
const selectedTable = ref<string | null>(null)
const activeTab = ref<'tables' | 'query' | 'stats'>('tables')
const currentPage = ref(1)
const pageSize = ref(50)

const totalPages = computed(() => Math.ceil(totalRecords.value / pageSize.value))

async function selectTable(tableName: string) {
  selectedTable.value = tableName
  currentPage.value = 1
  tableDataTable.reset()
  await Promise.all([
    fetchTableSchema(tableName),
    fetchTableData(tableName, currentPage.value, pageSize.value)
  ])
}

function changePage(page: number) {
  if (page >= 1 && page <= totalPages.value && selectedTable.value) {
    currentPage.value = page
    tableDataTable.selectedRows.value.clear()
    fetchTableData(selectedTable.value, page, pageSize.value)
  }
}

async function handleExecuteQuery() {
  queryDataTable.reset()
  await query.executeQuery()
}

onMounted(() => {
  fetchTables()
  fetchDbStats()
})
</script>

<template>
  <div class="database-page">
    <DatabaseSidebar
      :tables="tables"
      :selected-table="selectedTable"
      :stats="dbStats"
      :loading="loading"
      :error="error"
      @select-table="selectTable"
      @refresh="fetchTables"
    />

    <main class="content">
      <div class="tabs">
        <button :class="{ active: activeTab === 'tables' }" @click="activeTab = 'tables'">
          Explorer
        </button>
        <button :class="{ active: activeTab === 'query' }" @click="activeTab = 'query'">
          Query
        </button>
        <button :class="{ active: activeTab === 'stats' }" @click="activeTab = 'stats'">
          Stats
        </button>
      </div>

      <!-- Tables Tab -->
      <div v-if="activeTab === 'tables'" class="tab-content">
        <div v-if="!selectedTable" class="placeholder">
          <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
            <ellipse cx="12" cy="5" rx="9" ry="3"/>
            <path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"/>
            <path d="M3 12c0 1.66 4 3 9 3s9-1.34 9-3"/>
          </svg>
          <p>Select a table to view data</p>
        </div>

        <div v-else class="table-view">
          <SchemaInfo
            :table-name="selectedTable"
            :schema="tableSchema"
            :hidden-columns="tableDataTable.hiddenColumns.value"
            @toggle-column="tableDataTable.toggleColumn"
          />

          <FilterBar
            v-model="tableDataTable.filter.value"
            :row-count="tableDataTable.filteredData.value.length"
            :total-count="tableData.length"
            :selected-count="tableDataTable.selectedRows.value.size"
            :visible-col-count="tableDataTable.visibleColumns.value.length"
            :total-col-count="tableDataTable.allColumns.value.length"
            :copied="tableDataTable.copiedAll.value"
            @copy-all="tableDataTable.copyAll"
          />

          <DataTable
            :data="tableDataTable.filteredData.value"
            :visible-columns="tableDataTable.visibleColumns.value"
            :selected-rows="tableDataTable.selectedRows.value"
            :all-selected="tableDataTable.allRowsSelected.value"
            :copied-cell="tableDataTable.copiedCell.value"
            cell-id-prefix="data"
            @toggle-row="tableDataTable.toggleRow"
            @toggle-all="tableDataTable.toggleAllRows"
            @copy-cell="tableDataTable.copyCell"
          />

          <TablePagination
            :current-page="currentPage"
            :total-pages="totalPages"
            @change-page="changePage"
          />
        </div>
      </div>

      <!-- Query Tab -->
      <div v-if="activeTab === 'query'" class="tab-content query-tab">
        <QueryEditor
          v-model="query.queryText.value"
          :loading="query.queryLoading.value"
          @execute="handleExecuteQuery"
        />

        <div class="query-results">
          <div v-if="query.queryError.value" class="query-error">
            {{ query.queryError.value }}
          </div>
          <div v-else-if="query.queryResult.value" class="query-results-content">
            <QueryColumnsBar
              :columns="queryDataTable.allColumns.value"
              :hidden-columns="queryDataTable.hiddenColumns.value"
              @toggle-column="queryDataTable.toggleColumn"
            />

            <FilterBar
              v-model="queryDataTable.filter.value"
              :row-count="queryDataTable.filteredData.value.length"
              :total-count="query.queryResult.value.length"
              :selected-count="queryDataTable.selectedRows.value.size"
              :visible-col-count="queryDataTable.visibleColumns.value.length"
              :total-col-count="queryDataTable.allColumns.value.length"
              :copied="queryDataTable.copiedAll.value"
              @copy-all="queryDataTable.copyAll"
            />

            <DataTable
              :data="queryDataTable.filteredData.value"
              :visible-columns="queryDataTable.visibleColumns.value"
              :selected-rows="queryDataTable.selectedRows.value"
              :all-selected="queryDataTable.allRowsSelected.value"
              :copied-cell="queryDataTable.copiedCell.value"
              cell-id-prefix="query"
              @toggle-row="queryDataTable.toggleRow"
              @toggle-all="queryDataTable.toggleAllRows"
              @copy-cell="queryDataTable.copyCell"
            >
              <template #empty>Query returned no results</template>
            </DataTable>
          </div>
        </div>
      </div>

      <!-- Stats Tab -->
      <DatabaseStats
        v-if="activeTab === 'stats'"
        :stats="dbStats"
        :tables="tables"
      />
    </main>
  </div>
</template>

<style scoped>
.database-page {
  display: flex;
  flex: 1;
  overflow: hidden;
  background: var(--bg-primary);
}

.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.tabs {
  display: flex;
  gap: 0.25rem;
  padding: 0.75rem 1.5rem;
  background: var(--bg-secondary);
  border-bottom: 1px solid var(--border-color);
}

.tabs button {
  padding: 0.5rem 1rem;
  background: transparent;
  border: none;
  border-radius: 6px;
  color: var(--text-secondary);
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.15s;
}

.tabs button:hover {
  background: var(--bg-hover);
  color: var(--text-primary);
}

.tabs button.active {
  background: var(--accent-muted);
  color: var(--accent);
}

.tab-content {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.placeholder {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: var(--text-muted);
  gap: 1rem;
}

.placeholder p {
  margin: 0;
  font-size: 0.95rem;
}

.table-view {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.query-tab {
  padding: 1rem;
  gap: 1rem;
}

.query-results {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.query-results-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.query-error {
  padding: 1rem;
  background: var(--error-bg);
  color: var(--error);
  border-radius: 6px;
  font-size: 0.875rem;
}

@media (max-width: 768px) {
  .database-page {
    flex-direction: column;
  }
}
</style>
