<!-- src/pages/card/addcard.vue -->
<template>
  <div class="flex">
    <div class="w-full px-4 md-px-10 py-4">
      <!-- Breadcrumbs -->
      <div class="text-sm breadcrumbs">
        <ul>
          <li><router-link :to="{ name: 'home' }">Home</router-link></li>
          <li><router-link :to="{ name: 'customer' }">Customers</router-link></li>
          <li v-if="customer.id"><router-link
              :to="{ name: 'customerProfile', params: { id: customer.id } }">Profile</router-link></li>
          <li>Add Credit Card</li>
        </ul>
      </div>

      <!-- TOP SECTION: Customer Info -->
      <div class="my-6">
        <div class="bg-neutral rounded-lg p-5">
          <div class="text-xl font-bold mb-2">Customer</div>
          <div>
            <div class="font-bold">{{ customer.customer_first_name }} {{ customer.customer_last_name }}</div>
            <div>{{ customer.customer_address }}</div>
            <div v-if="customer.customer_apt && customer.customer_apt !== 'None'">{{ customer.customer_apt }}</div>
            <div>
              {{ customer.customer_town }},
              <span v-if="customer.customer_state == 0">Massachusetts</span>
              <span v-else-if="customer.customer_state == 1">Rhode Island</span>
              <span v-else-if="customer.customer_state == 2">New Hampshire</span>
              <span v-else-if="customer.customer_state == 3">Maine</span>
              <span v-else-if="customer.customer_state == 4">Vermont</span>
              <span v-else-if="customer.customer_state == 5">Maine</span>
              <span v-else-if="customer.customer_state == 6">New York</span>
              <span v-else>Unknown state</span>
              {{ customer.customer_zip }}
            </div>
            <div class="mt-2 text-sm">
              {{ customer.customer_phone_number }}
              (<span v-if="customer.customer_home_type == 0">Residential</span>
              <span v-else-if="customer.customer_home_type == 1">apartment</span>
              <span v-else-if="customer.customer_home_type == 2">condo</span>
              <span v-else-if="customer.customer_home_type == 3">commercial</span>
              <span v-else-if="customer.customer_home_type == 4">business</span>
              <span v-else-if="customer.customer_home_type == 5">construction</span>
              <span v-else-if="customer.customer_home_type == 6">container</span>
              <span v-else>Unknown type</span>)
            </div>
          </div>
        </div>
      </div>

      <!-- BOTTOM SECTION: Add Card Form -->
      <div class="bg-neutral rounded-lg p-6">
        <h2 class="text-2xl font-bold mb-4">Add a New Credit Card</h2>
        <form @submit.prevent="onSubmit" class="space-y-4">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <!-- Name -->
            <div class="form-control">
              <label class="label"><span class="label-text font-bold">Name on Card</span></label>
              <input v-model="form.name_on_card" type="text" placeholder="Name"
                class="input input-bordered input-sm w-full" :class="{ 'input-error': v$.form.name_on_card.$error }" />
              <span v-if="v$.form.name_on_card.$error" class="text-red-500 text-xs mt-1">A valid name_on_card is
                required.</span>
            </div>

            <!-- Card Number -->
            <div class="form-control">
              <label class="label"><span class="label-text font-bold">Card Number</span></label>
              <input v-model="form.card_number" type="text" placeholder="•••• •••• •••• ••••"
                class="input input-bordered input-sm w-full" :class="{ 'input-error': v$.form.card_number.$error }" />
              <span v-if="v$.form.card_number.$error" class="text-red-500 text-xs mt-1">A valid card number is
                required.</span>
            </div>

            <!-- CVV (Security Code) -->
            <div class="form-control">
              <label class="label"><span class="label-text font-bold">CVV</span></label>
              <input v-model="form.cvv" type="text" placeholder="123" class="input input-bordered input-sm w-full"
                :class="{ 'input-error': v$.form.cvv.$error }" />
              <span v-if="v$.form.cvv.$error" class="text-red-500 text-xs mt-1">CVV is required.</span>
            </div>

            <!-- Expiration -->
            <div class="form-control">
              <label class="label"><span class="label-text font-bold">Expiration Date</span></label>
              <div class="flex gap-2">
                <select v-model="form.expiration_month" class="select select-bordered select-sm w-full"
                  :class="{ 'select-error': v$.form.expiration_month.$error }">
                  <option disabled value="">Month</option>
                  <option v-for="m in 12" :key="m" :value="String(m).padStart(2, '0')">{{ String(m).padStart(2, '0') }}
                  </option>
                </select>
                <select v-model="form.expiration_year" class="select select-bordered select-sm w-full"
                  :class="{ 'select-error': v$.form.expiration_year.$error }">
                  <option disabled value="">Year</option>
                  <option v-for="y in 10" :key="y" :value="new Date().getFullYear() + y - 1">{{ new Date().getFullYear()
                    + y - 1 }}</option>
                </select>
              </div>
              <span v-if="v$.form.expiration_month.$error || v$.form.expiration_year.$error"
                class="text-red-500 text-xs mt-1">Both month and year are required.</span>
            </div>

            <!-- Card Type dropdown -->
            <div class="form-control">
              <label class="label"><span class="label-text font-bold">Card Type</span></label>
              <select v-model="form.type_of_card" class="select select-bordered select-sm w-full"
                :class="{ 'select-error': v$.form.type_of_card.$error }">
                <option disabled value="">Select Type</option>
                <option>Visa</option>
                <option>MasterCard</option>
                <option>Discover</option>
                <option>American Express</option>
              </select>
              <span v-if="v$.form.type_of_card.$error" class="text-red-500 text-xs mt-1">Required.</span>
            </div>

            <!-- Billing Zip Code input -->
            <div class="form-control">
              <label class="label"><span class="label-text font-bold">Billing Zip Code</span></label>
              <input v-model="form.zip_code" type="text" placeholder="12345"
                class="input input-bordered input-sm w-full" :class="{ 'input-error': v$.form.zip_code.$error }" />
              <span v-if="v$.form.zip_code.$error" class="text-red-500 text-xs mt-1">Required.</span>
            </div>

            <!-- Main Card Checkbox -->
            <div class="form-control md:col-span-2">
              <label class="label cursor-pointer justify-start gap-4">
                <span class="label-text font-bold">Set as Main Card for this customer</span>
                <input v-model="form.main_card" type="checkbox" class="checkbox checkbox-sm" />
              </label>
            </div>

          </div>

          <!-- SUBMIT BUTTON -->
          <div class="pt-4">
            <button type="submit" class="btn btn-primary btn-sm" :disabled="isLoading">
              <span v-if="isLoading" class="loading loading-spinner loading-xs"></span>
              {{ isLoading ? 'Saving...' : 'Save Credit Card' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>

</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { notify } from "@kyvg/vue3-notification"
import { useVuelidate } from '@vuelidate/core'
import { required, minLength } from "@vuelidate/validators"
import { paymentService } from '../../services/paymentService'
import { customerService } from '../../services/customerService'

const route = useRoute()
const router = useRouter()

// State
const customer = ref<any>({})
const isLoading = ref(false)
const isLoadingAuthorize = ref(true)
const authorizeCheck = ref({
  profile_exists: false,
  has_payment_methods: false,
  missing_components: [] as string[],
  valid_for_charging: false
})

const form = reactive({
  main_card: false,
  card_number: '',
  expiration_month: '',
  expiration_year: '',
  cvv: '',
  type_of_card: '',
  zip_code: '',
  name_on_card: '',
})

// Validation rules
const rules = computed(() => ({
  form: {
    card_number: { required, minLength: minLength(13) },
    expiration_month: { required },
    expiration_year: { required },
    cvv: { required, minLength: minLength(3) },
    type_of_card: { required },
    zip_code: { required, minLength: minLength(5) },
    name_on_card: { required },
  },
}))

const v$ = useVuelidate(rules, { form })

// Methods
async function getCustomer(userId: string | number) {
  try {
    const response = await customerService.getById(Number(userId))
    customer.value = response.data
    checkAuthorizeAccount()
  } catch (error) {
    notify({ title: "Error", text: "Could not find customer", type: "error" })
  }
}

async function checkAuthorizeAccount() {
  if (!customer.value.id) return
  isLoadingAuthorize.value = true

  try {
    const response = await paymentService.checkAuthorizeAccount(customer.value.id)
    authorizeCheck.value = response.data as any
  } catch (error) {
    console.error("Failed to check authorize account:", error)
    notify({ title: "Error", text: "Could not check payment account status.", type: "error" })
    authorizeCheck.value = {
      profile_exists: false,
      has_payment_methods: false,
      missing_components: ['api_error'],
      valid_for_charging: false
    }
  } finally {
    isLoadingAuthorize.value = false
  }
}

async function onSubmit() {
  const isValid = await v$.value.$validate()
  if (!isValid) {
    notify({ title: "Validation Error", text: "Please fill out all required fields.", type: "error" })
    return
  }

  isLoading.value = true

  // Payload for Flask backend
  const flaskPayload = {
    card_number: form.card_number,
    expiration_month: form.expiration_month,
    expiration_year: form.expiration_year,
    type_of_card: form.type_of_card,
    security_number: form.cvv,
    main_card: form.main_card,
    zip_code: form.zip_code,
    name_on_card: form.name_on_card,
  }

  // Payload for FastAPI backend (Authorize.Net)
  const fastapiPayload = {
    card_number: form.card_number.replace(/\s/g, ''),
    expiration_date: `${form.expiration_year}-${form.expiration_month}`,
    cvv: form.cvv,
    main_card: form.main_card,
  }

  // Step 1: Save to local database via Flask
  let cardId: number
  try {
    const response = await paymentService.createCard(customer.value.id, flaskPayload as any)
    if (!(response.data as any).ok) {
      throw new Error((response.data as any).error || "Failed to save card.")
    }
    cardId = (response.data as any).card_id
  } catch (error: any) {
    const errorMessage = error.response?.data?.error || "A critical error occurred while saving the card."
    notify({ title: "Error", text: errorMessage, type: "error" })
    isLoading.value = false
    return
  }

  // Check if Authorize.Net profile exists
  if (!authorizeCheck.value.profile_exists) {
    notify({ title: "Success", text: "Credit card has been saved.", type: "success" })
    isLoading.value = false
    router.push({ name: "customerProfile", params: { id: customer.value.id } })
    return
  }

  // Step 2: Tokenize card via Authorize.Net
  try {
    const response = await paymentService.createAuthorizeCard(customer.value.id, fastapiPayload)
    const paymentProfileId = (response.data as any).payment_profile_id
    // Update local card with payment_profile_id
    await paymentService.updatePaymentProfile(cardId, { auth_net_payment_profile_id: paymentProfileId })
  } catch (error: any) {
    console.warn("NON-CRITICAL-ERROR: Tokenization with Authorize.Net failed, but the card was saved locally.", error.response?.data || error.message)
  }

  // Always show success and redirect
  notify({ title: "Success", text: "Credit card has been saved.", type: "success" })
  isLoading.value = false
  router.push({ name: "customerProfile", params: { id: customer.value.id } })
}

// Lifecycle
onMounted(() => {
  getCustomer(route.params.id as string)
})
</script>
