<!-- eslint-disable @intlify/vue-i18n/no-raw-text -->
<template>
  <q-page class="sob-medida-page">
    <div class="row items-center q-px-md q-pt-md q-pb-sm bg-white shadow-profile">
      <q-btn class="header-back-btn" flat round dense icon="mdi-chevron-left" color="primary" @click="router.back()" />
      <q-space />
      <span class="text-subtitle1 text-primary font16 fontbold gradient-diarista">{{ $t('sob_medida.page_title') }}</span>
      <q-space />
    </div>
    <div class="page-shell">

      <q-card flat bordered class="figma-card compact-card">
        <div class="card-title text-left font16 fontbold gradient-diarista">
          {{ $t('sob_medida.your_order') }}
        </div>

        <div class="field-label text-center gradient-diarista font12 fontbold">
          {{ $t('sob_medida.quantity_service') }}
        </div>

        <div class="quantity-stepper">
          <q-btn
            round
            flat
            icon="remove"
            class="quantity-btn"
            size="sm"
            @click="decreaseQuantity"
          />

          <span class="quantity-value gradient-diarista">
            {{ quantity }}
          </span>

          <q-btn
            round
            flat
            icon="add"
            size="sm"
            class="quantity-btn"
            @click="increaseQuantity"
          />
        </div>

        <div class="address-type-grid gradient-diarista">
          <div
            v-for="option in addressTypesOptions"
            :key="option.value"
            class="option-col"
          >
            <q-radio
              v-model="selectedOption"
              :val="option.value"
              :label="option.label"
              color="purple"
              dense
            />
          </div>
        </div>

        <div class="field-label text-center gradient-diarista font12 fontbold">
          {{ $t('sob_medida.service_type') }}
        </div>

        <div class="service-type-inline">
          <div
            v-for="serviceType in serviceTypes"
            :key="serviceType.id"
            class="option-col"
          >
            <q-radio
              v-model="selectedServiceType"
              :val="serviceType.id"
              :label="serviceType.description"
              color="purple"
              dense
            />
          </div>
        </div>

        <div class="field-label text-center gradient-diarista font12 fontbold">
          {{ $t('sob_medida.preferred_specialty') }}
        </div>

        <div class="options-grid specialties-grid">
          <div
            v-for="item in specialties"
            :key="item.id"
            class="specialty-col"
          >
            <q-checkbox
              v-model="selectedSpecialties"
              :val="item.id"
              :label="item.description"
              color="purple"
              dense
            />
          </div>
        </div>

        <div class="field-label text-center gradient-diarista">
          {{ $t('sob_medida.description_label') }}
          <span class="optional">
            {{ $t('sob_medida.optional') }}
          </span>
        </div>

        <q-input
          v-model="description"
          type="textarea"
          outlined
          bg-color="white"
          color="dark"
          input-class="text-black"
          class="description-box"
          :placeholder="$t('sob_medida.description_placeholder')"
        />
      </q-card>

      <div class="section-title gradient-diarista font16 fontbold">
        {{ $t('sob_medida.price_range_title') }}
      </div>

      <q-card flat bordered class="figma-card compact-card">
        <div class="range-container">
          <div
            class="price-pin"
            :style="{ left: minPosition + '%' }"
          >
            <span>{{ priceRange.min }}</span>
          </div>

          <div
            class="price-pin"
            :style="{ left: maxPosition + '%' }"
          >
            <span>{{ priceRange.max }}</span>
          </div>

          <q-range
            v-model="priceRange"
            :min="PRICE_LIMITS.min"
            :max="PRICE_LIMITS.max"
            color="secondary"
            class="price-range"
          />
        </div>

        <div class="range-helper">
          {{ $t('sob_medida.price_range_helper') }}
        </div>

        <div class="price-preview-grid">
          <div
            v-for="preview in pricePreviews"
            :key="preview.periodType"
            class="price-preview-col"
          >
            <div class="price-preview-label font12 fontbold">
              {{ $t('sob_medida.price_preview_label', { hours: preview.periodType }) }}
            </div>

            <div class="price-preview-box font12">
              {{ $t('sob_medida.price_preview_value', {
                min: formatPriceAmount(preview.min),
                max: formatPriceAmount(preview.max)
              }) }}
            </div>
          </div>
        </div>
      </q-card>

      <div class="font16 fontbold section-title gradient-diarista">
        {{ $t('sob_medida.date_and_time') }}
      </div>

      <div class="calendar-custom shadow-card">
        <q-date
          v-model="selectedDate"
          minimal
          square
          color="purple"
          class="full-width figma-date"
          :options="dateOptions"
        />
      </div>
    </div>
  </q-page>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useQuasar, date } from 'quasar'
