<template>
  <div class="table-wrap">
    <table class="payout-table">
      <thead>
        <tr>
          <th
            v-for="column in resolvedColumns"
            :key="column.key"
            :class="`payout-cell--${column.align ?? 'center'}`"
          >
            <div class="header-wrapper">
              <div class="header-content">
                <span class="header-label">
                  {{ column.label }}
                </span>

                <q-icon
                  class="cursor-pointer sort-icon q-my-md"
                  size="15px"
                  :color="column.direction ? 'primary' : '#b0b0b0'"
                  :name="column.direction === 'desc' ? 'south' : 'north'"
                  @click="toggleSort(column)"
                />
              </div>
            </div>
          </th>
        </tr>
      </thead>

      <tbody>
        <tr v-for="item in sortedRows" :key="resolveRowKey(item)">
          <td
            v-for="column in resolvedColumns"
            :key="column.key"
            :class="`payout-cell--${column.align ?? 'center'}`"
          >
            {{ formatCell(resolveColumnValue(item, column), column) }}
          </td>
        </tr>

        <tr v-if="!sortedRows.length">
          <td class="payout-empty-row" :colspan="resolvedColumns.length">
            {{ emptyLabel }}
          </td>
        </tr>

        <tr class="payout-total-row">
          <td :class="`payout-cell--${resolvedColumns[0]?.align ?? 'center'}`">
            {{ totalLabel }}
          </td>

          <td
            v-for="column in totalColumns"
            :key="column.key"
            :class="`payout-cell--${column.align ?? 'center'}`"
          >
            {{ formatCell(resolvedTotalRow[column.key], column) }}
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script setup>
import { computed, ref, watch } from "vue";

const props = defineProps({
  columns: {
    type: Array,
    default: null,
  },

  emptyLabel: {
    type: String,
    default: "Nenhum registro encontrado para o período.",
  },

  rowKey: {
    type: String,
    default: "property_id",
  },

  rows: {
    type: Array,
    default: () => [],
  },

  totalLabel: {
    type: String,
    default: "Total",
  },

  totalRow: {
    type: Object,
    default: null,
  },

  totalReservations: {
    type: Number,
    default: 0,
  },

  totalValue: {
    type: Number,
    default: 0,
  },
});

const defaultColumns = [
  {
    key: "property_label",
    label: "Unidade",
    type: "text",
    align: "left",
    direction: null,
  },

  {
    key: "reservations_count",
    label: "Reservas",
    type: "reservations",
    align: "left",
    direction: null,
  },

  {
    key: "final_payout_amount",
    label: "Valor",
    type: "currency",
    align: "left",
    direction: null,
  },
];

const tableColumns = ref([]);

const cloneColumns = (value) => value.map((column) => ({ ...column }));

const resolvedColumns = computed(() => tableColumns.value);

const totalColumns = computed(() => resolvedColumns.value.slice(1));

const resolvedTotalRow = computed(() => {
  if (props.totalRow) {
    return props.totalRow;
  }

  return {
    reservations_count: props.totalReservations,
    final_payout_amount: props.totalValue,
  };
});

const toggleSort = (column) => {
  tableColumns.value.forEach((item) => {
    if (item !== column) {
      item.direction = null;
    }
  });

  column.direction = column.direction === "asc" ? "desc" : "asc";
};

const sortedRows = computed(() => {
  const activeSorts = resolvedColumns.value.filter(
    (column) => column.direction,
  );

  if (!activeSorts.length) {
    return [...props.rows];
  }

  return [...props.rows].sort((a, b) => {
    for (const sort of activeSorts) {
      const direction = sort.direction === "asc" ? 1 : -1;

      const valueA = resolveColumnValue(a, sort);
      const valueB = resolveColumnValue(b, sort);

      if (valueA > valueB) {
        return direction;
      }

      if (valueA < valueB) {
        return -direction;
      }
    }

    return 0;
  });
});

const resolveColumnValue = (item, column) => {
  if (typeof column.value === "function") {
    return column.value(item);
  }

  if (column.key === "reservations_count") {
    return resolveReservationsCount(item);
  }

  return item[column.key];
};

const resolveReservationsCount = (item) =>
  Number(
    item.checkout_reservations_count ??
      item.distinct_reservations_count ??
      item.reservations_count ??
      0,
  );

const resolveRowKey = (item) => {
  return item[props.rowKey] ?? item.key ?? item.id ?? JSON.stringify(item);
};

const formatCell = (value, column) => {
  if (column.type === "currency") {
    return formatCurrency(value);
  }

  if (column.type === "reservations") {
    return formatReservations(value);
  }

  if (column.type === "integer") {
    return formatInteger(value);
  }

  return value ?? "";
};

const formatCurrency = (value) => {
  return new Intl.NumberFormat("pt-BR", {
    style: "currency",
    currency: "BRL",
    minimumFractionDigits: 2,
  }).format(Number(value ?? 0));
};

const formatInteger = (value) => {
  return Number(value ?? 0).toLocaleString("pt-BR");
};

const formatReservations = (value) => {
  const reservations = Number(value ?? 0);
  const label = reservations === 1 ? "reserva" : "reservas";

  return `${formatInteger(reservations)} ${label}`;
};

watch(
  () => props.columns,
  (value) => {
    tableColumns.value = cloneColumns(value?.length ? value : defaultColumns);
  },
  { immediate: true, deep: true },
);
</script>

<style scoped lang="scss">
.table-wrap {
  overflow-x: auto;
}

.payout-table {
  width: 100%;
  border-collapse: collapse;
}

.payout-table th,
.payout-table td {
  padding: 10px 16px;
  border-bottom: 1px solid #aaaaaa;
  color: #273136;
  vertical-align: middle;
  text-align: center;
}

.payout-table th {
  font-size: 17px !important;
  font-weight: 700;
  color: #232323;
}

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

.payout-cell--left .header-wrapper {
  align-items: flex-start;
}

.payout-total-row td {
  font-size: 17px !important;
  font-weight: 700;
  border-bottom: 0;
  color: #4d4e4e;
  text-align: center;
}

.payout-empty-row {
  color: #7b878c;
}

.header-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 4px;
}

.header-label {
  line-height: 1;
}

.sort-icon {
  transition: 0.2s ease;
}

.sort-icon:hover {
  opacity: 1;
  transform: scale(1.08);
}

.cursor-pointer {
  cursor: pointer;
}

@media (max-width: 640px) {
  .payout-table {
    min-width: 0;
  }

  .payout-table th,
  .payout-table td {
    padding: 8px 12px;
    font-size: 13px;
  }

  .payout-table th,
  .payout-total-row td {
    font-size: 14px !important;
  }

  .header-content {
    gap: 2px;
  }
}
</style>
