<template>
  <thead class="eli-tabela__thead">
    <tr class="eli-tabela__tr eli-tabela__tr--header">
      <th v-if="temColunasInvisiveis" class="eli-tabela__th eli-tabela__th--expander" scope="col"></th>

      <th
        v-for="(coluna, idx) in colunas"
        :key="`th-${idx}`"
        class="eli-tabela__th"
        :class="[isOrdenavel(coluna) ? 'eli-tabela__th--ordenavel' : undefined]"
        scope="col"
      >
        <button
          v-if="isOrdenavel(coluna)"
          type="button"
          class="eli-tabela__th-botao"
          :class="[
            colunaOrdenacao === String(coluna.coluna_ordem) ? 'eli-tabela__th-botao--ativo' : undefined,
          ]"
          @click="emitAlternarOrdenacao(String(coluna.coluna_ordem))"
        >
          <span class="eli-tabela__th-texto">{{ coluna.rotulo }}</span>

          <component
            v-if="colunaOrdenacao === String(coluna.coluna_ordem)"
            :is="direcaoOrdenacao === 'asc' ? ArrowUp : ArrowDown"
            class="eli-tabela__th-icone"
            :size="16"
            :stroke-width="2"
            aria-hidden="true"
          />
          <ArrowUp
            v-else
            class="eli-tabela__th-icone eli-tabela__th-icone--oculto"
            :size="16"
            :stroke-width="2"
            aria-hidden="true"
          />
        </button>

        <span v-else class="eli-tabela__th-label">{{ coluna.rotulo }}</span>
      </th>

      <th v-if="temAcoes" class="eli-tabela__th eli-tabela__th--acoes" scope="col">
        Ações
      </th>
    </tr>
  </thead>
</template>

<script lang="ts">
import { defineComponent, PropType } from "vue";
import { ArrowDown, ArrowUp } from "lucide-vue-next";
import type { EliColuna } from "./types-eli-tabela";

export default defineComponent({
  name: "EliTabelaHead",
  components: { ArrowUp, ArrowDown },
  props: {
    colunas: {
      type: Array as PropType<Array<EliColuna<any>>>,
      required: true,
    },
    temAcoes: {
      type: Boolean,
      required: true,
    },
    temColunasInvisiveis: {
      type: Boolean,
      required: true,
    },
    colunaOrdenacao: {
      type: String as PropType<string | null>,
      required: true,
    },
    direcaoOrdenacao: {
      type: String as PropType<"asc" | "desc">,
      required: true,
    },
  },
  emits: {
    alternarOrdenacao(chave: string) {
      return typeof chave === "string" && chave.length > 0;
    },
  },
  setup(_props, { emit }) {
    function isOrdenavel(coluna: any) {
      return coluna?.coluna_ordem !== undefined && coluna?.coluna_ordem !== null;
    }

    function emitAlternarOrdenacao(chave: string) {
      emit("alternarOrdenacao", chave);
    }

    return {
      ArrowUp,
      ArrowDown,
      isOrdenavel,
      emitAlternarOrdenacao,
    };
  },
});
</script>
