<template>
  <q-dialog ref="dialogRef" persistent maximized transition-show="slide-up" transition-hide="slide-down" @hide="onDialogHide">
    <div class="bg-page full-height column">

      <div class="row items-center q-px-md q-pt-md q-pb-sm bg-surface shadow-header">
        <q-btn class="header-back-btn" icon="mdi-chevron-left" flat round dense color="primary" @click="onDialogCancel" />
        <q-space />
        <span class="font16 fontbold gradient-diarista">
          {{ $t('payment.title') }}
        </span>
        <q-space />
        <div style="width: 32px" />
      </div>

      <div class="col overflow-auto q-px-md q-pt-lg q-pb-xl">

        <div class="q-mb-sm text-text font14 fontbold">{{ $t('payment.schedule_address') }}</div>
        <div class="address-box row items-center no-wrap q-mb-lg">
          <div class="col">
            <div class="address-type-label fontbold">{{ addressTypeLabel }}</div>
            <div class="address-full-text text-grey-7">{{ addressFullText }}</div>
          </div>
          <q-icon name="mdi-chevron-down" color="grey-5" size="22px" />
        </div>

        <div class="text-text q-mb-sm font14 fontbold">{{ $t('payment.pay_with') }}</div>
        <div class="row q-gutter-sm q-mb-sm">

          <div
            class="payment-option-card col column items-center justify-center q-pa-md cursor-pointer"
            :class="{ 'payment-option-selected': selectedMethod === 'pix' }"
            @click="selectedMethod = 'pix'"
          >
            <span class="payment-option-title">{{ $t('payment.pix') }}</span>
            <q-icon name="mdi-cash-fast" size="32px" color="teal" class="q-mt-xs" />
          </div>

          <div
            class="payment-option-card col column items-center justify-center q-pa-md cursor-pointer"
            :class="{ 'payment-option-selected': selectedMethod === 'new_card' }"
            @click="openAddCard"
          >
            <span class="payment-option-title">{{ $t('payment.add_card') }}</span>
            <q-icon name="mdi-plus-circle-outline" size="22px" color="grey-5" class="q-mt-xs" />
            <span class="payment-option-sub">{{ $t('payment.credit_debit') }}</span>
          </div>

        </div>

        <div v-if="loadingCards" class="flex flex-center q-py-md">
          <q-spinner color="primary" size="2em" />
        </div>

        <div v-else-if="paymentMethods.length > 0" class="column q-gutter-y-sm q-mb-lg">
          <div
            v-for="card in paymentMethods"
            :key="card.id"
            class="saved-card-box row items-center no-wrap q-pa-md cursor-pointer"
            :class="{ 'payment-option-selected': selectedMethod === `card_${card.id}` }"
            @click="selectedMethod = `card_${card.id}`"
          >
            <div class="col column">
              <span class="card-titular-label">{{ $t('payment.card_holder') }}</span>
              <span class="card-holder-name text-text">{{ card.holder_name }}</span>
            </div>
            <div class="column items-end">
              <span class="card-brand-text">{{ brandDisplay(card.brand) }}</span>
              <span class="card-last-four">{{ '**** **** **** ' + card.last_four_digits }}</span>
              <span class="card-expiry-text">{{ card.expiration }}</span>
            </div>
          </div>
        </div>

        <q-separator class="q-my-lg" />

        <div class="payment-summary q-mb-lg">
          <div class="row items-center justify-between">
            <span class="summary-total-label">{{ $t('dashboard_client.pending_schedules.detail_total') }}</span>
            <span class="summary-total-value">{{ formatCurrency(selectedTotal) }}</span>
          </div>
        </div>

        <div class="row items-center q-mb-lg">
          <q-checkbox v-model="agreedToTerms" color="primary" keep-color />
          <span class="terms-text">
            {{ $t('payment.agree_prefix') }}
            <span class="text-primary cursor-pointer text-underline">{{ $t('payment.terms_link') }}</span>
          </span>
        </div>

        <q-btn
          unelevated
          rounded
          no-caps
          padding="8px 12px"
          color="primary"
          class="full-width"
          :label="$t('payment.confirm_btn')"
          :disable="!canConfirm"
          @click="onConfirm"
        />

      </div>
    </div>
  </q-dialog>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useDialogPluginComponent, useQuasar } from 'quasar'
import { useI18n } from 'vue-i18n'
import { userStore } from 'src/stores/user'
import { usePaymentStore } from 'src/stores/payment'
import { getClientPaymentMethods } from 'src/api/clientPaymentMethod'
import { formatCurrency } from 'src/helpers/utils'
import { getScheduleTotalWithPlatformFee } from 'src/helpers/paymentPlatformFees'
import { usePaymentPlatformFees } from 'src/composables/usePaymentPlatformFees'
import ProfilePaymentAddDialog from 'src/components/profile/ProfilePaymentAddDialog.vue'
import SchedulePaymentPixDialog from './SchedulePaymentPixDialog.vue'
import SchedulePaymentProcessingDialog from './SchedulePaymentProcessingDialog.vue'

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

defineEmits([...useDialogPluginComponent.emits])