import { useRouter } from 'vue-router'

import ServiceSelectionSheet from 'src/pages/search/components/ServiceSelectionSheet.vue'
import ServiceTimeSelectionDialog from 'src/pages/search/components/ServiceTimeSelectionDialog.vue'

import { createCustomSchedule } from 'src/api/customSchedules'
import { getPrimaryAddress } from 'src/api/address'
import { getPublicServiceTypes } from 'src/api/serviceTypes'
import { getPublicSpecialties } from 'src/api/specialties'
import {useI18n} from 'vue-i18n'
import { userStore } from 'src/stores/user'
import { calculateDailyPrices, chooseprice } from 'src/helpers/utils'

const $q = useQuasar()
const router = useRouter()
const user = userStore()
const { t } = useI18n()

const serviceTypes = ref([])
const specialties = ref([])
const address = ref(null)

const selectedServiceType = ref(null)
const selectedSpecialties = ref([])
const selectedOption = ref('home')
const description = ref('')
const selectedDate = ref(null)
const quantity = ref(1)

const PRICE_LIMITS = Object.freeze({
  min: 3,
  max: 500
})

const priceRange = ref({
  min: 3,
  max: 300
})

const addressTypesOptions = computed(() => [
  { label: t('sob_medida.residential'), value: 'home' },
  { label: t('sob_medida.commercial'), value: 'commercial' }
])

const providerPrices = computed(() =>
  calculateDailyPrices(priceRange.value.max * quantity.value)
)

const PREVIEW_PERIOD_TYPES = Object.freeze(['6', '4', '2'])

const pricePreviews = computed(() =>
  PREVIEW_PERIOD_TYPES.map((periodType) => ({
    periodType,
    min: chooseprice(periodType, priceRange.value.min),
    max: chooseprice(periodType, priceRange.value.max)
  }))
)

const formatPriceAmount = (value) =>
  Number(value ?? 0).toLocaleString('pt-BR', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })

const minPosition = computed(() =>
  ((priceRange.value.min - PRICE_LIMITS.min) /
    (PRICE_LIMITS.max - PRICE_LIMITS.min)) * 100
)

const maxPosition = computed(() =>
  ((priceRange.value.max - PRICE_LIMITS.min) /
    (PRICE_LIMITS.max - PRICE_LIMITS.min)) * 100
)

const openServiceSelection = () => {
  $q.dialog({
    component: ServiceSelectionSheet,
    componentProps: {
      provider: providerPrices.value,
      selectedDate: selectedDate.value
    }
  }).onOk((payload) => {
    if (payload?.serviceType) {
      openServiceTimeSelection(payload.serviceType)
    }
  })
}

const openServiceTimeSelection = (serviceType) => {
  $q.dialog({
    component: ServiceTimeSelectionDialog,
    componentProps: {
      serviceType,
      provider: providerPrices.value,
      selectedDate: selectedDate.value
    }
  }).onOk(saveFinalOrder)
}

const saveFinalOrder = async (payloadFinal) => {
  let [startHour, endHour] = payloadFinal.slot.value.split('-')

  startHour = String(startHour).padStart(2, '0')
  endHour = String(endHour).padStart(2, '0')

  const payload = {
    client_id: user.user.client.id,
    address_id: address.value?.id,
    quantity: quantity.value,
    date: payloadFinal.date,
    period_type: String(payloadFinal.serviceType.hoursCount),
    start_time: `${startHour}:00`,
    end_time: `${endHour}:00`,
    address_type: selectedOption.value,
    service_type_id: selectedServiceType.value,
    description: description.value,
    min_price: priceRange.value.min,
    max_price: priceRange.value.max,
    offers_meal: payloadFinal.meal === 'offer',
    speciality_ids: selectedSpecialties.value
  }

  await createCustomSchedule(payload)

  $q.notify({
    type: 'positive',
    message: t('sob_medida.success_message')
  })

  router.push('/#showSuccessModal')
}

const increaseQuantity = () => {
  quantity.value++
}

const decreaseQuantity = () => {
  if (quantity.value > 1) quantity.value--
}

const dateOptions = (d) => {
  const today = date.formatDate(new Date(), 'YYYY/MM/DD')
  return d >= today
}

