<!-- eslint-disable @intlify/vue-i18n/no-raw-text -->
<template>
  <q-dialog
    ref="dialogRef"
    @hide="onDialogHide"
  >
    <q-card
      class="solicitation-dialog-card bg-surface shadow-card"
      :flat="false"
    >
      <template v-if="isPaid">
        <div class="row justify-end q-pt-sm q-pr-sm">
          <q-btn
            color="grey-6"
            dense
            flat
            icon="close"
            round
            size="sm"
            @click="onDialogCancel"
          />
        </div>

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

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

          <div class="text-text font16 fontbold">
            {{ solicitation.client_name }}
          </div>

          <div
            v-if="solicitation.address?.district"
            class="text-grey-6 font12 q-mt-xs"
          >
            {{ solicitation.address.district }}
          </div>

          <div
            v-if="solicitation.address"
            class="text-grey-6 font12 text-center q-mt-xs"
          >
            {{ formatAddressShort(solicitation.address) }}
          </div>
        </q-card-section>

        <q-separator class="q-mx-md q-my-xs" />

        <q-card-section class="q-pt-xs q-pb-xs q-px-lg">
          <div
            v-for="service in servicesList"
            :key="service.label"
            class="row items-center q-gutter-x-sm q-mb-xs"
          >
            <q-icon
              :color="service.active ? 'secondary' : 'grey-4'"
              :name="service.active ? 'mdi-check' : 'mdi-close'"
              size="16px"
            />

            <span class="text-grey-8 font14">
              {{ service.label }}
            </span>
          </div>
        </q-card-section>

        <q-separator class="q-mx-md q-my-xs" />

        <q-card-section class="q-pt-xs q-pb-xs q-px-lg">
          <div class="detail-row">
            <span class="text-secondary font12 fontsemibold">
              {{ $t("common.terms.date") }}
            </span>

            <span class="text-grey-9 font13">
              {{ fullDateLabel }}
            </span>
          </div>

          <div class="detail-row">
            <span class="text-secondary font12 fontsemibold">
              {{ $t("common.terms.hour") }}
            </span>

            <span class="text-grey-9 font13">
              {{ solicitation.start_time?.slice(0, 5) }} {{ $t("common.to") }}
              {{ solicitation.end_time?.slice(0, 5) }}
            </span>
          </div>

          <div class="detail-row">
            <span class="text-secondary font12 fontsemibold">
              {{ $t("common.terms.total_amount") }}
            </span>

            <span class="text-grey-9 font13">
              {{ formatCurrency(baseAmount) }}
            </span>
          </div>

          <div class="detail-row">
            <span class="text-secondary font12 fontsemibold">
              {{ $t("provider.dashboard.cancel_schedule.service_fee") }}
            </span>

            <span class="text-grey-9 font13">
              {{ formatCurrency(serviceFee) }}
            </span>
          </div>
        </q-card-section>

        <q-separator class="q-mx-md q-my-xs" />

        <q-card-section class="q-pt-xs q-pb-sm text-center">
          <span class="text-grey-9 fontbold">
            {{ $t("provider.dashboard.cancel_schedule.total") }}
          </span>

          <span class="text-secondary fontbold font22 q-ml-xs">
            {{ formatCurrency(paidTotalAmount) }}
          </span>
        </q-card-section>

        <q-card-section class="q-pt-none q-pb-xs q-px-lg">
          <q-btn
            class="full-width btn-close-paid font16 fontbold"
            color="secondary"
            no-caps
            rounded
            unelevated
            :label="$t('provider.dashboard.cancel_schedule.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('provider.dashboard.cancel_schedule.btn_cancel_order')"
              @click="openCancelDialog"
            />

            <q-btn
              color="grey-7"
              flat
              no-caps
              size="sm"
              :label="$t('provider.dashboard.cancel_schedule.help')"
            />
          </div>
        </q-card-section>
      </template>

      <template v-else-if="view === 'details'">
        <div class="row justify-end q-pt-sm q-pr-sm">
          <q-btn
            color="grey-6"
            dense
            flat
            icon="close"
            round
            size="sm"
            @click="onDialogCancel"
          />
        </div>

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

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

          <div class="text-text font16 fontbold">
            {{ solicitation.client_name }}
          </div>

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

          <div
            v-if="packageItems.length > 1"
            class="text-grey-6 font12"
          >
            {{ packageCountLabel }}
          </div>
        </q-card-section>

        <q-card-section class="q-pt-none q-pb-sm q-px-md text-text">
          <div
            v-for="(pkgItem, idx) in packageItems"
            :key="idx"
            class="package-item-row"
          >
            <div class="full-width">
              <div class="row items-center no-wrap justify-between">
                <span class="fontbold font12">
                  {{ formatItemWeekday(pkgItem.date) }}, {{ formatItemDayMonth(pkgItem.date) }}
                </span>

                <span class="fontbold font12">
                  {{ formatCurrency(Number(pkgItem.total_amount) || 0) }}
                </span>
              </div>

              <div class="row items-center no-wrap justify-between">
                <span class="text-grey-6 font12">
                  {{ pkgItem.start_time?.slice(0, 5) }} {{ $t("common.to") }} {{ pkgItem.end_time?.slice(0, 5) }}
                </span>

                <div class="row items-center no-wrap">
                  <!--
                  <q-icon
                    :color="pkgItem.offers_meal ? 'positive' : 'grey-5'"
                    :name="pkgItem.offers_meal ? 'mdi-food' : 'mdi-food-off'"
                    size="14px"
                    class="q-mr-xs"
                  />
                  !-->
                  <span class="text-grey-7 font12">
                    {{
                      pkgItem.offers_meal
                        ? $t("provider.dashboard.solicitations.offers_meal")
                        : $t("provider.dashboard.solicitations.not_offers_meal")
                    }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </q-card-section>

        <q-card-section class="column items-center q-pt-xs q-pb-sm text-text">
          <div class="row items-start no-wrap self-start q-gutter-x-xs">
            <q-icon
              class="q-mt-xs"
              color="primary"
              name="mdi-map-marker"
              size="20px"
            />

            <span class="font16 fontbold text-center">
              {{ formatAddress(solicitation.address) || "N/A" }}
            </span>
          </div>

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

            <strong>
              {{ (solicitation.distance_km ?? 0) + " km" }}
            </strong>

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

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

            <span class="text-primary fontbold">
              {{ " " + $t("provider.dashboard.solicitations.via_agenda") }}
            </span>
          </div>
        </q-card-section>

        <q-separator />

        <q-card-section
          v-if="solicitation?.status != 'accepted'"
          class="q-py-sm"
        >
          <div class="row justify-center q-gutter-x-md">
            <q-btn
              class="btn-action bg-grey-3 text-grey-8"
              no-caps
              rounded
              unelevated
              :label="$t('common.refuse')"
              @click="view = 'confirm-reject'"
            />

            <q-btn
              class="btn-action"
              color="secondary"
              no-caps
              rounded
              unelevated
              :label="$t('common.accept')"
              :loading="loading"
              @click="confirmAccept"
            />
          </div>

          <div class="row justify-center q-mt-xs">
            <q-btn
              color="grey-7"
              flat
              no-caps
              size="sm"
              :label="$t('common.actions.back')"
              @click="onDialogCancel"
            />
          </div>
        </q-card-section>

        <div class="q-pa-md font12 text-primary">
          <span>
            {{ $t("provider.dashboard.solicitations.same_day_warning_before") }}
          </span>

          <span class="fontbold">
            {{ $t("provider.dashboard.solicitations.same_day_warning_bold") }}
          </span>

          <span>
            {{ $t("provider.dashboard.solicitations.same_day_warning_after") }}
          </span>
        </div>
      </template>

      <template v-else-if="view === 'confirm-reject'">
        <q-card-section class="column items-center q-pt-xl q-pb-md text-center">
          <div class="confirm-title text-secondary fontbold">
            {{ $t("provider.dashboard.solicitations.confirm_reject") }}
          </div>

          <div class="q-mt-md text-grey-7 confirm-tip font13">
            <strong>
              {{ $t("provider.dashboard.solicitations.tip_label") }}
            </strong>
  
            {{ $t("provider.dashboard.solicitations.reject_tip") }}
          </div>
        </q-card-section>

        <q-card-section class="q-pt-none q-pb-xl">
          <div class="row justify-center q-gutter-x-md">
            <q-btn
              class="btn-action"
              color="purple-5"
              no-caps
              rounded
              unelevated
              :label="$t('common.actions.back')"
              @click="backFromConfirm"
            />
  
            <q-btn
              class="btn-action"
              color="secondary"
              no-caps
              rounded
              unelevated
              :loading="loading"
              :label="$t('common.refuse')"
              @click="confirmReject"
            />
          </div>
        </q-card-section>
      </template>
    </q-card>
  </q-dialog>
</template>

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

import ScheduleCancelDialog from "./ScheduleCancelDialog.vue";

const props = defineProps({
  initialView: {
    default: "details",
    type: String,
    validator: (v) =>
      ["details", "confirm-reject"].includes(v),
  },
  solicitation: {
    required: true,
    type: Object,
  },
});

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

const loading = ref(false);
const view = ref(props.initialView);

const $q = useQuasar();

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

const { t } = useI18n();

const baseAmount = computed(() => {
  const amount =
    props.solicitation.service_amount ?? props.solicitation.base_amount;

  return parseAmount(amount);
});

const fullDateLabel = computed(() => {
  const date = parseLocalDate(props.solicitation.date);

  if (!date) return "";

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

const isPaid = computed(() => props.solicitation.status === "paid");

const paidTotalAmount = computed(() =>
  parseAmount(
    props.solicitation.gross_amount ?? props.solicitation.total_amount,
  ),
);

const packageCountLabel = computed(() =>
  packageItems.value.length > 1
    ? t("provider.dashboard.solicitations.package_count", {
        count: packageItems.value.length,
      })
    : "",
);

const packageItems = computed(() => {
  const items = props.solicitation?.package_items;

  if (Array.isArray(items) && items.length) {
    return items;
  }

  return [props.solicitation];
});

const packageTotal = computed(() =>
  packageItems.value.reduce(
    (total, item) => total + parseAmount(item.total_amount),
    0,
  ),
);

const serviceFee = computed(() => {
  const fee =
    props.solicitation.platform_fee_amount ??
    props.solicitation.service_fee_amount ??
    props.solicitation.service_fee;

  return parseAmount(fee);
});

const servicesList = computed(() => {
  const services = [];

  const solicitation = props.solicitation;

  if (
    solicitation.schedule_type === "custom" &&
    solicitation.specialities?.length
  ) {
    solicitation.specialities.forEach((speciality) => {
      services.push({ active: true, label: speciality.description });
    });
  } else {
    services.push({
      active: true,
      label: t("provider.dashboard.next_schedules.default"),
    });
  }

  if (solicitation.offers_meal !== undefined) {
    services.push({
      active: !!solicitation.offers_meal,
      label: solicitation.offers_meal
        ? t("provider.dashboard.solicitations.offers_meal")
        : t("provider.dashboard.solicitations.not_offers_meal"),
    });
  }

  return services;
});

//

const WEEKDAYS = ["Domingo", "Segunda-feira", "Terça-feira", "Quarta-feira", "Quinta-feira", "Sexta-feira", "Sábado"];

const backFromConfirm = () => {
  if (props.initialView !== "details") {
    onDialogCancel();
  } else {
    view.value = "details";
  }
};

const confirmAccept = () => {
  loading.value = true;

  onDialogOK({
    action: "accept",
    id: props.solicitation.id,
    ids: packageItems.value.map((item) => item.id),
    service_package_id: props.solicitation.service_package_id,
  });
};

const confirmReject = () => {
  loading.value = true;

  onDialogOK({
    action: "reject",
    id: props.solicitation.id,
    ids: packageItems.value.map((item) => item.id),
    service_package_id: props.solicitation.service_package_id,
  });
};

//

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

  if (!date) return "";

  return WEEKDAYS[date.getDay()];
};

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

  if (!date) return "";

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

const formatAddressShort = (address) => {
  if (!address) return "";

  const street = [address.address, address.number].filter(Boolean).join(", ");
  const district = address.district ? `, ${address.district}` : "";

  return street + district;
};

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.solicitation },
  }).onOk(() => {
    onDialogOK({ action: "cancelled", id: props.solicitation.id });
  });
};

const parseAmount = (value) => {
  const amount = Number.parseFloat(value);

  return Number.isFinite(amount) ? amount : 0;
};

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

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

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

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

.confirm-title {
  line-height: 1.35;
  padding: 0 12px;
}

.confirm-tip {
  line-height: 1.5;
  padding: 0 8px;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  align-items: baseline;
  margin-bottom: 4px;
}

.package-item-row {
  border-bottom: 1px solid #ececf2;
  padding: 6px 0;

  &:last-child {
    border-bottom: none;
  }
}

.min-width-0 {
  min-width: 0;
}
</style>
