<!-- eslint-disable @intlify/vue-i18n/no-raw-text -->
<template>
  <div class="q-mb-md q-mx-md">
    <div class="items-center justify-between q-mb-sm row">
      <div class="font16 fontbold gradient-diarista section-title">
        {{ $t("provider.dashboard.solicitations.title") }}
      </div>

      <q-btn
        color="grey-6"
        flat
        icon="mdi-chevron-right-outlined"
        no-caps
        size="sm"
        :label="$t('common.see_all')"
        >
  <q-badge
    v-if="groupedSolicitations.length"
    color="negative"
    floating
    rounded
    :label="groupedSolicitations.length"
  />
  </q-btn>
    </div>

    <div
      class="scroll-wrapper"
      :class="{ 'scroll-wrapper--single': visibleSolicitations.length === 1 }"
    >
      <div
        class="no-wrap row scroll-track"
        :class="{
          'q-gutter-x-md': visibleSolicitations.length > 1,
          'scroll-track--single': visibleSolicitations.length === 1,
        }"
      >
        <q-card
          v-for="item in visibleSolicitations"
          :key="item.id"
          :class="{
            'solicitation-card--single': visibleSolicitations.length === 1,
            'solicitation-card--multiple': visibleSolicitations.length > 1,
          }"
          :flat="false"
          class="bg-surface q-ma-md shadow-card solicitation-card"
        >
          <q-card-section class="q-pa-sm solicitation-card-section">
            <div class="items-center no-wrap q-gutter-x-sm row text-text">
              <q-avatar size="48px">
                <img
                  v-if="item.customer_photo"
                  :src="item.customer_photo"
                  style="object-fit: cover"
                />

                <span
                  v-else
                  class="flex flex-center full-height full-width"
                  style="border-radius: 50%"
                  :style="avatarColors[item.id % avatarColors.length]"
                >
                  {{
                    getFirstName(item.client_name)
                      ?.slice(0, 2)
                      .toUpperCase() ?? "??"
                  }}
                </span>
              </q-avatar>

              <div class="column flex-1 solicitation-info">
                <div class="items-center no-wrap q-gutter-x-xs row">
                  <span class="ellipsis font12 fontmedium text-name">
                    {{ getFirstName(item.client_name) || "—" }}
                  </span>

                  <div class="items-center no-wrap row">
                    <q-icon
                      color="warning"
                      name="mdi-star"
                      size="14px"
                    />

                    <span class="font11 no-wrap text-text">
                      {{ item.average_rating }}
                    </span>
                  </div>
                </div>

                <div class="schedule-list">
                  <div
                    v-if="item.package_items.length > 1"
                    class="font8 package-summary"
                  >
                    {{ $t("provider.dashboard.solicitations.package_count", { count: item.package_items.length }) }}
                  </div>

                  <div
                    v-for="scheduleItem in item.package_items"
                    :key="scheduleItem.id"
                    class="solicitation-date-time"
                  >
                    <div class="items-center no-wrap row">
                      <span class="font9 fontbold text-schedule-date-bold">
                        {{ formatWeekday(scheduleItem.date) }}
                      </span>

                      <span class="font9 text-schedule-date-regular">
                        {{ ", " + formatDayMonth(scheduleItem.date) }}
                      </span>
                    </div>

                    <div class="font9 text-schedule-date-regular">
                      {{ $t("common.from") }}

                      <span class="fontbold text-schedule-date-bold">
                        {{ scheduleItem.start_time?.slice(0, 5) }}
                      </span>

                      {{ $t("common.to") }}

                      <span class="fontbold text-schedule-date-bold">
                        {{ scheduleItem.end_time?.slice(0, 5) }}
                      </span>
                    </div>
                  </div>
                </div>

                <div class="font9 text-time-since">
                  {{ formatTimeSinceRequest(item.time_since_request) }}
                </div>
              </div>

              <div class="column items-end no-wrap solicitation-meta text-text">
                <div class="font14 fontbold no-wrap text-price">
                  {{ formatCurrency(packageTotal(item)) }}
                </div>

                <div class="font10 fontmedium text-type">
                  {{ periodTypeLabel(item) }}
                </div>

                <div class="ellipsis font10 text-region">
                  {{ item.address?.district || "N/A" }}
                </div>

                <div class="font10 no-wrap text-distance">
                  {{ item.distance_km ?? 0 }} {{ $t("common.km") }}
                </div>
              </div>
            </div>

            <div class="items-center q-gutter-x-sm q-mt-sm row solicitation-actions">
              <q-btn
                class="col-auto solicitation-details-btn"
                color="primary"
                flat
                no-caps
                padding="4px 8px"
                size="xs"
                unelevated
                :label="$t('common.details')"
                @click="emit('view-details', item)"
              />

              <q-space />

              <q-btn
                class="bg-grey-3 btn-action col-auto text-grey-8"
                no-caps
                rounded
                size="sm"
                unelevated
                :label="$t('common.refuse')"
                @click="emit('reject', item)"
              />

              <q-btn
                class="btn-action btn-accept"
                no-caps
                rounded
                size="sm"
                unelevated
                :label="$t('common.accept')"
                @click="emit('accept', item)"
              />
            </div>
          </q-card-section>
        </q-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { avatarColors, formatCurrency, getFirstName } from "src/helpers/utils";
