<script setup lang="ts">
import {ui} from './table.config'
import { twMerge } from 'tailwind-merge'
type Column = {
  label: string
  key: string | number
  class?: string
}
type Row = {
  [key: string]: any
}
interface Props {
  columns: Column[],
  columnAttribute?: keyof Column
  rows: Row[]
  loading?: boolean
  size?: 'sm' | 'md'
  classHead?: string
}
const props = withDefaults(defineProps<Props>(),{
  columnAttribute: "label",
  loading: true,
  size: 'md',
  classHead: '',
})

const {t} = useI18n()

function getRowData (row, rowKey, defaultValue: any = '') {
  return row[rowKey] ?? defaultValue
}

</script>

<template>
  <div :class="ui.wrapper">
    <table :class="[ui.base, ui.divide]">
      <thead :class="ui.thead">
        <tr :class="twMerge(ui.tr.base, classHead)">
          <th
            v-for="(column, index) in columns"
            :key="index"
            scope="col"
            :class="[ui.th.base, ui.th.padding, ui.th.color, ui.th.font, ui.th.size, column.class]"
          >
            <slot
              :name="`${column.key}-header`"
              :column="column"
            >
              <span>{{ t(column[columnAttribute]) }}</span>
            </slot>
          </th>
        </tr>
        <tr v-if="loading">
          <td
            :colspan="0"
            :class="ui.progress.wrapper"
          />
        </tr>
      </thead>
      <tbody :class="ui.tbody">
        <slot
          name="extra_row-top"
          :base-class="{row: ui.tr.base, td: [ui.td.base, ui.td.padding[size], ui.td.color, ui.td.font, ui.td.size]}"
        />
        <tr
          v-for="(row, index) in rows"
          :key="index"
          :class="twMerge(ui.tr.base, row?.class)"
        >
          <td
            v-for="(column, subIndex) in columns"
            :key="subIndex"
            :class="[ui.td.base, ui.td.padding[size], ui.td.color, ui.td.font, ui.td.size, column.class]"
          >
            <slot
              :name="`${column.key}-data`"
              :column="column"
              :row="row"
              :index="index"
            >
              {{ getRowData(row, column.key) }}
            </slot>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<style scoped>

</style>
