<template>
  <q-dialog
    ref="dialogRef"
    @hide="onDialogHide"
  >
    <q-card
      class="next-schedule-dialog-card bg-surface"
      :flat="false"
    >
      <q-card-section class="column items-center q-pt-lg q-pb-sm">
        <q-avatar
          class="fontbold text-h5 q-mb-sm"
          size="80px"
          :style="avatarStyle"
        >
          <img
            v-if="details?.provider_photo"
            :src="details.provider_photo"
          />

          <span v-else>
            {{ schedule.provider_name?.slice(0, 2).toUpperCase() ?? "??" }}
          </span>
        </q-avatar>

        <div class="provider-name font16 fontbold">
          {{ getFirstName(schedule.provider_name) || "—" }}

          <span
            v-if="providerAge !== null"
            class="text-grey-6"
          >
            {{
              "(" +
              providerAge +
              " " +
              $t("dashboard_client.next_schedules.provider_age_unit") +
              ")"
            }}
          </span>
        </div>

        <div class="text-text font12 fontbold">
          {{ schedule.address?.district }}
        </div>

        <div
          v-if="schedule.address"
          class="font9 fontmedium text-grey-7 q-mt-xs"
        >
          <q-icon
            class="q-mr-xs"
            color="text"
            name="mdi-map-marker"
            size="14px"
          />

          {{ formatAddress(schedule.address) }}
        </div>
      </q-card-section>

      <q-separator class="q-mx-lg" />

      <q-card-section class="q-py-sm">
        <template v-if="loadingDetails">
          <div class="row justify-center q-py-sm">
            <q-spinner-dots
              color="primary"
              size="24px"
            />
          </div>
        </template>

        <template v-else>
          <div
            v-for="service in servicesList"
            :key="service.label"
            class="row col-12 items-center q-gutter-x-sm q-mb-xs text-center"
          >
            <div class="full-width">
              <q-icon
                color="secondary"
                name="mdi-check"
                size="12px"
              />

              <span class="text-grey-8 font10 fontmedium q-pl-sm">
                {{ service.label }}
              </span>
            </div>
          </div>
        </template>
      </q-card-section>

      <q-separator class="q-mx-lg divisoria-tracejada" />

      <q-card-section class="q-py-md q-px-lg font12 fontmedium">
        <div class="detail-row">
          <span class="detail-label text-primary q-pr-sm">
            {{ $t("dashboard_client.pending_schedules.detail_date") }}
          </span>

          <span class="detail-value">
            {{ fullDateLabel }}
          </span>
        </div>

        <div class="detail-row">
          <span class="detail-label text-primary q-pr-sm">
            {{ $t("dashboard_client.pending_schedules.detail_time") }}
          </span>

          <span class="detail-value">
            {{ schedule.start_time?.slice(0, 5) }}
            {{ $t("dashboard_client.next_schedules.to") }}
            {{ schedule.end_time?.slice(0, 5) }}
          </span>
        </div>

        <div class="detail-row-total font16 fontbold">
          <span class="detail-label text-primary q-pr-sm">
            {{ $t("dashboard_client.pending_schedules.detail_total") }}
          </span>

          <span class="total-value">
            {{ formatCurrency(total) }}
          </span>
        </div>

        <q-separator class="q-my-sm divisoria-tracejada" />
      </q-card-section>

      <q-card-section class="q-pt-none q-pb-sm q-px-lg">
        <q-btn
          class="close-btn full-width"
          color="primary"
          no-caps
          rounded
          unelevated
          :label="$t('dashboard_client.next_schedules.btn_close')"
          @click="onDialogCancel"
        />
      </q-card-section>

      <q-card-section class="q-pt-xs q-pb-md text-center">
        <div class="row justify-center q-gutter-x-lg">
          <q-btn
            color="grey-7"
            flat
            no-caps
            size="sm"
            :label="$t('dashboard_client.pending_schedules.btn_cancel')"
            @click="openCancelDialog"
          />

          <q-btn
            color="grey-7"
            flat
            no-caps
            size="sm"
            :label="$t('dashboard_client.next_schedules.btn_help')"
            @click="openHelp"
          />
        </div>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { avatarColors } from "src/helpers/avatarColors";