watch(selectedDate, (newDate, oldDate) => {
  if (!newDate || newDate === oldDate) return
  openServiceSelection()
})

onMounted(async () => {
  const { data } = await getPrimaryAddress(user.user.client.id, 'client')
  address.value = data.payload

  serviceTypes.value = await getPublicServiceTypes()
  specialties.value = await getPublicSpecialties()
})
</script>

<style scoped lang="scss">
.sob-medida-page {
  background: #f6f5fb;
  min-height: 100vh;
  padding: 16px;
}

.page-shell {
  max-width: 420px;
  margin: 0 auto;
}

.page-title {
  display: block;
  text-align: center;
  margin: 0 0 20px;
  width: 100%;
  margin-top: 16px;
}

.address-type-grid {
  display: grid;
  grid-template-columns: repeat(2, 120px);
  gap: 20px;
  justify-content: center;
  margin-bottom: 16px;
}

.address-type-grid .option-col {
  width: 100%;
  display: flex;
  justify-content: flex-start;
}

.figma-card {
  background: #fff;
  padding: 18px;
  margin-bottom: 20px;
  box-shadow: none;
}

.card-title,
.section-title {
  color: #7b61ff;
  margin-bottom: 16px;
  margin-left: 16px;
  margin-right: 16px;
}

.options-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px 20px;
  margin-bottom: 12px;
  width: 100%;

  :deep(.q-radio__label),
  :deep(.q-checkbox__label) {
    color: #000 !important;
    line-height: 20px;
    white-space: normal;
  }

  :deep(.q-checkbox__inner),
  :deep(.q-radio__inner) {
    color: #a78bfa !important;
  }
}

.section-title {
  margin-left: 16px;
}

.field-label {
  color: #7b61ff;
  margin: 18px 0 10px;
}

.optional {
  color: #9e9e9e;
}



.option-col {
  min-width: 0;
  width: 100%;
  display: flex;
  justify-content: flex-start;
}

.description-box {
  margin-top: 8px;
}

.description-box :deep(textarea) {
  min-height: 90px;
  resize: none;
}

.compact-card {
  padding: 28px 22px;
  background: #fafafa;
  box-shadow: 0 4px 14px rgba(0, 0, 0, 0.06);
}

.date-card {
  display: flex;
  justify-content: center;
  align-items: center;
  width: fit-content;
  min-width: 320px;
  max-width: 360px;
  margin: 0 auto 20px;
  padding: 20px;
  border-radius: 24px;
  background: #fff;
}

.calendar-custom {
  border-radius: 20px;
  overflow: hidden;
  background: white;
  margin: 16px 20px;
}


.range-container {
  position: relative;
  padding-top: 58px;
  padding-left: 10px;
  padding-right: 10px;
}

.price-pin {
  position: absolute;
  top: 0;
  width: 46px;
  height: 46px;
  background: linear-gradient(180deg, #8b7cff, #6f57db);
  border-radius: 50% 50% 50% 0;
  transform: translateX(-50%) rotate(-45deg);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 6px 14px rgba(111, 87, 219, 0.28);
  z-index: 5;
}

.price-pin span {
  transform: rotate(45deg);
  color: #fff;
}

.price-range {
  padding: 8px 0 0;
}

.price-range :deep(.q-slider__track-container) {
  height: 6px;
  border-radius: 30px;
  background: #ddd7ea;
}

.price-range :deep(.q-slider__track) {
  height: 6px;
  border-radius: 30px;
  background: linear-gradient(90deg, #d95cff, #7a5cff);
}

.price-range :deep(.q-slider__thumb) {
  width: 24px;
  height: 24px;
  min-width: 24px;
  min-height: 24px;
  border-radius: 50%;
  background: #7a5cff !important;
  border: 4px solid #ffffff;
  box-shadow: none;
}

.price-range :deep(.q-slider__thumb-shape) {
  display: none;
}

.price-range :deep(.q-slider__focus-ring) {
  display: none;
}

.range-helper {
  margin-top: 18px;
  line-height: 1.45;
  text-align: center;
  color: #6b6b6b;
}

.price-preview-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
  margin-top: 18px;
}

.price-preview-col {
  min-width: 0;
  text-align: center;
}

.price-preview-label {
  margin-bottom: 6px;
  color: #4a4a4a;
}

.price-preview-box {
  padding: 8px 4px;
  border: 1px solid #e2dcf0;
  border-radius: 12px;
  background: #fff;
  line-height: 1.35;
  color: #7a5cff;
}

.price-pin,
.price-range :deep(.q-slider__thumb) {
  transition:
    background 0.25s ease,
    box-shadow 0.25s ease,
    filter 0.25s ease;
}

.quantity-stepper {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 18px;
  margin: 12px 0 20px;
}

.quantity-btn {
  background: #f5f0ff;
  color: #7b61ff;
  width: 28px;
  height: 28px;
}

.quantity-value {
  min-width: 40px;
  text-align: center;
}

.service-type-inline {
  display: grid;
  grid-template-columns: repeat(2, minmax(110px, 130px));
  gap: 12px 28px;
  justify-content: center;
  margin-bottom: 16px;
}


.specialties-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(120px, 140px));
  gap: 12px 24px;
  justify-content: center;
  margin-bottom: 16px;
}

