<!-- eslint-disable @intlify/vue-i18n/no-raw-text -->
<template>
  <q-dialog
    ref="dialogRef"
    maximized
    persistent
    transition-hide="slide-right"
    transition-show="slide-left"
  >
    <div class="bg-page full-height column no-shadow">
      <div
        class="row items-center q-px-md q-pt-md q-pb-sm bg-white shadow-profile bg-surface"
      >
        <q-btn
          v-close-popup
          class="header-back-btn"
          color="primary"
          dense
          flat
          icon="mdi-chevron-left"
          round
        />

        <q-space />

        <span
          class="text-subtitle1 text-primary font16 fontbold gradient-diarista"
        >
          {{ $t("profile.favorites.title") }}
        </span>

        <q-space />

        <div style="width: 32px" />
      </div>

      <div
        v-if="loading"
        class="col flex flex-center"
      >
        <q-spinner
          color="primary"
          size="3em"
        />
      </div>

      <div
        v-else-if="favorites.length === 0"
        class="col column items-center justify-center q-px-xl q-pb-xl"
      >
        <q-img
          class="q-mb-lg"
          fit="contain"
          style="width: 220px; height: 220px"
          :src="diarinho"
        />

        <p class="text-text text-center q-mb-xs">
          {{ $t("profile.favorites.empty_message") }}
        </p>

        <p class="text-primary text-center q-mb-xl">
          {{ $t("profile.favorites.empty_cta") }}
        </p>

        <q-btn
          v-close-popup
          class="full-width q-py-sm"
          color="primary"
          no-caps
          padding="10px 16px"
          rounded
          unelevated
          :label="$t('profile.favorites.search_btn')"
          @click="goToSearch"
        />
      </div>

      <div
        v-else
        class="col overflow-auto q-pb-xl"
      >
        <div class="q-mx-md q-mt-md q-pa-md">
          <p class="gradient-diarista text-center q-mb-md font12 fontbold">
            {{ $t("profile.favorites.indicate_title") }}
          </p>

          <div class="row items-center">
            <div class="col column items-center">
              <q-avatar
                class="text-h5 q-mb-sm shadow-1"
                size="72px"
                :style="avatarStyle(highlightedFavorite)"
              >
                <img
                  v-if="getProfileMediaUrl(highlightedFavorite)"
                  class="profile-image"
                  :src="getProfileMediaUrl(highlightedFavorite)"
                />

                <span v-else>
                  {{
                    highlightedFavorite?.provider_name
                      ?.charAt(0)
                      ?.toUpperCase() ?? "?"
                  }}
                </span>
              </q-avatar>

              <span class="font14 fontbold text-dark">
                {{ highlightedFavorite?.provider_name ?? "—" }}
              </span>

              <span
                v-if="getProviderGenderLabel(highlightedFavorite, t)"
                class="font10 fontmedium text-grey-6"
              >
                {{ getProviderGenderLabel(highlightedFavorite, t) }}
              </span>

              <span class="font12 fontmedium text-grey-6">
                {{ highlightedFavorite?.city_name ?? "—" }}
              </span>

              <div class="row items-center q-gutter-sm q-mt-sm">
                <q-btn
                  color="primary"
                  dense
                  flat
                  icon="mdi-chevron-left"
                  round
                  :disable="favorites.length <= 1"
                  @click="prevHighlight"
                />

                <q-btn
                  color="primary"
                  no-caps
                  padding="4px 20px"
                  rounded
                  size="sm"
                  unelevated
                  :label="$t('profile.favorites.indicate_btn')"
                  @click="openIndicateDialog(highlightedFavorite)"
                />

                <q-btn
                  color="primary"
                  dense
                  flat
                  icon="mdi-chevron-right"
                  round
                  :disable="favorites.length <= 1"
                  @click="nextHighlight"
                />
              </div>
            </div>
          </div>
        </div>

        <div class="q-mx-md q-mt-lg">
          <div class="row items-center justify-between q-mb-md">
            <span class="font16 fontbold gradient-diarista">
              {{ $t("profile.favorites.providers_title") }}
            </span>

            <div class="row items-center">
              <q-icon
                :class="selectedHours === '2h' ? '' : 'cursor-pointer'"
                :color="selectedHours === '2h' ? 'grey-4' : 'grey-6'"
                name="mdi-chevron-left"
                size="20px"
                @click="nextSelectedHours"
              />

              <span
                class="font12 fontbold text-grey-6 q-px-xs"
                style="user-select: none"
              >
                {{ $t("profile.favorites.until") }} {{ selectedHours }}
              </span>

              <q-icon
                :class="selectedHours === '8h' ? '' : 'cursor-pointer'"
                :color="selectedHours === '8h' ? 'grey-4' : 'grey-6'"
                name="mdi-chevron-right"
                size="20px"
                @click="prevSelectedHours"
              />
            </div>
          </div>

          <div
            v-for="(item, index) in favorites"
            :key="item.id"
            :class="{ 'item-separator': index < favorites.length - 1 }"
            class="favorite-item row items-center no-wrap q-py-md"
          >
            <div
              class="relative-position q-mr-md"
              style="margin-right: 16px"
            >
              <q-avatar
                class="shadow-1"
                size="60px"
                :style="avatarStyle(item)"
              >
                <img
                  v-if="getProfileMediaUrl(item)"
                  class="profile-image"
                  :src="getProfileMediaUrl(item)"
                />

                <span v-else>
                  {{ item.provider_name?.charAt(0)?.toUpperCase() ?? "?" }}
                </span>
              </q-avatar>

              <q-icon
                class="absolute cursor-pointer"
                name="mdi-heart"
                size="26px"
                style="bottom: -4px; right: -4px; color: #f518e3; filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.2))"
                @click.stop="confirmRemove(item)"
              />
            </div>

            <div
              class="col column justify-between"
              style="min-height: 60px"
            >
              <div class="row items-start justify-between">
                <div class="column">
                  <span
                    class="provider-name font12 fontmedium"
                    style="color: #4a4a4a; line-height: 1.1"
                  >
                    {{ item.provider_name ?? "—" }}
                  </span>

                  <span
                    v-if="getProviderGenderLabel(item, t)"
                    class="font9 fontmedium text-grey-7 q-pt-xs"
                  >
                    {{ getProviderGenderLabel(item, t) }}
                  </span>

                  <span
                    class="provider-city font9 fontbold text-grey-7 q-pt-xs"
                  >
                    {{ item.city_name ?? "—" }}
                  </span>
                </div>

                <span
                  class="provider-price font12 fontregular text-grey-7"
                  style="line-height: 1.1"
                >
                  R${{
                    getPriceByHours(item)
                      ? formatPrice(getPriceByHours(item))
                      : "—"
                  }}
                </span>
              </div>

              <div class="row items-end justify-between q-mt-xs">
                <div
                  class="row items-center text-grey-5"
                  style="margin-bottom: 2px"
                >
                  <q-icon
                    color="warning"
                    name="mdi-star"
                    size="12px"
                  />

                  <span
                    class="q-ml-xs font9 fontregular"
                    style="color: #666"
                  >
                    {{ item.average_rating ?? "—" }}
                  </span>

                  <span
                    class="q-ml-xs font9 fontregular"
                    style="margin-right: 2px"
                  >
                    ({{ item.total_services ?? 0 }})
                  </span>

                  <q-icon
                    class="q-mx-xs"
                    color="grey-4"
                    name="mdi-circle-small"
                    size="12px"
                  />

                  <q-icon
                    name="mdi-broom"
                    size="12px"
                    style="color: #f518e3; transform: scaleX(-1)"
                  />

                  <span
                    class="q-ml-xs font9 fontregular"
                    style="color: #666"
                  >
                    {{ item.total_services ?? "0" }}
                  </span>

                  <q-icon
                    class="q-mx-xs"
                    color="grey-4"
                    name="mdi-circle-small"
                    size="16px"
                  />

                  <span class="font9 fontregular"> 0Km </span>
                </div>

                <q-btn
                  class=""
                  no-caps
                  padding="4px 20px"
                  rounded
                  size="sm"
                  style="background: #a63df7; color: white"
                  unelevated
                  :label="$t('profile.favorites.schedule_btn')"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </q-dialog>
