<template>
  <div class="table-wrap">
    <table class="payout-table">
      <thead>
        <tr>
          <th
            v-for="(column, index) in columns"
            :key="column.key"
          >
            <div class="header-wrapper">
              <div class="header-content">
                <q-icon
                  class="cursor-pointer sort-icon q-my-md"
                  :name="
                    column.direction === 'desc'
                      ? 'south'
                      : 'north'
                  "
                  size="15px"
                  :color="
                    column.direction
                      ? 'primary'
                      : '#b0b0b0'
                  "
                  @click="toggleSort(column)"
                />

                <q-icon
                  class="cursor-pointer move-icon"
                  color="#888"
                  name="chevron_left"
                  size="18px"
                  @click="moveLeft(index)"
                />

                <span class="header-label">
                  {{ column.label }}
                </span>

                <q-icon
                  class="cursor-pointer move-icon"
                  color="#888"
                  name="chevron_right"
                  size="18px"
                  @click="moveRight(index)"
                />
              </div>
            </div>
          </th>
        </tr>
      </thead>

      <tbody>
        <tr
          v-for="item in sortedRows"
          :key="item.property_id"
        >
          <td
            v-for="column in columns"
            :key="column.key"
          >
            <template
              v-if="
                column.key ===
                'final_payout_amount'
              "
            >
              {{
                formatCurrency(
                  item[column.key]
                )
              }}
            </template>

            <template
              v-else-if="
                column.key ===
                'reservations_count'
              "
            >
              {{
                formatInteger(
                  resolveReservationsCount(item)
                )
              }}
            </template>

            <template v-else>
              {{ item[column.key] }}
            </template>
          </td>
        </tr>

        <tr class="payout-total-row">
          <td>Total</td>

          <td>
            {{
              formatInteger(
                totalReservations
              )
            }}
          </td>

          <td>
            {{
              formatCurrency(totalValue)
            }}
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

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

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

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

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

const columns = ref([
  {
    key: "property_label",
    label: "Unidade",
    direction: null,
  },

  {
    key: "reservations_count",
    label: "Reservas",
    direction: null,
  },

  {
    key: "final_payout_amount",
    label: "Valor",
    direction: null,
  },
]);

const toggleSort = (
  column
) => {
  column.direction =
    column.direction === "asc"
      ? "desc"
      : "asc";
};

const moveLeft = (index) => {
  const lastIndex =
    columns.value.length - 1;

  const targetIndex =
    index === 0
      ? lastIndex
      : index - 1;

  [
    columns.value[targetIndex],
    columns.value[index],
  ] = [
    columns.value[index],
    columns.value[targetIndex],
  ];
};

const moveRight = (index) => {
  const lastIndex =
    columns.value.length - 1;

  const targetIndex =
    index === lastIndex
      ? 0
      : index + 1;

  [
    columns.value[targetIndex],
    columns.value[index],
  ] = [
    columns.value[index],
    columns.value[targetIndex],
  ];
};

const sortedRows = computed(() => {
  const activeSorts =
    columns.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 =
          sort.key === "reservations_count"
            ? resolveReservationsCount(a)
            : a[sort.key];

        const valueB =
          sort.key === "reservations_count"
            ? resolveReservationsCount(b)
            : b[sort.key];

        if (valueA > valueB) {
          return direction;
        }

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

      return 0;
    }
  );
});

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

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");
};
</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-total-row td {
  font-size: 17px !important;
  font-weight: 700;
  border-bottom: 0;
  color: #4d4e4e;
  text-align: center;
}

.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;
}

.move-icon {
  opacity: 0.7;
  transition: 0.2s ease;
}

.move-icon:hover,
.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>