.specialty-col {
  width: 100%;
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;
}

.specialties-grid :deep(.q-checkbox) {
  width: 100%;
  margin: 0;
  justify-content: flex-start;
}

.specialties-grid :deep(.q-checkbox__inner) {
  margin-top: 1px;
}

.specialties-grid :deep(.q-checkbox__label) {
  color: #000 !important;
  line-height: 18px;
  white-space: normal;
  padding-left: 4px;
}

.price-pin:hover {
  background: linear-gradient(180deg, #7b68ff, #5f46d8);
  box-shadow: none;
}

.price-pin:active {
  background: linear-gradient(180deg, #6d52ff, #5438d6);
  box-shadow: none;
}

.price-range :deep(.q-slider__thumb:hover) {
  background: #6d52ff !important;
  box-shadow: 0 0 0 18px rgba(109, 82, 255, 0.22);
}

.price-range :deep(.q-slider__thumb:active) {
  background: #5e3fff !important;
  box-shadow: 0 0 0 22px rgba(94, 63, 255, 0.28);
}

.price-range:hover :deep(.q-slider__track) {
  filter: brightness(0.95);
}

.calendar-custom {
  :deep(.q-date) {
    background: white;
    width: 100%;
  }

  :deep(.q-date__calendar-item--out) {
    color: #CBD5E1 !important;
    opacity: 1 !important;
  }

  :deep(.q-date__calendar-item--passive) {
    color: #CBD5E1 !important;
    opacity: 1 !important;
  }

  :deep(.q-date__calendar-days .q-btn.disabled .q-btn__content),
  :deep(.q-date__calendar-days .q-btn[disabled] .q-btn__content) {
    color: #CBD5E1 !important;
    opacity: 1 !important;
  }

  :deep(.q-date__calendar-days .q-btn.disabled),
  :deep(.q-date__calendar-days .q-btn[disabled]) {
    opacity: 1 !important;
  }

  :deep(.q-date__calendar-days .q-btn__content) {
    font-weight: 500;
    color: #1E293B !important;
  }

  :deep(.q-date__calendar-weekdays > div) {
    color: #6366F1;
    font-weight: 700;
    opacity: 0.8;
  }

  :deep(.q-date__navigation) {
    .q-btn { color: #6366F1 !important; }
    .q-btn__content { color: #6366F1 !important; }
  }

  :deep(.q-date__event) {
    bottom: 4px;
    height: 6px;
    width: 6px;
    border-radius: 50%;
  }

  :deep(.q-date__today) {
    .q-btn__content {
      color: #7c4dff !important;
      background: #7c4dff15;
      border-radius: 50%;
    }
  }

  :deep(.q-date__selected) {
    .q-btn__content {
      background: #6366F1 !important;
      color: white !important;
      border-radius: 50%;
      box-shadow: 0 4px 10px rgba(99, 102, 241, 0.4);
    }
  }

  :deep(.q-date__view--months .q-btn),
  :deep(.q-date__view--years .q-btn) {
    color: #6366F1 !important;
  }
}


/* labels pretas */
:deep(.q-radio__label),
:deep(.q-checkbox__label) {
  color: #000 !important;
}

:deep(.q-checkbox__inner),
:deep(.q-radio__inner) {
  color: #a78bfa !important;
}

@media (max-width: 480px) {
  .page-shell {
    max-width: 100%;
  }

  .figma-card {
    padding: 16px;
  }

  .figma-date {
    max-width: 100%;
  }
}

@media (min-width: 768px) {
  .page-shell {
    max-width: 460px;
  }
}
</style>
