<!-- src/pages/card/editcard.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>Edit Credit Card</li>
        </ul>
      </div>

      <!-- TOP SECTION: Customer and Card Info -->
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 my-6">
        <!-- Customer Info Card -->
        <div class="bg-neutral rounded-lg p-5">
          <div class="flex justify-between items-center mb-4">
            <div>
              <div class="text-xl font-bold">{{ customer.customer_first_name }} {{ customer.customer_last_name }}</div>
              <div class="text-sm text-gray-400">Account: {{ customer.account_number }}</div>
            </div>
            <router-link :to="{ name: 'customerProfile', params: { id: customer.id } }"
              class="btn btn-secondary btn-sm">
              View Profile
            </router-link>
          </div>
          <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">Connecticut</span>
              <span v-else-if="customer.customer_state == 6">New York</span>
              <span v-else>Unknown state</span> {{ customer.customer_zip }}
            </div>
          </div>
        </div>

        <!-- Card Being Edited Info Card -->
        <div class="bg-neutral rounded-lg p-5">
          <h3 class="text-xl font-bold mb-4">Editing Card</h3>
          <div v-if="card.id" class="space-y-2">
            <p><strong class="font-semibold">Card Type:</strong> {{ card.type_of_card }}</p>
            <p><strong class="font-semibold">Card Number:</strong> {{ card.card_number }}</p>

          </div>
          <div v-else class="text-gray-400">Loading card details...</div>
        </div>
      </div>

      <!-- BOTTOM SECTION: Edit Card Form -->
      <div class="bg-neutral rounded-lg p-6">
        <h2 class="text-2xl font-bold mb-4">Update Card Details</h2>
        <form @submit.prevent="onSubmit" class="space-y-4">
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">

            <!-- Name on Card -->
            <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="" 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">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">Required.</span>
            </div>

            <!-- Expiration -->
            <div class="form-control">
              <label class="label"><span class="label-text font-bold">Expiration</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="">MM</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="">YYYY</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">Required.</span>
            </div>

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

            <!-- Card Type -->
            <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 -->
            <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="" class="input input-bordered input-sm w-full" />
            </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</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 ? 'Updating...' : 'Save Changes' }}
            </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 card = 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({
  name_on_card: '',
  expiration_month: '',
  expiration_year: '',
  type_of_card: '',
  security_number: '',
  card_number: '',
  zip_code: '',
  main_card: false,
})

// Validation rules
const rules = computed(() => ({
  form: {
    name_on_card: { required, minLength: minLength(1) },
    expiration_month: { required },
    expiration_year: { required },
    security_number: { required, minLength: minLength(1) },
    type_of_card: { required },
    card_number: { required, minLength: minLength(1) },
  },
}))

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) {
    console.error('Failed to fetch customer:', 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 getCard(cardId: string | number) {
  try {
    const response = await paymentService.getCardById(Number(cardId))
    const data = response.data as any
    card.value = data

    // Populate form
    form.name_on_card = data.name_on_card
    form.expiration_month = String(data.expiration_month).padStart(2, '0')
    form.expiration_year = String(data.expiration_year)
    form.type_of_card = data.type_of_card
    form.security_number = data.security_number
    form.main_card = data.main_card
    form.card_number = data.card_number
    form.zip_code = data.zip_code

    if (data.user_id) {
      getCustomer(data.user_id)
    }
  } catch (error) {
    console.error('Failed to fetch card:', error)
  }
}

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.security_number,
    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.security_number,
    main_card: form.main_card,
  }

  // Step 1: Update card in local database via Flask
  try {
    const response = await paymentService.updateCard(Number(route.params.id), flaskPayload)
    if (!(response.data as any).ok) {
      throw new Error((response.data as any).error || "Failed to update card.")
    }
  } catch (error: any) {
    const errorMessage = error.response?.data?.error || "A critical error occurred while updating 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 updated.", type: "success" })
    isLoading.value = false
    router.push({ name: "customerProfile", params: { id: customer.value.id } })
    return
  }

  // Step 2: Update card tokenization via Authorize.Net
  try {
    await paymentService.updateAuthorizeCard(customer.value.id, Number(route.params.id), fastapiPayload)
  } catch (error: any) {
    console.warn("NON-CRITICAL-ERROR: Authorize.Net update failed, but the card was updated locally.", error.response?.data || error.message)
  }

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

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