<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card class="solicitation-dialog-card bg-surface shadow-card" :flat="false">

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

        <q-card-section class="column items-center q-pt-xs q-pb-xs">
          <q-avatar size="72px" class="q-mb-sm">
            <img v-if="solicitation.customer_photo" :src="solicitation.customer_photo" style="object-fit:cover" />
            <span v-else class="text-weight-bold full-width full-height flex flex-center" :style="avatarColors[solicitation.id % avatarColors.length]" style="font-size:20px;border-radius:50%">{{ solicitation.client_name?.slice(0,2).toUpperCase() ?? '??' }}</span>
          </q-avatar>
          <div class="text-subtitle1 text-weight-bold text-text">
            {{ solicitation.client_name }}
          </div>
          <div v-if="solicitation.address?.district" class="text-caption text-grey-6 q-mt-xs">
            {{ solicitation.address.district }}
          </div>
          <div v-if="solicitation.address" class="text-caption text-grey-5 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
              :name="service.active ? 'mdi-check' : 'mdi-close'"
              :color="service.active ? 'secondary' : 'grey-4'"
              size="16px"
            />
            <span class="text-body2 text-grey-8">{{ 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="detail-label text-secondary text-weight-bold">{{ $t('common.terms.date') }}</span>
            <span class="detail-value text-grey-9">{{ fullDateLabel }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label text-secondary text-weight-bold">{{ $t('common.terms.hour') }}</span>
            <span class="detail-value text-grey-9">
              {{ solicitation.start_time?.slice(0, 5) }} {{ $t('common.to') }} {{ solicitation.end_time?.slice(0, 5) }}
            </span>
          </div>
          <div class="detail-row">
            <span class="detail-label text-secondary text-weight-bold">{{ $t('common.terms.total_amount') }}</span>
            <span class="detail-value text-grey-9">{{ formatCurrency(baseAmount) }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label text-secondary text-weight-bold">{{ $t('provider.dashboard.cancel_schedule.service_fee') }}</span>
            <span class="detail-value text-grey-9">{{ 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-weight-bold text-grey-9">{{ $t('provider.dashboard.cancel_schedule.total') }}</span>
          <span class="total-value text-secondary text-weight-bold q-ml-xs">{{ formatCurrency(solicitation.total_amount) }}</span>
        </q-card-section>

        <q-card-section class="q-pt-none q-pb-xs q-px-lg">
          <q-btn
            unelevated
            rounded
            no-caps
            color="secondary"
            class="full-width btn-close-paid"
            :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
              flat
              no-caps
              color="grey-7"
              size="sm"
              :label="$t('provider.dashboard.cancel_schedule.btn_cancel_order')"
              @click="openCancelDialog"
            />
            <q-btn
              flat
              no-caps
              color="grey-7"
              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 flat round dense icon="close" color="grey-6" size="sm" @click="onDialogCancel" />
        </div>

        <q-card-section class="column items-center q-pt-sm q-pb-sm">
          <q-avatar size="72px" class="q-mb-sm">
            <img v-if="solicitation.customer_photo" :src="solicitation.customer_photo" style="object-fit:cover" />
            <span v-else class="text-weight-bold full-width full-height flex flex-center" :style="avatarColors[solicitation.id % avatarColors.length]" style="font-size:20px;border-radius:50%">{{ solicitation.client_name?.slice(0,2).toUpperCase() ?? '??' }}</span>
          </q-avatar>

          <div class="text-subtitle1 text-weight-bold text-text">{{ solicitation.client_name }}</div>

          <div class="text-price q-mt-xs">{{ formatCurrency(solicitation.total_amount) }}</div>
          <div class="text-caption text-grey-6">{{ periodLabel }}</div>
        </q-card-section>

        <q-card-section class="column items-center q-pt-none q-pb-sm text-text">
          <div class="text-body2 text-center">
            <span class="text-weight-bold">{{ weekdayLabel + ' ,' + dayMonthLabel }}</span>
          </div>
          <div class="text-body2 text-center">
            {{ $t('common.from') }} <strong>{{ solicitation.start_time?.slice(0, 5) }}</strong>
            {{ $t('common.to') }} <strong>{{ solicitation.end_time?.slice(0, 5) }}</strong>
          </div>
        </q-card-section>

        <q-card-section class="column items-center q-pt-none q-pb-xs">
          <div class="row items-center q-gutter-x-xs">
            <q-icon
              :name="solicitation.offers_meal ? 'mdi-food' : 'mdi-food-off'"
              :color="solicitation.offers_meal ? 'positive' : 'grey-5'"
              size="18px"
            />
            <span class="text-body2 text-grey-7">
              {{ solicitation.offers_meal
                ? $t('provider.dashboard.solicitations.offers_meal')
                : $t('provider.dashboard.solicitations.not_offers_meal') }}
            </span>
          </div>
        </q-card-section>

        <q-card-section class="column items-center q-pt-xs q-pb-sm text-text">
          <div class="row items-center q-gutter-x-xs">
            <q-icon name="mdi-map-marker" color="secondary" size="20px" />
            <span class="text-body1 text-weight-bold">{{ solicitation.address?.district || 'N/A' }}</span>
          </div>
          <div class="text-caption text-grey-6 text-center 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">
            <span class="text-caption text-grey-6">{{ $t('provider.dashboard.solicitations.via_agenda_text') }} </span>
            <span class="text-caption text-secondary text-weight-bold">{{ ' ' + $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
              unelevated
              rounded
              no-caps
              class="btn-action bg-grey-3 text-grey-8"
              :label="$t('common.refuse')"
              @click="view = 'confirm-reject'"
            />
            <q-btn
              unelevated
              rounded
              no-caps
              color="secondary"
              class="btn-action"
              :label="$t('common.accept')"
              @click="view = 'confirm-accept'"
            />
          </div>
          <div class="row justify-center q-mt-xs">
            <q-btn flat no-caps color="grey-7" size="sm" :label="$t('common.actions.back')" @click="onDialogCancel" />
          </div>
        </q-card-section>

        <div class="q-pa-md">
          <span class="text-caption text-warning text-weight-bold">{{ $t('provider.dashboard.solicitations.same_day_warning_label') }} </span>
          <span class="text-caption text-grey-8">{{ $t('provider.dashboard.solicitations.same_day_warning') }}</span>
        </div>
      </template>

      <template v-else-if="view === 'confirm-accept'">
        <q-card-section class="column items-center q-pt-xl q-pb-lg text-center">
          <div class="confirm-title text-secondary text-weight-bold">
            {{ $t('provider.dashboard.solicitations.confirm_accept') }}
          </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
              unelevated
              rounded
              no-caps
              color="purple-5"
              class="btn-action"
              :label="$t('common.actions.back')"
              @click="backFromConfirm"
            />
            <q-btn
              unelevated
              rounded
              no-caps
              color="secondary"
              class="btn-action"
              :loading="loading"
              :label="$t('common.accept')"
              @click="confirmAccept"
            />
          </div>
        </q-card-section>
      </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 text-weight-bold">
            {{ $t('provider.dashboard.solicitations.confirm_reject') }}
          </div>
          <div class="q-mt-md text-body2 text-grey-7 confirm-tip">
            <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
              unelevated
              rounded
              no-caps
              color="purple-5"
              class="btn-action"
              :label="$t('common.actions.back')"
              @click="backFromConfirm"
            />
            <q-btn
              unelevated
              rounded
              no-caps
              color="secondary"
              class="btn-action"
              :loading="loading"
              :label="$t('common.refuse')"
              @click="confirmReject"
            />
          </div>
        </q-card-section>
      </template>

    </q-card>
  </q-dialog>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useDialogPluginComponent, useQuasar } from 'quasar'
import { useI18n } from 'vue-i18n'
import { formatCurrency } from 'src/helpers/utils'
import { labelsPeriodTypes } from 'src/helpers/arraysOptions/labelsPeriodTypes.js'
import ScheduleCancelDialog from './ScheduleCancelDialog.vue'

const avatarColors = [
  { background: '#ffd5df', color: '#932e57' },
  { background: '#d7e8ff', color: '#2158a8' },
  { background: '#dfd',    color: '#2a7a3b' },
  { background: '#ffe5cc', color: '#8a4500' },
];

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

const { t } = useI18n()
const $q = useQuasar()
const { dialogRef, onDialogHide, onDialogCancel, onDialogOK } = useDialogPluginComponent()

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

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

const periodLabel = computed(() => {
  const found = labelsPeriodTypes.find(l => l.value == props.solicitation.period_type)
  return found ? t(found.label) : ''
})

const parseLocalDate = (dateStr) => {
  if (!dateStr) return null
  const s = String(dateStr)
  const iso = s.match(/^(\d{4})-(\d{2})-(\d{2})/)
  if (iso) return new Date(+iso[1], +iso[2] - 1, +iso[3])
  const dmy = s.match(/^(\d{2})\/(\d{2})\/(\d{4})/)
  if (dmy) return new Date(+dmy[3], +dmy[2] - 1, +dmy[1])
  return null
}

const weekdayLabel = computed(() => {
  const d = parseLocalDate(props.solicitation.date)
  if (!d) return ''
  const w = d.toLocaleDateString('pt-BR', { weekday: 'long' })
  return w.charAt(0).toUpperCase() + w.slice(1)
})

const dayMonthLabel = computed(() => {
  const d = parseLocalDate(props.solicitation.date)
  if (!d) return ''
  return d.toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit' })
})

const fullDateLabel = computed(() => {
  const d = parseLocalDate(props.solicitation.date)
  if (!d) return ''
  return d.toLocaleDateString('pt-BR', { day: '2-digit', month: 'long', year: 'numeric' })
})

const SERVICE_FEE_RATE = 0.11

const serviceFee = computed(() => {
  const total = parseFloat(props.solicitation.total_amount) || 0
  return parseFloat((total * SERVICE_FEE_RATE).toFixed(2))
})
const baseAmount = computed(() => {
  const total = parseFloat(props.solicitation.total_amount) || 0
  return parseFloat((total - serviceFee.value).toFixed(2))
})

const servicesList = computed(() => {
  const list = []
  const s = props.solicitation
  if (s.schedule_type === 'custom' && s.specialities?.length) {
    s.specialities.forEach(sp => list.push({ label: sp.name, active: true }))
  }
  if (s.offers_meal !== undefined) {
    list.push({
      label: s.offers_meal
        ? t('provider.dashboard.solicitations.offers_meal')
        : t('provider.dashboard.solicitations.not_offers_meal'),
      active: !!s.offers_meal
    })
  }
  if (!list.length) {
    list.push({ label: t('provider.dashboard.next_schedules.default'), active: true })
  }
  return list
})

const formatAddressShort = (addr) => {
  if (!addr) return ''
  const parts = [addr.address, addr.number].filter(Boolean)
  const street = parts.join(', ')
  const suffix = addr.district ? `, ${addr.district}` : ''
  return street + suffix
}

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

const confirmAccept = () => {
  loading.value = true
  onDialogOK({ action: 'accept', id: props.solicitation.id })
}

const confirmReject = () => {
  loading.value = true
  onDialogOK({ action: 'reject', id: props.solicitation.id })
}

const openCancelDialog = () => {
  $q.dialog({
    component: ScheduleCancelDialog,
    componentProps: { schedule: props.solicitation }
  }).onOk(() => {
    onDialogOK({ action: 'cancelled', id: props.solicitation.id })
  })
}
</script>

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

.text-price {
  font-size: 24px;
  font-weight: 700;
  color: var(--q-secondary);
}

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

.btn-close-paid {
  font-weight: 700;
  font-size: 16px;
  padding: 10px 0;
}

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

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

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

.detail-label {
  font-size: 12px;
  font-weight: 600;
}

.detail-value {
  font-size: 13px;
}

.total-value {
  font-size: 22px;
}
</style>
