<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card
      class="bg-surface next-schedule-dialog-card shadow-card"
      :flat="false"
    >
      <div class="justify-end q-pr-sm q-pt-sm row">
        <q-btn
          color="grey-6"
          dense
          flat
          icon="close"
          round
          size="sm"
          @click="onDialogCancel"
        />
      </div>

      <q-card-section class="column items-center q-pb-sm q-pt-xs">
        <q-avatar
          class="q-mb-sm"
          size="72px"
        >
          <img
            v-if="schedule.customer_photo"
            :src="schedule.customer_photo"
            style="object-fit: cover"
          />

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

        <div class="font16 fontbold text-text">
          {{ getFirstName(schedule.customer_name ?? schedule.client_name) || "—" }}
        </div>

        <div class="font16 fontbold q-mt-xs text-price">
          {{ formatCurrency(schedule.total_amount) }}
        </div>

        <div class="font12 q-mt-xxs text-grey-6">
          {{ periodLabel }}
        </div>
      </q-card-section>

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

      <q-card-section class="column font12 items-center q-py-sm text-text">
        <div class="text-center">
          <span class="fontbold">
            {{ weekdayLabel }}
          </span>

          <span class="text-grey-7">
            {{ `, ${dayMonthLabel}` }}
          </span>
        </div>

        <div class="q-mt-xxs text-center">
          {{ $t("common.from") }}

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

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

          <span class="fontbold">
            {{ schedule.end_time?.slice(0, 5) }}
          </span>
        </div>
      </q-card-section>

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

      <q-card-section class="column items-center q-py-sm">
        <div class="items-center q-gutter-x-xs row">
          <q-icon
            :color="schedule.offers_meal ? 'secondary' : 'grey-5'"
            :name="
              schedule.offers_meal
                ? 'mdi-silverware'
                : 'mdi-close-circle-outline'
            "
            size="18px"
          />

          <span
            class="font12"
            :class="schedule.offers_meal ? 'text-text' : 'text-grey-6'"
          >
            {{
              schedule.offers_meal
                ? $t("provider.dashboard.next_schedules.offers_meal")
                : $t("provider.dashboard.next_schedules.no_meal")
            }}
          </span>
        </div>
      </q-card-section>

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

      <q-card-section class="column items-center q-px-lg q-py-sm">
        <div class="items-start no-wrap q-gutter-x-xs row">
          <div class="col-1 q-my-auto">
            <q-icon
              class="flex-shrink-0 q-mt-xxs"
              :color="isConfirmed ? 'primary' : 'grey-6'"
              :name="isConfirmed ? 'mdi-map-marker-outline' : 'mdi-map-marker-off-outline'"
              size="20px"
            />
          </div>

          <div class="col">
            <span
              class="font12 text-center"
              :class="isConfirmed ? 'text-grey-8' : 'text-grey-6'"
            >
              {{
                isConfirmed
                  ? formattedAddress || "N/A"
                  : $t("provider.dashboard.next_schedules.address_hidden")
              }}
            </span>
          </div>
        </div>

        <div class="font12 q-mt-xs text-center text-grey-6">
          {{ $t("provider.dashboard.solicitations.distance_prefix") }}

          <strong>
            {{ `${schedule.distance_km ?? 0} km` }}
          </strong>

          {{ $t("provider.dashboard.solicitations.distance_suffix") }}
        </div>

        <q-btn
          v-if="isConfirmed"
          class="q-mt-xs"
          color="primary"
          dense
          flat
          icon="mdi-content-copy"
          no-caps
          size="sm"
          :label="$t('provider.dashboard.next_schedules.copy_address')"
          @click="copyAddress"
        />
      </q-card-section>

      <q-card-section class="q-pb-sm q-pt-xs q-px-lg">
        <q-btn
          class="btn-close font14 fontbold full-width"
          color="primary"
          no-caps
          rounded
          size="sm"
          unelevated
          :label="$t('provider.dashboard.cancel_schedule.close')"
          @click="onDialogCancel"
        />
      </q-card-section>

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

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

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

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

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

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

const $q = useQuasar();

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

const { t } = useI18n();

const dayMonthLabel = computed(() => {
  const date = parseLocalDate(props.schedule.date);

  if (!date) return "";

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

const formattedAddress = computed(() => formatAddress(props.schedule.address));

const isConfirmed = computed(() =>
  ["accepted", "paid", "started", "finished"].includes(props.schedule.status),
);

const periodLabel = computed(() => {
  const period = labelsPeriodTypes.find(
    (label) => label.value == props.schedule.period_type,
  );

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

const weekdayLabel = computed(() => {
  const date = parseLocalDate(props.schedule.date);

  if (!date) return "";

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

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

const copyAddress = () => {
  const address = formattedAddress.value;

  if (address) {
    navigator.clipboard.writeText(address);
  }

  $q.notify({
    color: "positive",
    message: t("provider.dashboard.next_schedules.address_copied"),
  });
};

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

  const date = String(dateString);

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

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

  const brDate = date.match(/^(\d{2})\/(\d{2})\/(\d{4})/);

  if (brDate) {
    return new Date(+brDate[3], +brDate[2] - 1, +brDate[1]);
  }

  return null;
};

//

const openCancelDialog = () => {
  $q.dialog({
    component: ScheduleCancelDialog,
    componentProps: { schedule: props.schedule },
  }).onOk(() => {
    onDialogOK({ action: "cancelled", id: props.schedule.id });
  });
};

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

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

.text-price {
  color: var(--q-primary);
}

.btn-close {
  padding: 10px 0;
}

.flex-shrink-0 {
  flex-shrink: 0;
}

.q-mt-xxs {
  margin-top: 2px;
}
</style>
