<script setup lang="ts">
/**
 * `card.datatable` element composition.
 *
 * Renders a simple sortable data table. Column definitions come from
 * `tableColumns`; row data is either supplied via `item[name]` or fetched
 * from `dataRoute`. Full pagination/filter support is handled by the
 * platform's DataTableCard when used in the card-tier — this element-tier
 * variant is intentionally lightweight for inline embedding.
 */
import { computed } from "vue"
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { cn } from "@/lib/utils"

interface TableColumn {
  key: string
  label: string
  sortable?: boolean
}

export interface DatatableCardProps {
  label?: string
  title?: string
  showCard?: boolean
  tableColumns?: TableColumn[]
  /** Data rows supplied inline (e.g. from `item[name]`). */
  rows?: Array<Record<string, unknown>>
  /** API route for fetching rows (displayed as a hint when rows is empty). */
  dataRoute?: string
  item?: Record<string, unknown>
  name?: string | null
  classList?: string[] | string
}

const props = withDefaults(defineProps<DatatableCardProps>(), {
  showCard: true,
  tableColumns: () => [],
  rows: () => [],
  item: () => ({}),
})

const heading = computed(() => props.title ?? props.label)

const resolvedRows = computed<Array<Record<string, unknown>>>(() => {
  if (props.rows && props.rows.length > 0) return props.rows
  const name = props.name
  if (name && props.item[name]) {
    const val = props.item[name]
    if (Array.isArray(val)) return val as Array<Record<string, unknown>>
  }
  return []
})

function cellValue(row: Record<string, unknown>, col: TableColumn): string {
  const val = row[col.key]
  return val !== undefined && val !== null ? String(val) : "—"
}
</script>

<template>
  <Card v-if="props.showCard !== false" :class="cn(props.classList)">
    <CardHeader v-if="heading">
      <CardTitle>{{ heading }}</CardTitle>
    </CardHeader>
    <CardContent>
      <Table v-if="props.tableColumns.length">
        <TableHeader>
          <TableRow>
            <TableHead
              v-for="col in props.tableColumns"
              :key="col.key"
            >
              {{ col.label }}
            </TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          <TableRow
            v-for="(row, i) in resolvedRows"
            :key="i"
          >
            <TableCell
              v-for="col in props.tableColumns"
              :key="col.key"
            >
              {{ cellValue(row, col) }}
            </TableCell>
          </TableRow>
          <TableRow v-if="!resolvedRows.length">
            <TableCell
              :colspan="props.tableColumns.length || 1"
              class="text-center text-muted-foreground"
            >
              {{ props.dataRoute ? `Data fetched from: ${props.dataRoute}` : "No data." }}
            </TableCell>
          </TableRow>
        </TableBody>
      </Table>
      <p v-else class="text-sm text-muted-foreground">No columns configured.</p>
    </CardContent>
  </Card>

  <div v-else :class="cn(props.classList)">
    <Table v-if="props.tableColumns.length">
      <TableHeader>
        <TableRow>
          <TableHead v-for="col in props.tableColumns" :key="col.key">{{ col.label }}</TableHead>
        </TableRow>
      </TableHeader>
      <TableBody>
        <TableRow v-for="(row, i) in resolvedRows" :key="i">
          <TableCell v-for="col in props.tableColumns" :key="col.key">{{ cellValue(row, col) }}</TableCell>
        </TableRow>
      </TableBody>
    </Table>
  </div>
</template>
