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

      <div class="row items-center q-px-md q-pt-md q-pb-sm bg-white shadow-profile bg-surface">
        <q-btn icon="mdi-chevron-left" flat round dense color="primary" @click="onDialogCancel" />
        <q-space />
        <span class="text-subtitle1 text-weight-bold text-primary">
          {{ $t('profile.payments.title') }}
        </span>
        <q-space />
        <div style="width: 32px"></div>
      </div>

      <div class="col overflow-auto q-px-md q-pt-lg q-pb-xl">
        <div class="text-h6 text-weight-bold text-primary q-mb-md" style="text-transform: capitalize;">
          {{ paymentMethod ? $t('profile.payments.edit_title') : $t('profile.payments.add_card') }}
        </div>

        <div class="virtual-card q-mb-xl">
          <div class="card-top-row row items-start justify-between">
            <span class="card-brand-label">{{ brandDisplayName }}</span>
            <q-icon name="mdi-wifi-strength-4" size="24px" color="white" class="nfc-icon" style="transform: rotate(90deg);" />
          </div>
          <div class="card-number-preview">
            {{ maskedCardNumberPreview }}
          </div>
          <div class="card-bottom-row row items-end justify-between">
            <div class="column">
              <span class="card-holder-name">{{ form.holder_name || 'Nome do Titular' }}</span>
            </div>
            <div class="column items-end">
              <span class="card-expiry">{{ form.expiration || '**/****' }}</span>
            </div>
          </div>
        </div>

        <q-form ref="formRef" class="column q-gutter-y-sm text-text" @submit="onOKClick">
          <div>
            <div class="input-label">
              {{ $t('profile.payments.card_number') }}
            </div>
            <q-input
              v-model="form.card_number"
              :rules="[inputRules.requiredHideMessage]"
              :error="!!serverErrors.card_number"
              :error-message="serverErrors.card_number"
              mask="#### #### #### ####"
              unmasked-value
              outlined
              input-class="text-text"
              hide-bottom-space
              class="input-field bg-surface input-border-dark"
              @update:model-value="onCardNumberChange"
            />
          </div>

          <div class="q-pt-lg">
            <div class="input-label">
              {{ $t('profile.payments.holder_name') }}
            </div>
            <q-input
              v-model="form.holder_name"
              placeholder="Nome como está no cartão"
              :rules="[inputRules.requiredHideMessage]"
              :error="!!serverErrors.holder_name"
              :error-message="serverErrors.holder_name"
              outlined
              input-class="text-text"
              hide-bottom-space
              class="input-field bg-surface input-border-dark"
              @update:model-value="serverErrors.holder_name = null"
            />
          </div>

          <div class="row col-12 q-col-gutter-sm q-pt-lg">
            <div class="col-7">
              <div class="input-label">
                {{ $t('profile.payments.expiration') }}
              </div>
              <q-input
                v-model="form.expiration"
                :placeholder="$t('profile.payments.mmyyyy')"
                :rules="[inputRules.requiredHideMessage, validateExpiration]"
                :error="!!serverErrors.expiration"
                :error-message="serverErrors.expiration"
                mask="##/####"
                outlined
                class="col input-field bg-surface input-border-dark"
                input-class="text-text"
                hide-bottom-space
                @update:model-value="serverErrors.expiration = null"
              />
            </div>
            <div class="col-5">
              <div class="input-label row items-center q-gutter-x-xs">
                <span>{{ $t('profile.payments.cvv') }}</span>
                <q-icon name="mdi-help-circle-outline" color="grey-8" size="16px" class="cursor-pointer">
                  <q-tooltip>{{ $t('profile.payments.cvv_help') }}</q-tooltip>
                </q-icon>
              </div>
              <q-input
                v-model="form.cvv"
                placeholder="***"
                :rules="[inputRules.requiredHideMessage]"
                :error="!!serverErrors.cvv"
                :error-message="serverErrors.cvv"
                mask="####"
                unmasked-value
                type="password"
                outlined
                input-class="text-text"
                class="col input-field bg-surface input-border-dark"
                hide-bottom-space
                @update:model-value="serverErrors.cvv = null"
              />
            </div>
          </div>

          <div class="row items-center justify-center q-gutter-x-xs q-mt-sm q-mb-xs">
            <q-icon name="mdi-shield-check" color="positive" size="18px" />
            <span class="security-text-new">{{ $t('profile.payments.security_badge') }}</span>
          </div>

          <q-btn
            type="submit"
            unelevated
            rounded
            no-caps
            color="primary"
            class="full-width q-mt-md save-btn q-mb-md"
            padding="14px 16px"
            :label="paymentMethod ? $t('profile.payments.save_btn') : $t('profile.payments.add_card')"
            :loading="loading"
            :disable="!hasUpdatedFields"
          />
        </q-form>
      </div>

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

<script setup>
import { ref, computed } from 'vue';
import { useDialogPluginComponent } from 'quasar';
import { useI18n } from 'vue-i18n';
import { useFormUpdateTracker } from 'src/composables/useFormUpdateTracker';
import { useSubmitHandler } from 'src/composables/useSubmitHandler';
import { useInputRules } from 'src/composables/useInputRules';
import { /*validateCardNumberLuhn,*/ detectCardBrand, validateCardExpiration } from 'src/helpers/utils';
import { createClientPaymentMethod, updateClientPaymentMethod } from 'src/api/clientPaymentMethod';

