<template>
  <q-dialog
    ref="dialogRef"
    maximized
    transition-hide="slide-down"
    transition-show="slide-up"
  >
    <div
      v-if="details"
      class="bg-surface details-page"
    >
      <!-- HEADER -->
      <div class="page-header">
        <q-btn
          class="back-btn"
          dense
          flat
          icon="chevron_left"
          round
          @click="goBack"
        />

        <div class="font16 fontbold gradient-diarista">
          {{ $t('provider.dashboard.opportunity_details.title') }}
        </div>
      </div>

      <!-- CLIENTE -->
      <div class="client-section">
        <q-avatar
          class="q-mb-sm"
          size="90px"
        >
          <img
            v-if="details.schedule?.customer_photo"
            :src="details.schedule.customer_photo"
            style="object-fit: cover"
          />

          <span
            v-else
            class="flex flex-center fontbold full-height full-width"
            :style="[
              avatarColors[
                details.schedule?.client_id % avatarColors.length
              ],
              { borderRadius: '50%' }
            ]"
          >
            {{
              details.schedule?.client_name
                ?.slice(0, 2)
                .toUpperCase() ?? '??'
            }}
          </span>
        </q-avatar>

        <div class="client-name font16 fontmedium">
          {{ details.schedule?.client_name }}
        </div>

        <div class="client-price fontbold q-pt-md text-primary">
          {{ $t('provider.dashboard.opportunities.currency', {value: choosePrice(details.schedule?.period_type)}) }}
        </div>

        <div class="font10 fontmedium text-grey-6">
          {{ periodTypeLabel }}
        </div>

        <div class="date font11">
          <span class="fontbold">
            {{ formatWeekday(details.schedule?.date) }}
          </span>

          <span>
            {{ `, ${formatDayMonth(details.schedule?.date)}` }}
          </span>
        </div>

        <div class="font11 hour">
          {{ $t('common.from') }}

          <span class="fontbold">
            {{ formatHour(details.schedule?.start_time) }}
            {{ $t('common.to') }}
            {{ formatHour(details.schedule?.end_time) }}
          </span>
        </div>
      </div>

      <!-- ENDEREÇO -->
      <div class="address font14 fontbold">
        <q-icon
          class="gradient-diarista"
          name="place"
          size="16px"
        />

        {{ details.schedule?.address?.district }}
      </div>

      <div class="distance font12 fontbold">
        {{ $t('provider.dashboard.opportunity_details.distance_text', { distance: distanceKm ?? 0 }) }}
      </div>

      <!-- TAGS -->
      <div
        v-if="details.tags?.length"
        class="tags-row"
      >
        <q-chip
          v-for="(tag, index) in details.tags"
          :key="index"
          class="chip"
          outline
        >
          {{ tag }}
        </q-chip>
      </div>

      <!-- INFO -->
      <div class="font12 fontbold service-type">
        {{ $t('provider.dashboard.opportunity_details.sob_medida') }}

        <span>
          {{ $t('provider.dashboard.opportunity_details.sob_medida_highlight') }}
        </span>

        <br />

        {{ $t('provider.dashboard.opportunity_details.para') }}

        <strong class="highlight-service">
          {{ details.service_type_name }}
        </strong>
      </div>

      <div class="address-type">
        <q-chip
          class="font11 items-center"
          color="primary"
          outline
        >
          <q-icon
            class="q-mr-xs"
            size="14px"
            :name="addressIcon(details.address_type)"
          />

          {{ addressLabel(details.address_type) }}
        </q-chip>

        <q-chip
          class="font11 items-center"
          outline
          :color="details.offers_meal ? 'primary' : 'grey-5'"
        >
          <q-icon
            class="q-mr-xs"
            size="14px"
            :color="details.offers_meal ? 'primary' : 'grey-5'"
            :name="
              details.offers_meal
                ? 'mdi-silverware'
                : 'mdi-close-circle-outline'
            "
          />

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

      <!-- INFO TITLE -->
      <div
        v-if="details.description"
        class="font16 fontbold gradient-diarista text-center"
      >
        {{ $t('provider.dashboard.opportunity_details.info_title') }}
      </div>

      <!-- DESCRIÇÃO -->
      <div class="description-box font12">
        {{ details.description }}
      </div>

      <!-- BOTÃO -->
      <div class="q-px-md text-center">
        <q-btn
          class="font11 fontsemibold full-width"
          color="primary"
          no-caps
          rounded
          unelevated
          :label="
            $t('provider.dashboard.opportunity_details.button_accept')
          "
          @click="goToProposalFlow"
        />
      </div>

      <div class="q-px-md">
        <q-btn
          class="refuse-btn font11 fontsemibold full-width"
          flat
          label="Recusar oportunidade"
          no-caps
          rounded
          @click="openRefuseDialog"
        />

        <!-- ALERTA -->
        <div class="alert-box font12">
          <q-icon
            class="alert-icon"
            name="warning"
            size="18px"
          />

          <span class="alert-text">
            {{ $t('provider.dashboard.opportunity_details.alert_text') }}
          </span>
        </div>
      </div>
    </div>
  </q-dialog>