</template>

<script setup>
import diarinho from "src/assets/diarinho_perfil_cliente_favoritos.svg";

import { avatarColorsWithPurple as avatarColors } from "src/helpers/avatarColors";

import { computed, onMounted, ref } from "vue";

import {
  deleteClientFavoriteProvider,
  getClientFavoriteProviders,
} from "src/api/clientFavoriteProvider";

import { getProfileMediaUrl } from "src/helpers/profileMedia";
import { getProviderGenderLabel } from "src/helpers/provider";
import { useDialogPluginComponent, useQuasar } from "quasar";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { userStore } from "src/stores/user";

import ProfileFavoriteRemoveDialog from "./ProfileFavoriteRemoveDialog.vue";

defineEmits([...useDialogPluginComponent.emits]);

const { dialogRef } = useDialogPluginComponent();

const { t } = useI18n();

const $q = useQuasar();
const router = useRouter();
const store = userStore();

const favorites = ref([]);
const highlightIndex = ref(0);
const loading = ref(false);
const selectedHours = ref("8h");

const highlightedFavorite = computed(
  () => favorites.value[highlightIndex.value] ?? null,
);

const hoursOptions = ["8h", "6h", "4h", "2h"];

const avatarStyle = (item) => {
  const index = (item?.id ?? 0) % avatarColors.length;

  return avatarColors[index];
};

