<template>
  <q-page class="opportunities-page">
    <div class="page-header">
      <q-btn
        class="back-btn"
        dense
        flat
        icon="chevron_left"
        round
        @click="router.back()"
      />

      <div class="gradient-diarista font16 fontbold">
        {{ $t("provider.dashboard.opportunities.title") }}
      </div>
    </div>

    <q-card
      class="info-banner"
      flat
    >
      <q-icon
        name="mdi-auto-fix"
        size="30px"
      />

      <div class="banner-text font10 fontmedium">
        {{ $t("provider.dashboard.opportunities.banner_text") }}
      </div>
    </q-card>

    <div
      v-if="loading"
      class="flex flex-center q-pa-lg"
    >
      <q-spinner-dots
        color="secondary"
        size="32px"
      />
    </div>

    <div
      v-else-if="!opportunities.length"
      class="text-center q-pa-md font14 medium text-text"
    >
      {{ $t("provider.dashboard.opportunities.empty") }}
    </div>

    <div
      v-else
      class="opportunity-list"
    >
      <q-card
        v-for="item in opportunities"
        :key="item.id"
        :flat="false"
        class="opportunity-card shadow-card bg-surface"
      >
        <div class="row">
          <div>
            <img
              v-if="item.customer_photo"
              alt="Avatar"
              class="client-avatar"
              :src="item.customer_photo"
            />

            <div
              v-else
              class="client-avatar client-avatar--initials font14 fontbold"
              :style="avatarColors[item.id % avatarColors.length]"
            >
              {{ getFirstName(item.client_name)?.slice(0, 2).toUpperCase() ?? "??" }}
            </div>
          </div>

          <div class="center-content q-pl-md">
            <div class="client-name-row">
              <span class="text-text font12 fontmedium">
                {{ getFirstName(item.client_name) || "—" }}
              </span>

              <span class="rating font9 fontregular">
                <q-icon
                  name="star"
                  size="11px"
                />

                {{ item.client?.average_rating }}
              </span>
            </div>

            <div class="service-date text-text font9">
              <span class="fontbold">
                {{ formatWeekday(item.date) }}
              </span>

              <span>
                {{ ", " + formatDayMonth(item.date) }}
              </span>
            </div>

            <div class="service-hour text-text font9">
              {{ $t("common.from") }}

              <span class="fontbold">
                {{ formatHour(item.start_time) }}
                {{ $t("common.to") }}
                {{ formatHour(item.end_time) }}
              </span>
            </div>
          </div>

          <div class="right-content">
            <div class="price font14 fontbold">
              {{ filterCurrency(chooseprice(item.period_type, user.user.provider.daily_price_8h)) }}
            </div>

            <div class="font9 fontmedium text-text">
              {{ t(labelsPeriodTypes.find((label) => label.value == item.period_type)?.label) }}
            </div>

            <div class="service-address font10 fontbold">
              {{ item.address?.district }}
            </div>

            <div class="distance font9">
              {{ $t("provider.dashboard.opportunities.distance_km", { distance: item.distance_km ?? 0 }) }}
            </div>
          </div>
        </div>

        <div class="row">
          <div class="q-my-auto text-primary font9 fontbold">
            {{ item.custom_schedule?.service_type.description }}
          </div>

          <q-space />

          <q-btn
            class="font11 fontsemibold"
            color="secondary"
            no-caps
            padding="4px 12px"
            rounded
            size="xs"
            unelevated
            :label="$t('provider.dashboard.opportunities.details')"
            @click="goToOpportunityDetails(item)"
          />
        </div>
      </q-card>
    </div>
  </q-page>
</template>

<script setup>
import {
  avatarColors,
  chooseprice,
  filterCurrency,
  getFirstName,
} from "src/helpers/utils";

import { getProviderOpportunities } from "src/api/opportunities";
import { labelsPeriodTypes } from "src/helpers/labelsPeriodTypes.js";
import { onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useQuasar } from "quasar";
import { useRouter } from "vue-router";
import { userStore } from "src/stores/user";

import OpportunityDetailsDialog from "./components/OpportunityDetailsDialog.vue";

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

const { t } = useI18n();

const opportunities = ref([]);
const loading = ref(false);



const goToOpportunityDetails = (item) => {
  const id = item.custom_schedule?.id || item.id;

  $q.dialog({
    component: OpportunityDetailsDialog,
    componentProps: {
      opportunityId: id,
      distanceKm: item.distance_km ?? null,
    },
  });
};

const loadOpportunities = async () => {
  loading.value = true;

  try {
    const response = await getProviderOpportunities(user.user.provider.id);

    opportunities.value = response || [];
  } catch (error) {
    console.error("Erro ao buscar oportunidades:", error);

    opportunities.value = [];
  } finally {
    loading.value = false;
  }
};

//

const parseLocalDate = (dateString) => {
  if (!dateString) return null;

  const date = String(dateString);
  const isoDate = date.match(/^(\d{4})-(\d{2})-(\d{2})/);

  if (!isoDate) return null;

  return new Date(+isoDate[1], +isoDate[2] - 1, +isoDate[3]);
};

const formatDayMonth = (dateString) => {
  const date = parseLocalDate(dateString);

  if (!date) return "";

  return date.toLocaleDateString("pt-BR", {
    day: "2-digit",
    month: "2-digit",
  });
};

const formatHour = (time) => {
  if (!time) return "";

  return time.slice(0, 5);
};

const formatWeekday = (dateString) => {
  const date = parseLocalDate(dateString);

  if (!date) return "";

  const weekday = date.toLocaleDateString("pt-BR", {
    weekday: "long",
  });

  return weekday.charAt(0).toUpperCase() + weekday.slice(1);
};

//

onMounted(loadOpportunities);
</script>

<style scoped lang="scss">
.opportunities-page {
  min-height: 100vh;
  padding: 0;
  background: #f7f7fb;
}

.page-header {
  position: relative;
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 14px 16px;
  margin-bottom: 16px;
  background: #fff;
  border-radius: 0 0 16px 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.back-btn {
  position: absolute;
  left: 8px;
  color: #7c5cff;
}

.info-banner {
  display: flex;
  gap: 12px;
  padding: 14px;
  margin: 16px;
  color: white;
  background: #a78bfa;
  border-radius: 14px;
}

.banner-text {
  line-height: 1.4;
}

.opportunity-list {
  display: flex;
  flex-direction: column;
  gap: 14px;
  padding: 0 16px 16px;
}

.opportunity-card {
  display: flex;
  flex-direction: column;
  gap: 14px;
  padding: 14px;
  border-radius: 18px;
}

.client-avatar {
  width: 54px;
  height: 54px;
  object-fit: cover;
  border-radius: 50%;
}

.client-avatar--initials {
  display: flex;
  align-items: center;
  justify-content: center;
}

.center-content {
  display: flex;
  flex: 1;
  flex-direction: column;
}

.client-name-row {
  display: flex;
  gap: 4px;
  align-items: center;
}

.rating {
  display: flex;
  gap: 2px;
  align-items: center;
  color: #ffb800;
}

.service-date,
.service-hour {
  line-height: 1.35;
}

.right-content {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.price {
  color: #2d2d2d;
}

.service-address {
  max-width: 120px;
  margin-top: 6px;
  line-height: 1.3;
  color: #666;
  text-align: right;
}

.distance {
  margin-top: 4px;
  color: #999;
}
</style>