</template>

<script setup>
import { Dialog, useDialogPluginComponent } from 'quasar'

import {
  getOpportunityById,
  proposalOpportunity
} from 'src/api/opportunities'

import { avatarColors } from 'src/helpers/utils'
import { labelsPeriodTypes } from 'src/helpers/labelsPeriodTypes.js'
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { userStore } from 'src/stores/user'

import RefuseOpportunityDialog from './RefuseOpportunityDialog.vue'

const props = defineProps({
  distanceKm: {
    type: Number,
    default: null
  },
  opportunityId: {
    type: Number,
    required: true
  }
})

defineEmits([
  ...useDialogPluginComponent.emits
])

const {
  dialogRef,
  onDialogOK
} = useDialogPluginComponent()

const router = useRouter()
const { t } = useI18n()

const user = userStore()

const details = ref(null)
const loading = ref(true)

const periodTypeLabel = computed(() => {
  const periodType = labelsPeriodTypes.find(
    (item) => item.value === Number(details.value?.schedule?.period_type)
  )

  return periodType ? t(periodType.label) : ''
})



const choosePrice = (periodType) => {
  switch (periodType) {
    case '8':
      return user.user.provider_daily_price_8h

    case '6':
      return user.user.provider_daily_price_6h

    case '4':
      return user.user.provider_daily_price_4h

    case '2':
      return user.user.provider_daily_price_2h

    default:
      return 0
  }
}

//

// A data vem do backend no formato DD/MM/YYYY.
const parseLocalDate = (date) => {
  if (!date) {
    return null
  }

  const match = String(date).match(
    /^(\d{2})\/(\d{2})\/(\d{4})$/
  )

  if (!match) {
    return null
  }

  return new Date(
    Number(match[3]),
    Number(match[2]) - 1,
    Number(match[1])
  )
}

const formatDayMonth = (date) => {
  const parsedDate = parseLocalDate(date)

  if (!parsedDate) {
    return ''
  }

  return parsedDate.toLocaleDateString('pt-BR', {
    day: '2-digit',
    month: '2-digit'
  })
}

const formatHour = (time) => {
  if (!time) {
    return ''
  }

  return time.slice(0, 5)
}