import { computed, onMounted, ref } from "vue";
import { formatAddress, formatCurrency, getFirstName } from "src/helpers/utils";
import { getScheduleClienteDetails } from "src/api/dashboard";

import {
  getSchedulePaymentType,
  getScheduleTotalWithPlatformFee,
} from "src/helpers/paymentPlatformFees";

import { useDialogPluginComponent, useQuasar } from "quasar";
import { useI18n } from "vue-i18n";
import { usePaymentPlatformFees } from "src/composables/usePaymentPlatformFees";

import ProfileHelpDialog from "src/components/profile/ProfileHelpDialog.vue";
import ScheduleCancelDialog from "./ScheduleCancelDialog.vue";

const props = defineProps({
  schedule: { type: Object, required: true },
});

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

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

const { dialogRef, onDialogHide, onDialogCancel } = useDialogPluginComponent();

const { platformFees, loadPlatformFees } = usePaymentPlatformFees();

const details = ref(null);
const loadingDetails = ref(true);

const avatarStyle = computed(
  () => avatarColors[props.schedule.id % avatarColors.length],
);

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 fullDateLabel = computed(() => {
  if (props.schedule.formatted_date) return props.schedule.formatted_date;

  const d = parseLocalDate(props.schedule.date);

  if (!d) return props.schedule.date ?? "";

  return d.toLocaleDateString("pt-BR", {
    day: "2-digit",
    month: "long",
    year: "numeric",
  });
});

const providerAge = computed(() => {
  if (!details.value?.provider_birth_date) return null;

  const birth = new Date(details.value.provider_birth_date);

  const today = new Date();

  let age = today.getFullYear() - birth.getFullYear();

  const m = today.getMonth() - birth.getMonth();

  if (m < 0 || (m === 0 && today.getDate() < birth.getDate())) age--;

  return age;
});

const servicesList = computed(() => {
  const scheduleType =
    details.value?.schedule_type ?? props.schedule.schedule_type;

  const specialities = details.value?.specialities ?? [];

  if (scheduleType === "custom" && specialities.length) {
    return specialities.map((speciality) => ({
      label: speciality.description,
    }));
  }

  return [{ label: t("dashboard_client.next_schedules.default_service") }];
});

const total = computed(() =>
  getScheduleTotalWithPlatformFee(
    props.schedule,
    getSchedulePaymentType(props.schedule),
    platformFees.value,
  ),
);

const openCancelDialog = () => {
  $q.dialog({
    component: ScheduleCancelDialog,
    componentProps: { schedule: props.schedule },
  });
};

const openHelp = () => {
  $q.dialog({ component: ProfileHelpDialog });
};

onMounted(async () => {
  try {
    details.value = await getScheduleClienteDetails(props.schedule.id);

    loadPlatformFees().catch(() => {});
  } catch {
    $q.notify({ message: t("http.errors.failed"), color: "negative" });
  } finally {
    loadingDetails.value = false;
  }
});
</script>

<style scoped lang="scss">
.next-schedule-dialog-card {
  width: 320px;
  max-width: 92vw;
  border-radius: 20px !important;
  overflow: hidden;
}

.provider-name {
  color: #8b5cf6;
}

.detail-row {
  display: flex;
  justify-content: left;
  align-items: center;
}

.detail-row-total {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 4px 0;
}

.detail-label {
  color: #8a8a9a;
}

.detail-value {
  color: #3a3a4a;
}

.total-value {
  color: #3a3a4a;
}

.close-btn {
  color: white;
  height: 48px;
}

.q-mt-xxs {
  margin-top: 2px;
}

.divisoria-tracejada {
  border-top: 1px dashed #cfcfcf;
}
</style>
