<script setup lang="ts">
import MarketEntityLink from "../market/MarketEntityLink.vue";

type TableColumn = {
  key: string;
  label: string;
  numeric?: boolean;
  wide?: boolean;
  code?: boolean;
  sortable?: boolean;
  format?: (value: unknown, row: Record<string, unknown>) => string;
};

const props = withDefaults(defineProps<{
  columns: TableColumn[];
  rows: Record<string, unknown>[];
  sortKey: string;
  sortDirection: "asc" | "desc";
  entityType?: "stock" | "sector" | "theme" | "index";
}>(), { entityType: "stock" });
const emit = defineEmits<{ sort: [key: string] }>();

function ariaSort(key: string, sortable?: boolean): "ascending" | "descending" | "none" | undefined {
  if (!sortable) return undefined;
  if (key !== props.sortKey) return "none";
  return props.sortDirection === "asc" ? "ascending" : "descending";
}
</script>

<template>
  <div class="data-table-wrap">
    <table class="data-table">
      <thead>
        <tr>
          <th class="index-column" scope="col">序号</th>
          <th v-for="column in columns" :key="column.key" scope="col" :aria-sort="ariaSort(column.key, column.sortable)" :class="{ numeric: column.numeric, 'wide-column': column.wide, 'code-column': column.code }">
            <button v-if="column.sortable" type="button" @click="emit('sort', column.key)">
              {{ column.label }}<span v-if="sortKey === column.key">{{ sortDirection === "asc" ? "↑" : "↓" }}</span>
            </button>
            <span v-else>{{ column.label }}</span>
          </th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(row, index) in rows" :key="String(row.identifier ?? index)">
          <td class="index-column numeric">{{ index + 1 }}</td>
          <td v-for="column in columns" :key="column.key" :data-label="column.label" :class="{ numeric: column.numeric, 'wide-column': column.wide, 'code-column': column.code, up: column.key.includes('change') && Number(row[column.key]) > 0, down: column.key.includes('change') && Number(row[column.key]) < 0 }">
            <MarketEntityLink
              v-if="column.code && row.identifier && row.code && row.name"
              :entity="{ entity_type: entityType, identifier: String(row.identifier), code: String(row.code), name: String(row.name), sector: row.sector ? String(row.sector) : null }"
              :label="String(column.format ? column.format(row[column.key], row) : row[column.key])"
            />
            <template v-else>{{ column.format ? column.format(row[column.key], row) : (row[column.key] ?? "") }}</template>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>