const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } = useDialogPluginComponent()
const $q = useQuasar()
const { t } = useI18n()
const store = userStore()
const paymentStore = usePaymentStore()
const { platformFees, loadPlatformFees } = usePaymentPlatformFees()

const item = computed(() => props.servicePackage)

const selectedMethod = ref(null)
const agreedToTerms = ref(false)
const paymentMethods = ref([])
const loadingCards = ref(false)

const selectedPaymentType = computed(() => selectedMethod.value === 'pix' ? 'pix' : 'credit_card')
const selectedTotal = computed(() => getScheduleTotalWithPlatformFee(item.value, selectedPaymentType.value, platformFees.value))

const getAddress = () => {
  return item.value.schedules?.[0]?.address ?? item.value.address ?? null;
};

const addressTypeLabel = computed(() => {
  const addr = getAddress();
  const type = addr?.address_type;
  if (!type) return '';
  return t(`profile.address.type.${type}`, type);
});

const addressFullText = computed(() => {
  const a = getAddress();
  if (!a) return '';
  const parts = [a.address, a.number, a.district].filter(Boolean);
  return parts.join(', ');
});

const canConfirm = computed(() => selectedMethod.value !== null && agreedToTerms.value)

const brandDisplay = (brand) => {
  if (!brand) return ''
  const map = { visa: 'VISA', mastercard: 'Mastercard', elo: 'Elo', hipercard: 'Hipercard', diners: 'Diners', discover: 'Discover' }
  return map[brand] ?? brand.toUpperCase()
}

const loadCards = async () => {
  loadingCards.value = true
  try {
    paymentMethods.value = await getClientPaymentMethods(store.user?.client_id)
    const selectedCardId = String(selectedMethod.value || '').replace('card_', '')
    const hasSelectedCard = paymentMethods.value.some((card) => String(card.id) === selectedCardId)

    if (selectedMethod.value !== 'pix' && !hasSelectedCard) {
      selectedMethod.value = paymentMethods.value.length > 0 ? `card_${paymentMethods.value[0].id}` : 'pix'
    }
  } catch (e) {
    console.error(e)
  } finally {
    loadingCards.value = false
  }
}

const openAddCard = () => {
  $q.dialog({
    component: ProfilePaymentAddDialog,
    componentProps: { clientId: store.user?.client_id },
  }).onOk(() => {
    loadCards()
  })
}

const openPixPayment = () => {
  $q.dialog({
    component: SchedulePaymentPixDialog,
    componentProps: {
      servicePackage: item.value,
      total: selectedTotal.value,
    },
  }).onOk(() => {
    onDialogOK()
  })
}

const onConfirm = () => {
  if (selectedMethod.value === 'pix') {
    openPixPayment()
    return
  }
  const clientPaymentMethodId = Number(String(selectedMethod.value).replace('card_', ''))

  $q.dialog({
    component: SchedulePaymentProcessingDialog,
    componentProps: {
      servicePackage: item.value,
      clientPaymentMethodId,
      total: selectedTotal.value,
    },
  }).onOk(() => {
    onDialogOK()
  })
}

onMounted(() => {
  loadPlatformFees().catch(() => {})

  const existingPix = paymentStore.getValidPixPaymentForServicePackage(item.value.id)

  if (existingPix) {
    openPixPayment()
    return
  }

  loadCards()
})
</script>

<style scoped lang="scss">
.shadow-header {
  box-shadow: 0px 1px 8px rgba(0, 0, 0, 0.1);
}


.address-box {
  border: 1px solid #e0e0e0;
  border-radius: 10px;
  padding: 12px 16px;
  background: #fff;
}

.address-type-label {
  color: #3a3a4a;
}

.address-full-text {
  line-height: 1.4;
  margin-top: 2px;
}

.payment-option-card {
  border: 1.5px solid #e0e0e0;
  border-radius: 12px;
  background: #fff;
  min-height: 90px;
  text-align: center;
  transition: border-color 0.2s;
}

.payment-option-selected {
  border-color: #22c55e !important;
  box-shadow: 0 0 0 1px #22c55e;
}

.payment-option-title {
  color: #3a3a4a;
}

.payment-option-sub {
  color: #9a9aaa;
  margin-top: 2px;
}

.payment-summary {
  border: 1px solid #e0e0e0;
  border-radius: 10px;
  background: #fff;
  padding: 12px 16px;
}

.summary-label,
.summary-value {
  color: #5a5a6a;
}

.summary-total-label,
.summary-total-value {
  color: #3a3a4a;
  font-weight: 700;
}

.saved-card-box {
  border: 1.5px solid #e0e0e0;
  border-radius: 12px;
  background: #fff;
  transition: border-color 0.2s;
}

.card-titular-label {
  color: #9a9aaa;
}

.card-holder-name {
  color: #3a3a4a;
}

.card-brand-text {
  color: #3a3a4a;
  text-align: right;
}

.card-last-four {
  color: #6a6a7a;
  letter-spacing: 1px;
}

.card-expiry-text {
  color: #9a9aaa;
}

.terms-text {
  color: #5a5a6a;
  line-height: 1.4;
}

.text-underline {
  text-decoration: underline;
}

</style>