const props = defineProps({
  paymentMethod: {
    type: Object,
    default: null,
  },
  clientId: {
    type: Number,
    required: true,
  },
});

defineEmits([...useDialogPluginComponent.emits]);

const { dialogRef, onDialogOK, onDialogCancel } = useDialogPluginComponent();
const { t } = useI18n();
const { inputRules } = useInputRules();
const formRef = ref(null);

const { form, hasUpdatedFields } = useFormUpdateTracker({
  client_id: props.paymentMethod ? props.paymentMethod.client_id : props.clientId,
  card_number: props.paymentMethod ? props.paymentMethod.card_number : null,
  holder_name: props.paymentMethod ? props.paymentMethod.holder_name : null,
  expiration: props.paymentMethod ? (props.paymentMethod.expiration?.includes('/') && props.paymentMethod.expiration.split('/')[1].length === 2 ? `${props.paymentMethod.expiration.split('/')[0]}/20${props.paymentMethod.expiration.split('/')[1]}` : props.paymentMethod.expiration) : null,
  cvv: props.paymentMethod ? props.paymentMethod.cvv : null,
  card_name: props.paymentMethod ? props.paymentMethod.card_name : null,
  brand: props.paymentMethod ? props.paymentMethod.brand : null,
  last_four_digits: props.paymentMethod ? props.paymentMethod.last_four_digits : null,
  is_active: props.paymentMethod ? props.paymentMethod.is_active : true,
});

const { loading, serverErrors, execute: submitForm } = useSubmitHandler(() => onDialogOK(true));

const brandDisplayName = computed(() => {
  if (!form.brand) return '';
  const names = {
    visa: 'VISA',
    mastercard: 'Mastercard',
    elo: 'Elo',
    hipercard: 'Hipercard',
    diners: 'Diners',
    discover: 'Discover',
  };
  return names[form.brand] ?? form.brand;
});

const maskedCardNumberPreview = computed(() => {
  const raw = form.card_number ? String(form.card_number).replace(/\D/g, '') : '';
  if (!raw || raw.includes('*')) return '**** **** **** ****';
  const lastFour = raw.slice(-4).padStart(4, '*');
  return `**** **** **** ${lastFour}`;
});

// const validateCardNumber = (val) => {
//   if (!val) return true;
//   if (val.includes('*')) return true;
//   if (!validateCardNumberLuhn(val)) return t('profile.payments.invalid_card_number');
//   return true;
// };

const validateExpiration = (val) => {
  if (!val) return true;
  if (!validateCardExpiration(val)) return t('profile.payments.expired_card');
  return true;
};

const onCardNumberChange = () => {
  serverErrors.value.card_number = null;
  const raw = form.card_number ? String(form.card_number).replace(/\D/g, '') : '';
  if (raw.length >= 6 && !String(form.card_number).includes('*')) {
    const brand = detectCardBrand(raw);
    if (brand) form.brand = brand;
    if (raw.length >= 4) form.last_four_digits = raw.slice(-4);
  }
};

const onOKClick = async () => {
  const valid = await formRef.value?.validate();
  if (!valid) return;
  if (props.paymentMethod) {
    await submitForm(() => updateClientPaymentMethod(props.paymentMethod.id, { ...form }));
  } else {
    await submitForm(() => createClientPaymentMethod({ ...form }));
  }
};
</script>

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

.virtual-card {
  background: linear-gradient(135deg, #6c3fc5 0%, #9c27b0 100%);
  border-radius: 20px;
  padding: 20px 24px;
  min-height: 180px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  box-shadow: 0 8px 24px rgba(108, 63, 197, 0.4);
  color: white;
}

.nfc-icon {
  opacity: 0.85;
}

.card-brand-label {
  font-family: 'Inter', sans-serif;
  font-size: 16px;
  font-weight: 700;
  letter-spacing: 1px;
  opacity: 0.9;
}

.card-number-preview {
  font-family: 'Inter', sans-serif;
  font-size: 20px;
  font-weight: 600;
  letter-spacing: 3px;
  text-align: center;
  margin: 12px 0;
}

.card-label-sm {
  font-family: 'Inter', sans-serif;
  font-size: 10px;
  font-weight: 400;
  opacity: 0.7;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.card-holder-name {
  font-family: 'Inter', sans-serif;
  font-size: 13px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.card-expiry {
  font-family: 'Inter', sans-serif;
  font-size: 13px;
  font-weight: 600;
  letter-spacing: 1px;
}

.input-field {
  font-family: 'Inter', sans-serif;
}

.input-label {
  font-family: 'Inter', sans-serif;
  font-size: 14px;
  font-weight: 800;
  color: #444;
  margin-bottom: 2px;
}

.input-border-dark :deep(.q-field__control:before) {
  border: 1px solid #afafaf !important;
  opacity: 1 !important;
}

.input-border-dark :deep(.q-field__control:after) {
  border-color: #666 !important;
  opacity: 1 !important;
}

.input-border-dark :deep(.q-field__control) {
  border-radius: 6px !important;
}

.security-text-new {
  font-family: 'Inter', sans-serif;
  font-size: 13px;
  font-weight: 500;
  color: #555;
}

.save-btn {
  font-family: 'Inter', sans-serif;
  font-size: 16px;
  font-weight: 700;
}
</style>
