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

      <q-card-section class="column items-center q-pt-lg q-pb-sm">
        <q-avatar size="80px" :style="avatarStyle" class="text-h5 q-mb-sm">
          {{ schedule.provider_name?.slice(0, 2).toUpperCase() ?? '??' }}
        </q-avatar>

        <div class="font16 fontbold provider-name">
          {{ schedule.provider_name }}
        </div>

        <div class="font14 fontmedium text-text">
          {{ schedule.address?.district || '' }}
        </div>
      </q-card-section>

      <q-card-section class="text-center q-pt-xs q-pb-md">
        <div class="accepted-title font16 fontbold">
          {{ $t('dashboard_client.pending_schedules.accepted_title') }}
        </div>
      </q-card-section>

      <q-separator />

      <q-card-section class="q-py-md q-px-lg">
        <div class="detail-row">
          <span class="text-primary font14 fontmedium">
            {{ $t('dashboard_client.pending_schedules.detail_date') }}
          </span>

          <span class="detail-value">
            {{ formattedDate }}
          </span>
        </div>
        <div class="detail-row">
          <span class="text-primary font14 fontmedium">
            {{ $t('dashboard_client.pending_schedules.detail_time') }}
          </span>

          <span class="detail-valued text-text">
            {{ schedule.start_time?.slice(0, 5) }} {{ $t('dashboard_client.next_schedules.to') }} {{ schedule.end_time?.slice(0, 5) }}
          </span>
        </div>

        <div v-if="hasCartDiscount" class="detail-row">
          <span class="text-primary font14 fontmedium">
            {{ $t('dashboard_client.pending_schedules.detail_total') }}
          </span>

          <span class="total-value font14 fontbold">
            {{ formatCurrency(pixTotal) }}
          </span>
        </div>

        <div v-if="!hasCartDiscount" class="detail-row">
          <span class="text-primary font14 fontmedium">
            {{ $t('dashboard_client.pending_schedules.detail_pix_total') }}
          </span>

          <span class="total-value font14 fontbold">
            {{ formatCurrency(pixTotal) }}
          </span>
        </div>

        <div v-if="!hasCartDiscount && pixDiscount > 0" class="detail-row discount-row">
          <span class="font13 fontmedium">
            {{ $t('dashboard_client.pending_schedules.detail_pix_discount') }}
          </span>

          <span class="font13 fontbold">
            {{ formatCurrency(pixDiscount) }}
          </span>
        </div>

        <div v-if="!hasCartDiscount" class="detail-row">
          <span class="text-primary font14 fontmedium">
            {{ $t('dashboard_client.pending_schedules.detail_credit_card_total') }}
          </span>

          <span class="total-value font14 fontbold">
            {{ formatCurrency(creditCardTotal) }}
          </span>
        </div>
      </q-card-section>

      <q-card-section class="q-pt-none q-pb-lg q-px-lg column q-gutter-y-sm">
        <q-btn
          class="payment-btn full-width"
          color="primary"
          padding="4px 12px"
          rounded
          :label="$t('dashboard_client.pending_schedules.btn_payment')"
          @click="onGoToPayment"
        />

        <q-btn
          class="full-width"
          color="grey-6"
          flat
          no-caps
          padding="4px 12px"
          :label="$t('dashboard_client.pending_schedules.btn_cancel')"
          @click="onDialogHide"
        />
      </q-card-section>

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

<script setup>
import { computed, onMounted } from 'vue'
import { formatCurrency } from 'src/helpers/utils'
import { getSchedulePlatformFeeRate, scheduleUsesCartDiscount } from 'src/helpers/paymentPlatformFees'
import { useDialogPluginComponent, useQuasar } from 'quasar'
import { usePaymentStore } from 'src/stores/payment'
import { usePaymentPlatformFees } from 'src/composables/usePaymentPlatformFees'
import SchedulePaymentDialog from './SchedulePaymentDialog.vue'
import SchedulePaymentPixDialog from './SchedulePaymentPixDialog.vue'

const props = defineProps({
  schedule: { type: Object, required: true }
})

defineEmits([...useDialogPluginComponent.emits])

const { dialogRef, onDialogHide, onDialogOK } = useDialogPluginComponent()

const $q = useQuasar()

const paymentStore = usePaymentStore()

const { platformFees, loadPlatformFees } = usePaymentPlatformFees()

const baseAmount = computed(() => Number(props.schedule.total_amount) || 0)

const creditCardTotal = computed(() => parseFloat((baseAmount.value + platformFee('credit_card')).toFixed(2)))

const hasCartDiscount = computed(() => scheduleUsesCartDiscount(props.schedule))

const formattedDate = computed(() => {
  if (props.schedule.formatted_date) return props.schedule.formatted_date

  const raw = String(props.schedule.date || '')

  const m = raw.match(/^(\d{4})-(\d{2})-(\d{2})/)

  if (!m) return raw

  const d = new Date(+m[1], +m[2] - 1, +m[3])

  return d.toLocaleDateString('pt-BR', { day: '2-digit', month: 'long', year: 'numeric' })
})

const pixDiscount = computed(() => Math.max(0, parseFloat((creditCardTotal.value - pixTotal.value).toFixed(2))))
const pixTotal    = computed(() => parseFloat((baseAmount.value + platformFee('pix')).toFixed(2)))

const platformFee = (paymentType) => {
  const feeRate = getSchedulePlatformFeeRate(props.schedule, paymentType, platformFees.value)

  return parseFloat((baseAmount.value * (feeRate ?? 0)).toFixed(2))
}

const onGoToPayment = () => {
  const hasValidPixPayment = !!paymentStore.getValidPixPayment(props.schedule.id)

  $q.dialog({
    component: hasValidPixPayment ? SchedulePaymentPixDialog : SchedulePaymentDialog,
    componentProps: {
      schedule: props.schedule, ...(hasValidPixPayment ? { total: pixTotal.value } : {}),
    },
  }).onOk(() => {
    onDialogOK()
  })
}

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

const avatarStyle = computed(() => avatarColors[props.schedule.id % avatarColors.length])

onMounted(() => {
  loadPlatformFees().catch(() => {})
})
</script>

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

.accepted-title {
  line-height: 1.3;
  color: #8B5CF6;
}

.provider-name {
  color: #8B5CF6;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
}

.detail-label {
  color: #8a8a9a;
}

.detail-value {
  color: #3a3a4a;
}

.total-value {
  color: #3a3a4a;
}

.discount-row {
  color: #16845d;
  background: rgba(22, 132, 93, 0.08);
  border-radius: 8px;
  margin: 2px 0;
  padding: 5px 8px;
}

.payment-btn {
  height: 48px;
}
</style>
