<script setup lang="ts">
import { isRef } from 'vue';
import type { DataTableLoader } from '~/components/pub/my-ui/data/types'
import type { Config } from './index'
import { Info } from 'lucide-vue-next'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '~/components/pub/ui/table'

const props = defineProps<Config & { rows: unknown[] }>()

const emit = defineEmits<{
  (e: 'update:modelValue', val: any[] | any): void
}>()

const getSkeletonSize = computed(() => {
  return props.skeletonSize || 5
})
const loader = inject('table_data_loader') as DataTableLoader

// local state utk selection
const selected = ref<any[]>([])

function toggleSelection(row: any) {
  if (props.selectMode === 'single') {
    selected.value = [row]
    emit('update:modelValue', row)
  } else {
    const idx = selected.value.findIndex((r) => r === row)
    if (idx >= 0) {
      selected.value.splice(idx, 1)
    } else {
      selected.value.push(row)
    }
    emit('update:modelValue', [...selected.value])
  }
}

function deepFetch(data: Record<string, any>, key: string): string {
  let result = '';
  const keys = key.split('.')
  let lastVal: any = isRef(data) ? {...(data.value as any)} : data
  for (let i = 0; i < keys.length; i++) {
    let idx = keys[i] || ''
    if (typeof lastVal[idx] != undefined && lastVal[idx] != null) {
      if (i == keys.length - 1) {
        return lastVal[idx];
      } else {
        lastVal = isRef(lastVal[idx]) ? {...(lastVal[idx].value as any)} : lastVal[idx]
      }
    }
  }
  return result;
}


function handleActionCellClick(event: Event, _cellRef: string) {
  // Prevent event if clicked directly on the button/dropdown
  const target = event.target as HTMLElement
  if (target.closest('button') || target.closest('[role="button"]')) {
    return
  }

  // Find the dropdown trigger button and click it
  const cell = event.currentTarget as HTMLElement
  const triggerButton = cell.querySelector('button[data-state]') || cell.querySelector('button')
  if (triggerButton) {
    ;(triggerButton as HTMLButtonElement).click()
  }
}
</script>

<template>
  <Table>
    <TableHeader v-if="headers" class="bg-gray-50 dark:bg-gray-800">
      <TableRow>
        <TableHead
          v-for="(h, idx) in headers[0]"
          :key="`head-${idx}`"
          class="border"
          :style="{ width: cols[idx]?.width ? `${cols[idx].width}px` : undefined }"
        >
          {{ h.label }}
        </TableHead>
      </TableRow>
    </TableHeader>

    <TableBody v-if="loader?.isTableLoading">
      <!-- Loading state with 5 skeleton rows -->
      <TableRow v-for="n in getSkeletonSize" :key="`skeleton-${n}`">
        <TableCell v-for="(key, cellIndex) in keys" :key="`cell-skel-${n}-${cellIndex}`" class="border">
          <Skeleton class="h-6 w-full animate-pulse bg-gray-100 dark:bg-gray-700 text-muted-foreground" />
        </TableCell>
      </TableRow>
    </TableBody>
    <TableBody v-else-if="rows.length === 0">
      <TableRow>
        <TableCell :colspan="keys.length" class="py-8 text-center">
          <div class="flex items-center justify-center">
            <Info class="size-5 text-muted-foreground" />
            <span class="ml-2">Tidak ada data tersedia</span>
          </div>
        </TableCell>
      </TableRow>
    </TableBody>
    <TableBody v-else>
      <TableRow
        v-for="(row, rowIndex) in rows"
        :key="`row-${rowIndex}`"
        :class="{
          'bg-green-50': props.selectMode === 'single' && selected.includes(row),
          'bg-blue-50': props.selectMode === 'multiple' && selected.includes(row),
        }"
        @click="toggleSelection(row)"
      >
        <!-- opsional: kalau mau tampilkan checkbox/radio di cell pertama -->
        <TableCell v-if="props.selectMode">
          <input
            v-if="props.selectMode === 'single'"
            type="radio"
            :checked="selected.includes(row)"
            @change="toggleSelection(row)"
          />
          <input v-else type="checkbox" :checked="selected.includes(row)" @change="toggleSelection(row)" />
        </TableCell>

        <!-- lanjut render cell normal -->
        <TableCell v-for="(key, cellIndex) in keys" :key="`cell-${rowIndex}-${cellIndex}`" class="border">
          <!-- existing cell renderer -->
          <component
            :is="components?.[key]?.(row, rowIndex).component"
            v-if="components?.[key]"
            :rec="row"
            :idx="rowIndex"
            v-bind="components[key]?.(row, rowIndex).props"
          />
          <template v-else>
            <div v-if="htmls?.[key]" v-html="htmls?.[key]?.(row, rowIndex)"></div>
            <template v-else>
              {{ parses?.[key]?.(row, rowIndex) ?? deepFetch((row as any), key) }}
            </template>
          </template>
        </TableCell>
      </TableRow>
    </TableBody>
  </Table>
</template>
