<template>
  <div v-if="show" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
    <div class="bg-base-100 rounded-lg shadow-xl max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
      <!-- Header -->
      <div class="flex justify-between items-center p-6 border-b">
        <h2 class="text-2xl font-bold">Payment Authorization</h2>
        <button @click="close" class="btn btn-ghost btn-sm">✕</button>
      </div>

      <!-- Content -->
      <div class="p-6 space-y-6">
        <!-- Amount Input -->
        <div class="form-control">
          <label class="label">
            <span class="label-text font-semibold">Charge Amount</span>
          </label>
          <input
            v-model="chargeAmount"
            type="number"
            step="0.01"
            class="input input-bordered"
            placeholder="Enter amount"
            :disabled="loading"
          />
        </div>

        <!-- Charge Breakdown -->
        <div class="bg-neutral rounded-lg p-4">
          <h3 class="text-lg font-semibold mb-4">Charge Breakdown</h3>
          <div class="space-y-2">
            <div class="flex justify-between">
              <span>Gallons Ordered:</span>
              <span>{{ delivery.gallons_ordered || 0 }} gallons</span>
            </div>
            <div class="flex justify-between">
              <span>Price per Gallon:</span>
              <span>${{ delivery.customer_price || 0 }}</span>
            </div>
            <div class="flex justify-between">
              <span>Subtotal:</span>
              <span>${{ calculateSubtotal() }}</span>
            </div>
            <div v-if="delivery.prime == 1" class="flex justify-between text-sm">
              <span>Prime Fee:</span>
              <span>+ ${{ pricing.price_prime || 0 }}</span>
            </div>
            <div v-if="delivery.same_day == 1" class="flex justify-between text-sm">
              <span>Same Day Fee:</span>
              <span>+ ${{ pricing.price_same_day || 0 }}</span>
            </div>
            <div v-if="delivery.emergency == 1" class="flex justify-between text-sm">
              <span>Emergency Fee:</span>
              <span>+ ${{ pricing.price_emergency || 0 }}</span>
            </div>
            <div v-if="promoActive" class="flex justify-between text-success">
              <span>{{ promo.name_of_promotion }}:</span>
              <span>- ${{ discount }}</span>
            </div>
            <hr class="my-2">
            <div class="flex justify-between font-bold">
              <span>Total:</span>
              <span>${{ promoActive ? totalAmountAfterDiscount : totalAmount }}</span>
            </div>
          </div>
        </div>

        <!-- Credit Card Display -->
        <div v-if="selectedCard" class="bg-neutral rounded-lg p-4">
          <h3 class="text-lg font-semibold mb-4">Payment Method</h3>
          <div class="bg-base-100 p-4 rounded-md">
            <div class="flex justify-between items-center mb-2">
              <div class="font-semibold">{{ selectedCard.type_of_card }}</div>
              <div v-if="selectedCard.main_card" class="badge badge-primary">Primary</div>
            </div>
            <div class="font-mono text-sm">
              <div>**** **** **** {{ selectedCard.last_four_digits }}</div>
              <div>{{ selectedCard.name_on_card }}</div>
              <div>Expires: {{ selectedCard.expiration_month }}/{{ selectedCard.expiration_year }}</div>
            </div>
          </div>
        </div>

        <!-- Error Message -->
        <div v-if="error" class="alert alert-error">
          <span>{{ error }}</span>
        </div>

        <!-- Success Message -->
        <div v-if="success" class="alert alert-success">
          <span>{{ success }}</span>
        </div>
      </div>

      <!-- Footer -->
      <div class="flex justify-end gap-4 p-6 border-t">
        <button @click="close" class="btn btn-ghost" :disabled="loading">Cancel</button>
        <button
          @click="handlePreauthorize"
          class="btn btn-warning"
          :disabled="loading || !chargeAmount"
        >
          <span v-if="loading && action === 'preauthorize'" class="loading loading-spinner loading-sm"></span>
          Preauthorize
        </button>
        <button
          @click="handleChargeNow"
          class="btn btn-primary"
          :disabled="loading || !chargeAmount"
        >
          <span v-if="loading && action === 'charge'" class="loading loading-spinner loading-sm"></span>
          Charge Now
        </button>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import axios from 'axios'