import { computed } from "vue";
import { labelsPeriodTypes } from "src/helpers/labelsPeriodTypes.js";
import { useI18n } from "vue-i18n";

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

const emit = defineEmits(["accept", "reject", "view-details"]);

const { t } = useI18n();

const groupedSolicitations = computed(() => {
  const groups = new Map();

  props.data.forEach((item) => {
    const key = item.service_package_id
      ? `package:${item.service_package_id}`
      : `schedule:${item.id}`;

    const group = groups.get(key);

    if (group) {
      group.package_items.push(item);
    } else {
      groups.set(key, { ...item, package_items: [item] });
    }
  });

  return [...groups.values()];
});

const visibleSolicitations = computed(() =>
  groupedSolicitations.value.slice(0, 3)
);

const periodTypeLabel = (item) => {
  const label = labelsPeriodTypes.find(
    (periodType) => periodType.value == item.period_type,
  )?.label;

  return label ? t(label) : "";
};

const packageTotal = (item) =>
  item.package_items.reduce(
    (total, packageItem) => total + (Number(packageItem.total_amount) || 0),
    0,
  );

//

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

  const matches = String(iso).match(/^(\d{4})-(\d{2})-(\d{2})/);

  return matches
    ? new Date(+matches[1], +matches[2] - 1, +matches[3])
    : null;
};

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

  if (!date) return "";

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

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

  if (!date) return "";

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

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

const formatTimeSinceRequest = (value) => {
  if (!value) return "";

  const normalizedValue = String(value).trim().replace(/\s+/g, " ");

  if (/^just now$/i.test(normalizedValue)) {
    return t("provider.dashboard.solicitations.time_ago.just_now");
  }

  const match = normalizedValue.match(
    /^(-?\d+|an?|one)\s+(second|minute|hour|day|week|month|year)s?(?:\s+ago)?$/i,
  );

  if (!match) return normalizedValue;

  const count = /^-?\d+$/.test(match[1]) ? Math.abs(Number(match[1])) : 1;

  return t(
    `provider.dashboard.solicitations.time_ago.${match[2].toLowerCase()}`,
    count,
  );
};
</script>

<style lang="scss" scoped>
.scroll-wrapper {
  overflow-x: auto;
  padding: 0 0 8px 8px;

  &::-webkit-scrollbar {
    display: none;
  }
}

.scroll-wrapper--single {
  overflow-x: visible;
  padding: 0 0 8px 0;
}

.scroll-track {
  align-items: flex-start;
}

.solicitation-card {
  border-radius: 12px;
  overflow: visible;
}

.solicitation-card--single {
  flex: 0 0 100%;
  margin: 0 !important;
  width: 100%;
}

.solicitation-card--multiple {
  flex: 0 0 82vw;
  margin-left: 8px !important;
  margin-right: 8px !important;
  max-width: 82vw;
  min-width: 82vw;
  width: 82vw;
}

.scroll-track--single {
  width: 100%;
}

.btn-action {
  min-width: 90px;
}

.flex-1 {
  flex: 1;
  min-width: 0;
}

.solicitation-info {
  gap: 2px;
  min-width: 0;
}

.solicitation-meta {
  gap: 2px;
  max-width: 42%;
  text-align: right;
}

.schedule-list {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.solicitation-date-time {
  line-height: 1.35;
  min-width: 0;
}

.font11 {
  font-size: 11px;
}

.text-name,
.text-price,
.text-schedule-date-bold {
  color: #3a3a4a;
}

.text-distance,
.text-region,
.text-schedule-date-regular,
.text-type {
  color: #666;
}

.text-time-since {
  color: #9a9aa5;
}

.solicitation-details-btn {
  margin-top: 0;
}

.package-summary {
  color: #666;
  line-height: 1.35;
}
.btn-accept {
  position: relative;
  overflow: hidden;
  color: #fff !important;

  background: linear-gradient(
    90deg,
    #3b5cff,
    #7a4dff,
    #d94cff
  );
}

.btn-accept::after {
  content: "";
  position: absolute;
  inset: 0;
  left: -40%;

  width: 40%;
  background: linear-gradient(
    90deg,
    transparent,
    rgba(255,255,255,.35),
    transparent
  );

  transform: skewX(-20deg);
  animation: shine 2s linear infinite;
}

@keyframes shine {
  from {
    left: -40%;
  }

  to {
    left: 140%;
  }
}
</style>
