<template>
  <q-page class="bg-page q-pb-xl">
    <div class="calendar-header row items-center bg-white">
      <q-space />

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

      <q-space />
    </div>

    <template v-if="loading">
      <div
        class="row items-center justify-center full-width"
        style="height: 60vh"
      >
        <q-spinner-dots color="primary" />
      </div>
    </template>

    <template v-else>
      <div class="q-mt-md q-mx-md">
        <div class="section-title font16 fontbold gradient-diarista q-mb-sm">
          {{ $t('provider.dashboard.agenda.upcoming_title') }}
        </div>

        <template v-if="upcomingSchedules.length > 0">
          <q-card
            v-for="item in upcomingSchedules"
            :key="item.id"
            :flat="false"
            class="calendar-card bg-surface shadow-card q-mb-sm"
          >
            <q-card-section class="q-pa-sm">
              <div class="row no-wrap items-start q-gutter-x-sm">
                <q-avatar size="44px">
                  <img
                    v-if="item.customer_photo"
                    :src="item.customer_photo"
                    style="object-fit:cover"
                  />

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

                <div class="col column text-text">
                  <span class="font12 fontmedium ellipsis">
                    {{ getFirstName(item.client_name) }}
                  </span>

                  <div class="row items-center no-wrap">
                    <span class="font9 fontbold">
                      {{ formatWeekday(item.date) }}
                    </span>

                    <span class="font9 fontmedium">
                      {{ ', ' + formatDayMonth(item.date) }}
                    </span>
                  </div>

                  <span class="font9 fontmedium">
                    {{ $t('common.from') }}

                    <span class="font9 fontbold">
                      {{ item.start_time?.slice(0, 5) }}
                    </span>

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

                    <span class="font9 fontbold">
                      {{ item.end_time?.slice(0, 5) }}
                    </span>
                  </span>
                </div>

                <div class="col-auto column items-end">
                  <q-chip
                    class="status-chip font9"
                    dense
                    square
                    :color="statusBgColor(item.status)"
                    :label="statusLabel(item.status)"
                    :text-color="statusTextColor(item.status)"
                  />

                  <span class="text-price font10 fontbold">
                    {{ formatCurrency(item.total_amount) }}
                  </span>

                  <span class="text-period font9 fontmedium">
                    {{ periodLabel(item.period_type) }}
                  </span>
                </div>
              </div>

              <div class="row items-center no-wrap q-mt-xs">
                <span class="type-label text-primary font10 fontmedium">
                  {{ item.schedule_type === 'custom' ? $t('provider.dashboard.agenda.type_custom') : $t('provider.dashboard.agenda.type_default') }}
                </span>

                <q-space />

                <q-btn
                  color="primary"
                  padding="4px 12px"
                  rounded
                  size="xs"
                  unelevated
                  :label="$t('provider.dashboard.agenda.btn_view_details')"
                  @click="openDetailsDialog(item)"
                />
              </div>
            </q-card-section>
          </q-card>
        </template>

        <div v-else class="font16 fontbold text-center text-grey-5 q-py-lg">
          {{ $t('provider.dashboard.agenda.empty_upcoming') }}
        </div>
      </div>

      <div class="q-mt-lg q-mx-md">
        <div class="section-title font16 fontbold gradient-diarista q-mb-sm">
          {{ $t('provider.dashboard.agenda.completed_title') }}
        </div>

        <template v-if="completedSchedules.length > 0">
          <q-card
            v-for="item in completedSchedules"
            :key="item.id"
            :flat="false"
            class="calendar-card bg-surface shadow-card q-mb-sm"
          >
            <q-card-section class="q-pa-sm">
              <div class="row no-wrap items-start q-gutter-x-sm">
                <q-avatar size="44px">
                  <img
                    v-if="item.customer_photo"
                    :src="item.customer_photo"
                    style="object-fit:cover"
                  />

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

                <div class="col column text-text">
                  <span class="font12 fontmedium ellipsis">
                    {{ getFirstName(item.client_name) || '—' }}
                  </span>

                  <div class="row items-center no-wrap">
                    <span class="font9 fontbold">
                      {{ formatWeekday(item.date) }}
                    </span>

                    <span class="font9 fontmedium">
                      {{ ', ' + formatDayMonth(item.date) }}
                    </span>
                  </div>

                  <span class="font9 fontmedium">
                    {{ $t('common.from') }}

                    <span class="font9 fontbold">
                      {{ item.start_time?.slice(0, 5) }}
                    </span>

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

                    <span class="font9 fontbold">
                      {{ item.end_time?.slice(0, 5) }}
                    </span>
                  </span>
                </div>

                <div class="col-auto column items-end">
                  <q-chip
                    class="status-chip font9"
                    dense
                    square
                    :color="statusBgColor(item.status)"
                    :label="statusLabel(item.status)"
                    :text-color="statusTextColor(item.status)"
                  />

                  <span class="text-price font10 fontbold">
                    {{ formatCurrency(item.total_amount) }}
                  </span>

                  <span class="text-period font9 fontmedium">
                    {{ periodLabel(item.period_type) }}
                  </span>
                </div>
              </div>

              <div class="row items-center no-wrap q-mt-xs">
                <span class="type-label text-primary font10 fontmedium">
                  {{ item.schedule_type === 'custom' ? $t('provider.dashboard.agenda.type_custom') : $t('provider.dashboard.agenda.type_default') }}
                </span>

                <q-space />

                <q-rating
                  :model-value="item.provider_reviewed ? item.provider_stars : 0"
                  :max="5"
                  class="q-mr-sm"
                  color="amber"
                  icon="mdi-star-outline"
                  icon-selected="mdi-star"
                  readonly
                  size="14px"
                />

                <q-btn
                  v-if="!item.provider_reviewed"
                  class="btn-rate"
                  color="secondary"
                  no-caps
                  padding="4px 12px"
                  rounded
                  size="xs"
                  unelevated
                  :label="$t('provider.dashboard.agenda.btn_rate')"
                  @click="openRatingDialog(item)"
                />
              </div>
            </q-card-section>
          </q-card>
        </template>

        <div v-else class="text-center text-grey-5 q-py-lg">
          {{ $t('provider.dashboard.agenda.empty_completed') }}
        </div>
      </div>
    </template>
  </q-page>
