<template>
  <q-card-section class="no-padding">
    <div class="text-text q-mb-sm text-weight-medium">{{ $t('provider.login.steps.step_5.daily_price_title') }}</div>
    <DefaultCurrencyInput
      v-model="form.daily_price_8h"
      rounded
      no-error-icon
      class="bg-surface q-mb-sm custom-currency-input"
      input-class="text-text"
      placeholder="R$ 0,00"
      :error="!!priceError"
      hide-bottom-space
      label=""
    />

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

    <q-banner class="bg-blue-1 text-primary q-mb-lg q-pa-md bannerRound">
      <template #avatar>
        <q-icon name="mdi-alert-outline" color="primary" />
      </template>
      <span class="text-weight-bold">{{ $t('provider.login.steps.step_5.dont_worry') }}</span> {{ $t('provider.login.steps.step_5.change_anytime') }}
    </q-banner>

    <div class="text-text text-center q-mb-sm">{{ $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 text-weight-bold">{{ $t('provider.login.steps.step_5.up_to_6h') }}</div>
        <q-input :model-value="formatCurrency(form.daily_price_6h)" readonly class="bg-surface" input-class="text-text"/>
      </div>
      <div class="col-4">
        <div class="text-text text-center text-weight-bold">{{ $t('provider.login.steps.step_5.up_to_4h') }}</div>
        <q-input :model-value="formatCurrency(form.daily_price_4h)" readonly class="bg-surface" input-class="text-text"/>
      </div>
      <div class="col-4 column">
        <div class="text-text text-center text-weight-bold">{{ $t('provider.login.steps.step_5.up_to_2h') }}</div>
        <q-input :model-value="formatCurrency(form.daily_price_2h)" readonly class="bg-surface" input-class="text-text"/>
      </div>
    </div>

    <div class="text-text text-weight-medium q-mb-xs text-center">{{ $t('provider.login.steps.step_5.other_services') }}</div>
    <div class="text-caption text-grey-7 q-mb-md text-center">{{ $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"
          color="primary"
          class="q-mb-md text-text"
          keep-color
          @update:model-value="(checked) => onServiceToggle(service.value, checked)"
        />
      </div>
    </div>

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

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

<script setup>
import { computed, onMounted, ref, watch } from 'vue';
import { getPublicServiceTypes } from 'src/api/serviceType';
import DefaultCurrencyInput from 'src/components/defaults/DefaultCurrencyInput.vue';

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

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

const priceError = computed(() => {
  const value = form.value.daily_price_8h;
  if (value === null || value === undefined || value === '') {
    return 'Este campo é obrigatório';
  }

  const numericValue = Number(value);

  if (Number.isNaN(numericValue)) {
    return 'Valor inválido';
  }

  if (numericValue < 100) {
    return 'Valor mínimo R$ 100,00';
  }

  if (numericValue > 500) {
    return 'Valor máximo R$ 500,00';
  }

  return '';
});

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', {
    style: 'currency',
    currency: 'BRL',
    minimumFractionDigits: 2,
  });
};

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 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;
  }
};

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.30).toFixed(2));
  },
  { immediate: true },
);

onMounted(() => {
  loadServiceTypes();
});
</script>
<style scoped>
.bannerRound {
  border-radius: 18px;
}
:deep(.custom-currency-input .q-field__control) {
  border-radius: 28px;
}
</style>