<template>
  <q-card-section class="no-padding">
    <div class="font12 fontbold q-mb-sm text-text">
      {{ $t("provider.login.steps.step_5.daily_price_title") }}
    </div>

    <DefaultCurrencyInput
      :ref="fieldRefs.daily_price_8h"
      v-model="form.daily_price_8h"
      class="bg-surface q-mb-sm custom-currency-input"
      hide-bottom-space
      input-class="text-text font12 fontmedium"
      label=""
      no-error-icon
      placeholder="R$ 0,00"
      rounded
      :error="!!serverErrors.daily_price_8h || !!priceError"
      :error-message="serverErrors.daily_price_8h || priceError"
      :rules="[validateDailyPrice]"
      @update:model-value="clearServerError('daily_price_8h')"
    />

    <div class="font10 fontmedium q-mb-md text-center text-grey-7">
      {{ dailyPriceMinMaxText }}
    </div>

    <q-banner class="banner-round bg-blue-1 q-mb-lg q-pa-md text-primary">
      <template #avatar>
        <q-icon color="primary" name="mdi-alert-outline" />
      </template>

      <span class="fontbold font12">
        {{ $t("provider.login.steps.step_5.dont_worry") }}
      </span>

      <span class="font12 q-ml-xs">
        {{ $t("provider.login.steps.step_5.change_anytime") }}
      </span>
    </q-banner>

    <div class="font12 fontmedium q-mb-sm text-center text-text">
      {{ $t("provider.login.steps.step_5.shorter_services") }}
    </div>

    <div class="row q-col-gutter-sm q-mb-lg q-mt-md">
      <div class="col-4">
        <div class="text-text text-center fontbold font12">
          {{ $t("provider.login.steps.step_5.up_to_6h") }}
        </div>

        <q-input
          :model-value="formatCurrency(form.daily_price_6h)"
          class="bg-surface"
          input-class="font12 fontmedium text-text"
          readonly
        />
      </div>

      <div class="col-4">
        <div class="text-text text-center fontbold font12">
          {{ $t("provider.login.steps.step_5.up_to_4h") }}
        </div>

        <q-input
          :model-value="formatCurrency(form.daily_price_4h)"
          class="bg-surface"
          input-class="font12 fontmedium text-text"
          readonly
        />
      </div>

      <div class="col-4 column">
        <div class="text-text text-center fontbold font12">
          {{ $t("provider.login.steps.step_5.up_to_2h") }}
        </div>

        <q-input
          :model-value="formatCurrency(form.daily_price_2h)"
          class="bg-surface"
          input-class="font12 fontmedium text-text"
          readonly
        />
      </div>
    </div>

    <div class="font12 fontbold q-mb-xs text-center text-text">
      {{ $t("provider.login.steps.step_5.other_services") }}
    </div>

    <div class="text-grey-7 q-mb-md text-center font10">
      {{ $t("provider.login.steps.step_5.change_in_profile") }}
    </div>

    <div v-if="loadingServiceTypes" class="row justify-center q-mb-lg">
      <q-spinner color="primary" size="28px" />
    </div>

    <div v-else-if="serviceOptions.length" class="row q-col-gutter-sm q-mb-lg">
      <div v-for="service in serviceOptions" :key="service.value" class="col-6">
        <q-checkbox
          :model-value="selectedServices.includes(service.value)"
          :label="service.label"
          class="q-mb-md text-text font12 fontmedium"
          color="primary"
          keep-color
          @update:model-value="
            (checked) => onServiceToggle(service.value, checked)
          "
        />
      </div>
    </div>

    <div v-else class="text-grey-7 q-mb-lg font12 fontmedium">
      {{ $t("provider.login.steps.step_5.no_services") }}
    </div>

    <div class="text-grey-7 text-center font12 fontmedium">
      {{ $t("provider.login.steps.step_5.search_visibility") }}
    </div>
  </q-card-section>
</template>

