<template>
  <div class="table-container">

    <div v-if="searchbar" class="table-search-bar-container">

      <search-bar class="search-bar" v-model="filter" @input-changed="reload"></search-bar>
    </div>


    <div class="table-wrapper">
      <table class="data-table">
        <thead>
        <tr>
          <th v-for="column in columns" :key="column.key" class="table-header" :class="getAlignment(column.align)">
            {{ column.label }}
          </th>
        </tr>
        </thead>
        <transition name="list-container" mode="out-in">
          <tbody v-if="data.length === 0">
          <tr class="no-data">
            <td :colspan="columns.length" class="no-data-cell">
              {{ filter ? 'No results found' : 'No data available' }}
            </td>
          </tr>
          </tbody>
          <tbody v-else-if="loading">
          <tr class="no-data">
            <td :colspan="columns.length" class="no-data-cell">
              <spinner class="space-around"></spinner>
            </td>
          </tr>
          </tbody>
          <tbody v-else>
          <tr v-for="(item, index) in data" :key="index" class="table-row" @click="$emit('row-click', item)"
              :class="{'table-row--hover': mouseOver}">
            <td v-for="column in columns" :key="column.key" class="table-cell" :class="getAlignment(column.align)">

              <flag v-if="column.showFlag" :tooltip-text="getCellValue(item, column)" :iso="getCellValue(item, column)"></flag>
              <div class="badge-container" v-else-if="column.badgeResolver != null && typeof column.badgeResolver === 'function'">
                <basic-badge v-for="badge in getCellValue(item, column)" :variant="badge.variant">{{ badge.text }}</basic-badge>
              </div>
              <span v-else-if="column.iconResolver == null">{{ getCellValue(item, column) }}</span>
              <component v-else
                         :is="getCellValue(item, column)"
                         weight="regular"
                         size="24"
                         class="table-icon"
              />


            </td>
          </tr>
          </tbody>
        </transition>
      </table>
    </div>
  </div>

  <pagination :total-count="totalCount" :page-count="pageCount" :page="page" @page-change="updatePage"></pagination>


</template>

<script>

import Spinner from "@/components/UI/Spinner.vue";
import Checkbox from "@/components/UI/Checkbox.vue";
import BasicButton from "@/components/UI/BasicButton.vue";
import SearchBar from "@/components/UI/SearchBar.vue";
import Box from "@/components/UI/Box.vue";
import Pagination from "@/components/UI/Pagination.vue";
import Flag from "@/components/UI/Flag.vue";
import basicBadge from "@/components/UI/BasicBadge.vue";
import BasicBadge from "@/components/UI/BasicBadge.vue";

export default {
  name: "TableView",
  components: {BasicBadge, Flag, Pagination, Box, SearchBar, BasicButton, Checkbox, Spinner},
  emits: ['row-click'],
  props: {
    dataSource: {
      type: Function,
      required: true
    },
    mouseOver: {
      type: Boolean,
      default: false,

    },
    searchbar: {
      type: Boolean,
      default: true
    },
    columns: {
      type: Array,
      required: true,
      validator(columns) {
        return columns.every(col => col.key && col.label);
      }
    },
    page: {
      type: Number,
      default: 1,
    },
    pageSize: {
      type: Number,
      default: 10
    },
    pageCount: {
      type: Number,
      default: 1
    },
    totalCount: {
      type: Number,
      default: 0
    }
  },
  mounted() {
    this.reload();
  },
  computed: {
    basicBadge() {
      return basicBadge
    }
  },
  methods: {
    async updatePage(page) {
      this.reload(this.filter, page);
    },
    async reload(filter, page = 1) {
      this.loading = true;

      const query = {searchTerm: filter, page: page, pageSize: this.pageSize};

      this.data = await this.dataSource(query);
      this.loading = false;
    },
    getNestedValue(obj, path) {
      return path.split('.').reduce((current, key) => {
        return current && current[key] !== undefined ? current[key] : null;
      }, obj);
    },
    getAlignment(alignment) {
      if (alignment == null || alignment === 'left') {
        return 'table-cell--left';
      } else if (alignment === 'right') {
        return 'table-cell--right';
      } else if (alignment === 'center') {
        return 'table-cell--center';
      }
    },
    getCellValue(item, column) {
      const rawValue = this.getNestedValue(item, column.key);

      if (column.iconResolver && typeof column.iconResolver === 'function') {
        return column.iconResolver(rawValue, item);
      }

      if (column.badgeResolver && typeof column.badgeResolver === 'function') {
        return column.badgeResolver(rawValue, item);
      }

      if (column.iconResolver) {
        return 'PhImageBroken';
      }

      if (column.formatter && typeof column.formatter === 'function') {
        return column.formatter(rawValue, item);
      }

      return rawValue !== null && rawValue !== undefined ? rawValue : '';
    },
  },
  data() {
    return {
      data: [],
      filter: '',
      loading: false,
    };
  },
}
</script>


<style scoped>

/* Container Animation */
.list-container-enter-active, .list-container-leave-active {
  transition: all 0.3s ease;
}

.list-container-enter-from, .list-container-leave-to {
  opacity: 0;
}

.badge-container {
  display: flex;
  gap: 0.8rem;
}

.table-icon {
  transition: all 0.1s ease-in-out;
  color: #6B869C;
}

.search-bar {
  width: 30%;
}

.table-search-bar-container {
  display: flex;
  justify-content: flex-end;
  padding: 1.6rem;
}

.no-data-cell {
  text-align: center;
  font-size: 1.6rem;
  color: #6B869C;
  padding: 2.4rem;
}

.table-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 1.6rem;
  overflow: visible;
  border-radius: 0.8rem;
  background-color: #FFFFFF;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.space-around {
  margin: 3rem;
}


.data-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  background-color: transparent;
  border: 0 solid #E3EDFF;

}

.table-header {

  border-bottom: 1px solid rgba(107, 134, 156, 0.2);
  font-weight: 500;
  font-size: 1.4rem;
  color: #6B869C;
  text-transform: uppercase;
  letter-spacing: 0.08rem;
  text-align: left;
  padding: 1.6rem 1.6rem 1.6rem 0;
}

.table-row {
  font-weight: 400;
  font-size: 1.4rem;
  color: #6B869C;
}

.table-cell {
  padding: 0.8rem;
  background-color: transparent;
  border-bottom: 0.1rem solid #E3EDFF;
  text-align: right;
}

.table-cell-content {
  display: flex;
  align-items: center;
  gap: 0.8rem;
}

.table-cell--left {
  text-align: left;
}


.table-cell--right {
  text-align: right;
}

.table-cell--center {
  text-align: center;
}

.table-row:hover {
  background-color: rgba(107, 134, 156, 0.05);
}

.table-row--hover {
  cursor: pointer;
}


</style>