</template>


<script setup>
import { formatCurrency, getFirstName } from 'src/helpers/utils';
import { getProviderCalendar } from 'src/api/providerCalendar';
import { labelsPeriodTypes } from 'src/helpers/labelsPeriodTypes.js';
import { onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useQuasar } from 'quasar';

import NextSchedulesDetailsDialog from 'src/components/dashboard/NextSchedulesDetailsDialog.vue';
import ScheduleRatingDialog from 'src/components/dashboard/ScheduleRatingDialog.vue';

const $q = useQuasar();
const { t } = useI18n();

const avatarColors = [
  { background: '#ffd5df', color: '#932e57' },
  { background: '#d7e8ff', color: '#2158a8' },
  { background: '#dfd',    color: '#2a7a3b' },
  { background: '#ffe5cc', color: '#8a4500' },
];

const loading = ref(true);
const upcomingSchedules = ref([]);
const completedSchedules = ref([]);

//

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

  const s = String(dateStr);

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

  if (iso) return new Date(+iso[1], +iso[2] - 1, +iso[3]);

  const dmy = s.match(/^(\d{2})\/(\d{2})\/(\d{4})/);

  if (dmy) return new Date(+dmy[3], +dmy[2] - 1, +dmy[1]);

  return null;
};

const formatDayMonth = (dateStr) => {
  const d = parseLocalDate(dateStr);

  if (!d) return '';

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

const formatWeekday = (dateStr) => {
  const d = parseLocalDate(dateStr);

  if (!d) return '';

  const w = d.toLocaleDateString('pt-BR', { weekday: 'long' });

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

//

const periodLabel = (periodType) => {
  const found = labelsPeriodTypes.find(l => l.value == periodType);
  return found ? t(found.label) : '';
};

const statusBgColor = (status) => {
  const map = {
    pending: 'warning-bg',
    accepted: 'success-bg',
    paid: 'success-bg',
    started: 'info-bg',
    finished: 'neutral-bg',
    cancelled: 'secondary-bg',
  };

  return map[status] ?? 'neutral-bg';
};

const statusLabel = (status) => {
  const map = {
    pending: t('provider.dashboard.agenda.status_pending'),
    accepted: t('provider.dashboard.agenda.status_accepted'),
    paid: t('provider.dashboard.agenda.status_paid'),
    started: t('provider.dashboard.agenda.status_started'),
    finished: t('provider.dashboard.agenda.status_finished'),
    cancelled: t('provider.dashboard.agenda.status_cancelled'),
  };

  return map[status] ?? status;
};

const statusTextColor = (status) => {
  const map = {
    pending: 'warning',
    accepted: 'success',
    paid: 'success',
    started: 'info',
    finished: 'status-finished',
    cancelled: 'secondary',
  };

  return map[status] ?? 'text';
};

//

const loadCalendar = async () => {
  const response = await getProviderCalendar();

  if (response) {
    upcomingSchedules.value = response.upcomingSchedules ?? [];
    completedSchedules.value = response.completedSchedules ?? [];
  }
};

const openDetailsDialog = (schedule) => {
  $q.dialog({
    component: NextSchedulesDetailsDialog,
    componentProps: { schedule },
  }).onOk(async ({ action }) => {
    if (action === 'cancelled') {
      await loadCalendar();
    }
  });
};

const openRatingDialog = (schedule) => {
  $q.dialog({
    component: ScheduleRatingDialog,
    componentProps: { schedule },
  }).onOk(() => {
    loadCalendar();
  });
};

onMounted(async () => {
  await loadCalendar();
  loading.value = false;
});
</script>

<style scoped lang="scss">
.calendar-header {
  padding-top: 12px;
  padding-bottom: 12px;
  box-shadow: 0px 1px 8px rgba(0, 0, 0, 0.08);
}

.calendar-card {
  border-radius: 12px;
  width: 100%;
}

.type-label {
  line-height: 1.2;
}

.text-price {
  color: #3a3a4a;
  white-space: nowrap;
}

.text-period {
  color: #888;
  text-align: right;
  white-space: nowrap;
}

.status-chip {
  height: auto;
}

.btn-rate {
  padding: 3px 10px;
}

</style>