const formatWeekday = (date) => {
  const parsedDate = parseLocalDate(date)

  if (!parsedDate) {
    return ''
  }

  const weekday = parsedDate.toLocaleDateString('pt-BR', {
    weekday: 'long'
  })

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

//

const addressIcon = (type) => {
  if (type === 'home') {
    return 'mdi-home-outline'
  }

  if (type === 'apartment') {
    return 'mdi-domain'
  }

  return 'mdi-office-building-outline'
}

const addressLabel = (type) => {
  if (type === 'home') {
    return t('provider.dashboard.next_schedules.place_home')
  }

  if (type === 'apartment') {
    return t('provider.dashboard.next_schedules.place_apartment')
  }

  if (type === 'commercial') {
    return t('provider.dashboard.next_schedules.place_commercial')
  }

  return t('provider.dashboard.next_schedules.place_unknown')
}

const goBack = () => {
  onDialogOK()
}

const goToProposalFlow = async () => {
  await proposalOpportunity(
    details.value.schedule_id,
    user.user.provider.id
  )

  await router.push({
    name: 'DashboardPage',
    query: {
      showSuccessModal: 'true'
    }
  })

  onDialogOK()
}

// Dialog de recusar oportunidade.
const openRefuseDialog = () => {
  Dialog.create({
    component: RefuseOpportunityDialog,

    componentProps: {
      opportunityId: details.value.schedule_id,
      providerId: user.user.provider.id
    }
  }).onOk(() => {
    window.location.reload()
  })
}

onMounted(async () => {
  try {
    const response = await getOpportunityById(
      props.opportunityId
    )

    if (response) {
      details.value = response
      return
    }

    console.warn('Nenhum dado retornado')
  } catch (error) {
    console.error('Erro ao carregar detalhes:', error)
  } finally {
    loading.value = false
  }
})
</script>

<style scoped lang="scss">
.details-page {
  min-height: 100vh;
}

/* HEADER */
.page-header {
  position: relative;
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 14px 16px;
  padding-top: calc(env(safe-area-inset-top, 24px) + 14px);
  margin-bottom: 16px;
  background: #fff;
  border-radius: 0 0 16px 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.back-btn {
  position: absolute;
  top: 50%;
  left: 8px;
  color: #7c5cff;
  transform: translateY(-50%);
}

/* CLIENTE */
.client-section {
  margin-top: 10px;
  text-align: center;
}

.client-avatar {
  width: 90px;
  height: 90px;
  margin-bottom: 10px;
  object-fit: cover;
  border-radius: 50%;
}

.client-name {
  color: #444;
}

.rating {
  margin-left: 4px;
  color: #ffb800;
}

.client-price {
  font-size: 24px;
}

/* DATA */
.date {
  margin-top: 10px;
  color: #555;
}

.hour {
  margin-bottom: 10px;
  color: #777;
}

/* ENDEREÇO */
.address {
  display: flex;
  gap: 6px;
  align-items: center;
  justify-content: center;
  margin-top: 12px;
  color: #7c5cff;
}

.distance {
  margin-top: 4px;
  margin-bottom: 14px;
  color: #888;
  text-align: center;
}

/* TEXTO SOB MEDIDA */
.service-type {
  margin-top: 14px;
  color: #666;
  line-height: 1.5;
  text-align: center;
}

.service-type span {
  color: #7c5cff;
}

.highlight-service {
  color: #7c5cff;
}

/* CHIPS */
.address-type {
  display: flex;
  gap: 10px;
  justify-content: center;
  margin-top: 14px;
  margin-bottom: 14px;
}

.chip-type {
  padding: 6px 16px;
  color: #7c5cff;
  background: white;
  border: 1.5px solid #7c5cff;
  border-radius: 999px;
}

/* DESCRIÇÃO */
.description-box {
  padding: 0 10px;
  margin: 12px 0 24px;
  color: #666;
  line-height: 1.5;
  text-align: center;
}

/* ALERTA */
.alert-box {
  display: flex;
  gap: 8px;
  align-items: center;
  justify-content: center;
  padding: 12px;
  margin-top: 14px;
  color: #5c6b8a;
  text-align: center;
  background: #e9f0ff;
  border-radius: 14px;
}

.refuse-btn {
  width: 100%;
  margin-top: 12px;
  color: #ff4d67;
  border: 1px solid #ff4d67;
  border-radius: 28px;
}
</style>