<script setup lang="ts">
import { computed } from 'vue';
import { storeToRefs } from 'pinia';
import { QTableSlots } from 'quasar';
import { DebitNote, useDebitNote } from 'src/stores/debit-note';

import { columns } from './constants.ts';
import KebabAction from 'src/components/shared/KebabAction.vue';

const debitNote = useDebitNote();
const { data, page, pageSize } = storeToRefs(debitNote);

const prop = defineProps<{ grid: boolean; visibleColumns: string[] }>();
defineEmits<{ (evt: 'view' | 'delete' | 'edit', val: DebitNote): void }>();

const visible = computed(() =>
  columns.filter(
    (v) => prop.visibleColumns.includes(v.name) || v.name === '#action',
  ),
);
</script>
<template>
  <q-table
    :rows-per-page-options="[0]"
    :rows="
      data.map((item, i) => ({
        ...item,
        _index: i,
        _page: page,
        _pageSize: pageSize,
      }))
    "
    :columns="visible"
    :grid
    hide-bottom
    bordered
    flat
    hide-pagination
    selection="multiple"
    card-container-class="q-col-gutter-sm"
    class="full-width"
  >
    <template v-slot:header="props">
      <q-tr
        style="background-color: hsla(var(--info-bg) / 0.07)"
        :props="props"
      >
        <q-th v-for="col in visible" :key="col.name" :props="props">
          <template v-if="!col.name.startsWith('#')">
            {{ $t(col.label) }}
          </template>
        </q-th>
      </q-tr>
    </template>

    <template
      v-slot:body="props: {
        row: DebitNote & { _index: number; _page: number; _pageSize: number };
      } & Omit<Parameters<QTableSlots['body']>[0], 'row'>"
    >
      <q-tr :class="{ dark: $q.dark.isActive }" class="text-center">
        <q-td v-for="col in visible" :align="col.align" :key="col.name">
          <!-- NOTE: custom column will starts with # -->
          <template v-if="!col.name.startsWith('#')">
            <span v-if="col.name !== 'quotationPayment'">
              {{
                typeof col.field === 'string'
                  ? props.row[col.field as keyof DebitNote]
                  : col.field(props.row)
              }}
            </span>

            <span v-if="col.name === 'quotationPayment'">
              {{ $t(`quotation.type.${col.field(props.row)}`) }}
            </span>
          </template>

          <template v-if="col.name === '#action'">
            <KebabAction
              :id-name="`btn-kebab-${props.row.workName}`"
              hide-toggle
              hide-edit
              @edit="$emit('edit', props.row)"
              @delete="$emit('delete', props.row)"
              @view="$emit('view', props.row)"
            />
          </template>
        </q-td>
      </q-tr>
    </template>

    <template v-slot:item="props: { row: DebitNote }">
      <slot name="grid" :item="props" />
    </template>
  </q-table>
</template>