<script setup>
import { computed, inject, onMounted, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { getProviderDailyPriceMin } from "src/api/provider";
import { getPublicServiceTypes } from "src/api/serviceType";

import DefaultCurrencyInput from "src/components/defaults/DefaultCurrencyInput.vue";

const form = defineModel({
  required: true,
  type: Object,
});

const { t } = useI18n();

const serverErrors = inject("serverErrors", ref({}));
const clearServerError = inject("clearServerError", () => {});

const fieldRefs = {
  daily_price_8h: ref(null),
};

defineExpose({
  getFieldRef: (field) => field.startsWith("daily_price_")
    ? fieldRefs.daily_price_8h
    : fieldRefs[field],
});

const DEFAULT_DAILY_PRICE_MIN = 100;
const DAILY_PRICE_MAX = 500;

const dailyPriceMin = ref(DEFAULT_DAILY_PRICE_MIN);
const loadingServiceTypes = ref(false);
const serviceOptions = ref([]);

const dailyPriceMinMaxText = computed(() => {
  return t('profile.service_data.price_min_max', {
    min: formatCurrency(dailyPriceMin.value),
    max: formatCurrency(DAILY_PRICE_MAX),
  });
});

const priceError = computed(() =>
  getDailyPriceError(form.value.daily_price_8h),
);

const selectedServices = computed(() => {
  if (!Array.isArray(form.value.services_types_ids)) {
    return [];
  }

  return form.value.services_types_ids;
});

const formatCurrency = (value) => {
  if (value === null || value === undefined || Number.isNaN(Number(value))) {
    return "R$ 0,00";
  }

  return Number(value).toLocaleString("pt-BR", {
    currency: "BRL",
    minimumFractionDigits: 2,
    style: "currency",
  });
};

const getDailyPriceError = (value) => {
  if (value === null || value === undefined || value === "") {
    return t('validation.rules.required');
  }

  const numericValue = Number(value);

  if (Number.isNaN(numericValue)) {
    return t('validation.rules.required');
  }

  if (numericValue < dailyPriceMin.value) {
    return t('profile.service_data.price_min_error', { value: formatCurrency(dailyPriceMin.value) });
  }

  if (numericValue > DAILY_PRICE_MAX) {
    return t('profile.service_data.price_max_error', { value: formatCurrency(DAILY_PRICE_MAX) });
  }

  return "";
};

const loadDailyPriceMin = async () => {
  try {
    const payload = await getProviderDailyPriceMin();

    dailyPriceMin.value = parseDailyPriceMin(payload);
  } catch (error) {
    dailyPriceMin.value = DEFAULT_DAILY_PRICE_MIN;

    console.error(error);
  }
};

const loadServiceTypes = async () => {
  loadingServiceTypes.value = true;

  try {
    const serviceTypes = await getPublicServiceTypes();

    serviceOptions.value = (Array.isArray(serviceTypes) ? serviceTypes : [])
      .filter((item) => item?.is_active !== false)
      .map((item) => ({
        label: item.description,
        value: Number(item.id),
      }))
      .filter((item) => Number.isInteger(item.value) && item.value > 0);
  } catch (error) {
    serviceOptions.value = [];

    console.error(error);
  } finally {
    loadingServiceTypes.value = false;
  }
};

const normalizeSelectedServiceIds = () => {
  if (!Array.isArray(form.value.services_types_ids)) {
    form.value.services_types_ids = [];
  }

  form.value.services_types_ids = form.value.services_types_ids
    .map((id) => Number(id))
    .filter((id) => Number.isInteger(id) && id > 0);
};

const onServiceToggle = (value, checked) => {
  normalizeSelectedServiceIds();

  if (checked) {
    if (!form.value.services_types_ids.includes(value)) {
      form.value.services_types_ids.push(value);
    }

    return;
  }

  form.value.services_types_ids = form.value.services_types_ids.filter(
    (serviceId) => serviceId !== value,
  );
};

const parseDailyPriceMin = (payload) => {
  const rawValue =
    payload?.daily_price_min ??
    payload?.dailyPriceMin ??
    payload?.min ??
    payload?.value ??
    payload;

  const value = Number(rawValue);

  if (!Number.isFinite(value) || value < 0) {
    return DEFAULT_DAILY_PRICE_MIN;
  }

  return value;
};

const validateDailyPrice = () => {
  return getDailyPriceError(form.value.daily_price_8h) || true;
};

watch(
  () => form.value.daily_price_8h,
  (value) => {
    const price = Number(value);

    if (!price || Number.isNaN(price)) {
      form.value.daily_price_6h = null;
      form.value.daily_price_4h = null;
      form.value.daily_price_2h = null;
      return;
    }

    form.value.daily_price_6h = Number((price * 0.85).toFixed(2));
    form.value.daily_price_4h = Number((price * 0.55).toFixed(2));
    form.value.daily_price_2h = Number((price * 0.3).toFixed(2));
  },
  { immediate: true },
);

onMounted(() => {
  loadServiceTypes();
  loadDailyPriceMin();
});
</script>
<style scoped lang="scss">
@use "sass:map";

.banner-round {
  border-radius: 18px;
}

:deep(.custom-currency-input .q-field__control) {
  border-radius: 28px;
}

:deep(.custom-currency-input .q-field__bottom) {
  background: map.get($colors, "surface-dark");
}
</style>