const confirmRemove = (item) => {
  $q.dialog({
    component: ProfileFavoriteRemoveDialog,
  }).onOk(async () => {
    try {
      await deleteClientFavoriteProvider(item.id);

      favorites.value = favorites.value.filter(
        (favorite) => favorite.id !== item.id,
      );

      if (highlightIndex.value >= favorites.value.length) {
        highlightIndex.value = Math.max(0, favorites.value.length - 1);
      }
    } catch (error) {
      console.error("Erro ao remover favorito:", error);
    }
  });
};

const formatPrice = (value) => {
  return Number(value).toLocaleString("pt-BR", {
    maximumFractionDigits: 2,
    minimumFractionDigits: 2,
  });
};

const getPriceByHours = (item) => {
  const priceKey = `daily_price_${selectedHours.value}`;

  return item[priceKey] ?? item.daily_price_8h ?? 0;
};

const goToSearch = () => {
  router.push({
    name: "SearchPage",
  });
};

const nextHighlight = () => {
  highlightIndex.value = (highlightIndex.value + 1) % favorites.value.length;
};

const nextSelectedHours = () => {
  const currentIndex = hoursOptions.indexOf(selectedHours.value);

  if (currentIndex < hoursOptions.length - 1) {
    selectedHours.value = hoursOptions[currentIndex + 1];
  }
};

const openIndicateDialog = (item) => {
  const message = t("profile.favorites.indicate_whatsapp_message", {
    city: item?.city_name ?? "",
    name: item?.provider_name ?? "",
  });

  console.log("[Indicar diarista - WhatsApp]", message);

  $q.notify({
    message: t("profile.favorites.indicate_coming_soon"),
    type: "info",
  });
};

const prevHighlight = () => {
  highlightIndex.value =
    highlightIndex.value === 0
      ? favorites.value.length - 1
      : highlightIndex.value - 1;
};

const prevSelectedHours = () => {
  const currentIndex = hoursOptions.indexOf(selectedHours.value);

  if (currentIndex > 0) {
    selectedHours.value = hoursOptions[currentIndex - 1];
  }
};

onMounted(async () => {
  loading.value = true;

  try {
    const clientId = store.user?.client_id;

    if (clientId) {
      favorites.value = await getClientFavoriteProviders(clientId);
    }
  } catch (error) {
    console.error("Erro ao carregar favoritos:", error);
  } finally {
    loading.value = false;
  }
});
</script>

<style scoped lang="scss">
.heart-badge {
  position: absolute;
  bottom: -2px;
  right: -2px;
  background: white;
  border-radius: 50%;
  padding: 1px;
}

.favorite-item {
  background: transparent;
}

.item-separator {
  border-bottom: 1px solid rgba(0, 0, 0, 0.07);
}

.provider-name {
  color: #2c3e50;
  line-height: 1.3;
}

.provider-city {
  color: #888;
  line-height: 1.2;
}

.provider-metrics {
  gap: 3px;
}

.metric-value {
  color: #3a3a4a;
  line-height: 1;
}

.metric-meta {
  color: #999;
  line-height: 1;
}

.metric-dot {
  color: #ccc;
  line-height: 1;
  padding: 0 1px;
}

.provider-price {
  color: #2c3e50;
}

.profile-image {
  height: 100%;
  object-fit: cover;
  width: 100%;
}

.shadow-profile {
  box-shadow: 0px 1px 8px rgba(0, 0, 0, 0.1);
}
</style>