import { notify } from "@kyvg/vue3-notification"

export default defineComponent({
  name: 'PaymentAuthorizePopup',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    delivery: {
      type: Object,
      required: true
    },
    customer: {
      type: Object,
      required: true
    },
    creditCards: {
      type: Array,
      default: () => []
    },
    pricing: {
      type: Object,
      required: true
    },
    promoActive: {
      type: Boolean,
      default: false
    },
    promo: {
      type: Object,
      default: () => ({})
    },
    totalAmount: {
      type: Number,
      required: true
    },
    totalAmountAfterDiscount: {
      type: Number,
      required: true
    },
    discount: {
      type: Number,
      default: 0
    }
  },
  emits: ['close', 'payment-success'],
  data() {
    return {
      chargeAmount: 0,
      loading: false,
      action: '', // 'preauthorize' or 'charge'
      error: '',
      success: ''
    }
  },
  computed: {
    selectedCard(): any {
      // Find the card that matches the delivery's payment_card_id
      return this.creditCards.find((card: any) => card.id === this.delivery.payment_card_id)
    }
  },
  watch: {
    show(newVal) {
      if (newVal) {
        // Pre-populate with total amount when popup opens
        this.chargeAmount = this.promoActive ? this.totalAmountAfterDiscount : this.totalAmount
        this.error = ''
        this.success = ''
      }
    }
  },
  methods: {
    close() {
      this.$emit('close')
    },

    calculateSubtotal() {
      const gallons = this.delivery.gallons_ordered || 0
      const pricePerGallon = this.delivery.customer_price || 0
      return (gallons * pricePerGallon).toFixed(2)
    },

    async handlePreauthorize() {
      await this.processPayment('preauthorize')
    },

    async handleChargeNow() {
      await this.processPayment('charge')
    },

    async processPayment(actionType: string) {
      if (!this.selectedCard) {
        this.error = 'No credit card found for this customer'
        return
      }

      this.loading = true
      this.action = actionType
      this.error = ''
      this.success = ''

      try {
        const endpoint = actionType === 'preauthorize' ? 'authorize' : 'charge'
        const payload = {
          card_number: (this.selectedCard as any).card_number,
          expiration_date: `${(this.selectedCard as any).expiration_month}${(this.selectedCard as any).expiration_year}`,
          cvv: (this.selectedCard as any).security_number,
          [actionType === 'preauthorize' ? 'preauthorize_amount' : 'charge_amount']: this.chargeAmount.toString(),
          transaction_type: actionType === 'preauthorize' ? 1 : 0,
          service_id: this.delivery.service_id || null,  // Add service_id from delivery
          delivery_id: this.delivery.id,  // Add delivery_id from delivery
          card_id: (this.selectedCard as any).id  // Add card_id from selected card
        }

        console.log('=== DEBUG: PaymentAuthorizePopup payload ===')
        console.log('Delivery object:', this.delivery)
        console.log('Delivery ID:', this.delivery.id)
        console.log('Service ID:', this.delivery.service_id)
        console.log('Final payload being sent:', payload)
        console.log('Endpoint:', endpoint)
        const response = await axios.post(
          `${import.meta.env.VITE_AUTHORIZE_URL}/api/${endpoint}/?customer_id=${this.customer.id}`,
          payload,
          { withCredentials: true }
        )

        if (response.data && response.data.status === 0) {
          this.success = `${actionType === 'preauthorize' ? 'Preauthorization' : 'Charge'} successful! Transaction ID: ${response.data.auth_net_transaction_id || 'N/A'}`
          this.$emit('payment-success', {
            action: actionType,
            transaction: response.data
          })
          setTimeout(() => this.close(), 2000)
        } else {
          throw new Error(`Payment ${actionType} failed: ${response.data?.status || 'Unknown error'}`)
        }
      } catch (error: any) {
        this.error = error.response?.data?.detail || `Failed to ${actionType} payment`
        notify({
          title: "Error",
          text: this.error,
          type: "error",
        })
      } finally {
        this.loading = false
        this.action = ''
      }
    }
  }
})
</script>

<style scoped>
/* Additional styles if needed */
</style>
