<!-- 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="CardForm.name_on_card" type="text" placeholder="" class="input input-bordered input-sm w-full" />
              <span v-if="v$.CardForm.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="CardForm.card_number" type="text" placeholder="" class="input input-bordered input-sm w-full" />
              <span v-if="v$.CardForm.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="CardForm.expiration_month" class="select select-bordered select-sm w-full">
                  <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="CardForm.expiration_year" class="select select-bordered select-sm w-full">
                  <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$.CardForm.expiration_month.$error || v$.CardForm.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="CardForm.security_number" type="text" placeholder="" class="input input-bordered input-sm w-full" />
              <span v-if="v$.CardForm.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="CardForm.type_of_card" class="select select-bordered select-sm w-full">
                <option disabled value="">Select Type</option>
                <option>Visa</option>
                <option>MasterCard</option>
                <option>Discover</option>
                <option>American Express</option>
              </select>
              <span v-if="v$.CardForm.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="CardForm.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="CardForm.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>
  <Footer />
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import axios from 'axios'
import authHeader from '../../services/auth.header'
import Footer from '../../layouts/footers/footer.vue'
import useValidate from "@vuelidate/core";
import { minLength, required } from "@vuelidate/validators";
import { notify } from "@kyvg/vue3-notification";

export default defineComponent({
  name: 'EditCard',
  components: {
    Footer,
  },
  data() {
    return {
      v$: useValidate(),
      user: null as any,
      customer: {} as any,
      card: {} as any, // To store original card details for display
      isLoading: false,
      isLoadingAuthorize: true,
      authorizeCheck: { profile_exists: false, has_payment_methods: false, missing_components: [] as string[], valid_for_charging: false },
      // --- REFACTORED: Simplified, flat form object ---
      CardForm: {
        name_on_card: '',
        expiration_month: '',
        expiration_year: '',
        type_of_card: '',
        security_number: '',
        card_number: '',
        zip_code: '',
        main_card: false,
      },
    }
  },
  validations() {
    return {
      // --- REFACTORED: Validation points to the flat form object ---
      CardForm: {
        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) },
      },
    };
  },
  created() {
    this.userStatus();
    this.getCard(this.$route.params.id);
  },
  methods: {
    userStatus() {
      const path = import.meta.env.VITE_BASE_URL + '/auth/whoami';
      axios.get(path, { withCredentials: true, headers: authHeader() })
        .then((response: any) => {
          if (response.data.ok) { this.user = response.data.user; }
        })
        .catch(() => { this.user = null; });
    },
    getCustomer(userid: any) {
      const path = `${import.meta.env.VITE_BASE_URL}/customer/${userid}`;
      axios.get(path, { headers: authHeader() })
        .then((response: any) => {
          this.customer = response.data;
          this.checkAuthorizeAccount();
        });
    },
    async checkAuthorizeAccount() {
      if (!this.customer.id) return;

      this.isLoadingAuthorize = true;

      try {
        const path = `${import.meta.env.VITE_AUTHORIZE_URL}/user/check-authorize-account/${this.customer.id}`;
        const response = await axios.get(path, { headers: authHeader() });
        this.authorizeCheck = response.data;
      } catch (error) {
        console.error("Failed to check authorize account:", error);
        notify({ title: "Error", text: "Could not check payment account status.", type: "error" });
        // Set default error state
        this.authorizeCheck = {
          profile_exists: false,
          has_payment_methods: false,
          missing_components: ['api_error'],
          valid_for_charging: false
        };
      } finally {
        this.isLoadingAuthorize = false;
      }
    },
   getCard(card_id: any) {
  const path = `${import.meta.env.VITE_BASE_URL}/payment/card/${card_id}`;
  axios.get(path, { withCredentials: true, headers: authHeader() })
    .then((response: any) => {
      this.card = response.data; // Store original details for display
      
      // Populate the flat form object for editing
      this.CardForm.name_on_card = response.data.name_on_card;
      
      // --- FIX IS HERE ---
      // Convert the month number (e.g., 8) to a zero-padded string ("08") to match the <option> value.
      this.CardForm.expiration_month = String(response.data.expiration_month).padStart(2, '0');
      
      // Convert the year number (e.g., 2025) to a string ("2025") for consistency.
      this.CardForm.expiration_year = String(response.data.expiration_year);
      // --- END FIX ---
      
      this.CardForm.type_of_card = response.data.type_of_card;
      this.CardForm.security_number = response.data.security_number;
      this.CardForm.main_card = response.data.main_card;
      this.CardForm.card_number = response.data.card_number;
      this.CardForm.zip_code = response.data.zip_code;
      
      if (response.data.user_id) {
        this.getCustomer(response.data.user_id);
      }
    });
},
editCard(payload: any) {
  const path = `${import.meta.env.VITE_BASE_URL}/payment/card/edit/${this.$route.params.id}`;

  // REMOVE the payload manipulation. Send the form data directly.
  // The 'payload' object (which is this.CardForm) is already in the correct format.
  axios.put(path, payload, { withCredentials: true, headers: authHeader() })
    .then((response: any) => {
      if (response.data.ok) {
        this.$router.push({ name: "customerProfile", params: { id: this.customer.id } });
      } else {
        // You should notify the user here as well
    
        console.error("Failed to edit card:", response.data.error);
      }
    })
    .catch(console.log("error"));
},
async onSubmit() {
      this.v$.$validate();
      if (this.v$.$error) {
        notify({ title: "Validation Error", text: "Please fill out all required fields.", type: "error" });
        return;
      }

      this.isLoading = true;

      // --- STEP 1: PREPARE PAYLOADS FOR BOTH SERVICES ---
      // Payload for your Flask backend (it takes all the raw details for your DB)
      const flaskPayload = {
        card_number: this.CardForm.card_number,
        expiration_month: this.CardForm.expiration_month,
        expiration_year: this.CardForm.expiration_year,
        type_of_card: this.CardForm.type_of_card,
        security_number: this.CardForm.security_number,
        main_card: this.CardForm.main_card,
        zip_code: this.CardForm.zip_code,
        name_on_card: this.CardForm.name_on_card,
      };

      // Payload for your FastAPI backend (it only needs the essentials for Authorize.Net)
      const fastapiPayload = {
        card_number: this.CardForm.card_number.replace(/\s/g, ''),
        expiration_date: `${this.CardForm.expiration_year}-${this.CardForm.expiration_month}`,
        cvv: this.CardForm.security_number,
        main_card: this.CardForm.main_card,
      };

      // --- STEP 2: CRITICAL CALL - UPDATE CARD TO LOCAL DATABASE VIA FLASK ---
      try {
        const flaskPath = `${import.meta.env.VITE_BASE_URL}/payment/card/edit/${this.$route.params.id}`;
        console.log("Attempting to update card to local DB via Flask:", flaskPath);
        const flaskResponse = await axios.put(flaskPath, flaskPayload, { withCredentials: true, headers: authHeader() });

        if (!flaskResponse.data.ok) {
          throw new Error(flaskResponse.data.error || "Failed to update card.");
        }
        console.log("Card successfully updated to local database via Flask with ID:", this.$route.params.id);

      } catch (error: any) {
        const errorMessage = error.response?.data?.error || "A critical error occurred while updating the card.";
        notify({ title: "Error", text: errorMessage, type: "error" });
        this.isLoading = false;
        return;
      }

      // --- CHECK IF AUTHORIZE.NET PROFILE EXISTS ---
      if (!this.authorizeCheck.profile_exists) {
        console.log("Skipping Authorize.Net tokenization as no profile exists for customer.");
        // Show success and redirect (card updated locally without tokenization)
        notify({ title: "Success", text: "Credit card has been updated.", type: "success" });
        this.isLoading = false;
        this.$router.push({ name: "customerProfile", params: { id: this.customer.id } });
        return;
      }

      // --- STEP 3: BEST-EFFORT CALL - TOKENIZE/UPDATE CARD VIA AUTHORIZE
      try {
        const fastapiPath = `${import.meta.env.VITE_AUTHORIZE_URL}/api/payments/customers/${this.customer.id}/cards/${this.$route.params.id}`;
        console.log("Attempting to update card tokenization with Authorize.Net via FastAPI:", fastapiPath);
        await axios.put(fastapiPath, fastapiPayload, { withCredentials: true, headers: authHeader() });
        console.log("Card successfully updated with Authorize.Net via FastAPI.");

      } catch (error: any) {
        // If this fails, we just log it for the developers. We DON'T show an error to the user.
        console.warn("NON-CRITICAL-ERROR: Authorize.Net update failed, but the card was updated locally.", error.response?.data || error.message);
        // Card is updated but Authorize.Net profile may not be current, which is ok.
      }

      // --- STEP 4: ALWAYS SHOW SUCCESS AND REDIRECT ---
      notify({ title: "Success", text: "Credit card has been updated.", type: "success" });
      this.isLoading = false;
      this.$router.push({ name: "customerProfile", params: { id: this.customer.id } });
    },
  },
});
</script>
