<!-- src/pages/pay/service/capture_authorize.vue -->
<template>
  <div class="flex">
    <!-- Main container with responsive horizontal padding -->
    <div class="w-full px-4 py-4 md:px-6">
      <div v-if="service" 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>
            <router-link :to="{ name: 'customerProfile', params: { id: service.customer_id } }">
              {{ service.customer_name }}
            </router-link>
          </li>
          <li>Capture Service #{{ service.id }}</li>
        </ul>
      </div>

      <!-- Page Header -->
      <div class="flex flex-wrap items-center justify-between gap-2 mt-4">
        <h1 class="text-3xl font-bold">
          Capture Charge for Service #{{ service?.id }}
        </h1>
        <router-link v-if="service" :to="{ name: 'customerProfile', params: { id: service.customer_id } }">
          <button class="btn btn-sm btn-secondary">Back to Customer</button>
        </router-link>
      </div>

      <!-- Main Content Grid -->
      <div v-if="service" class="grid grid-cols-1 gap-6 mt-6 lg:grid-cols-2">
        <!-- LEFT COLUMN: Customer and Service Details -->
        <div class="space-y-6">
          <!-- Customer Info Card -->
          <div class="p-5 rounded-lg bg-neutral">
            <div class="mb-2 text-xl font-bold">Customer</div>
            <div>
              <div class="font-bold">{{ service.customer_name }}</div>
              <div>{{ service.customer_address }}</div>
              <div v-if="service.customer_apt && service.customer_apt !== 'None'">{{ service.customer_apt }}</div>
              <div>
                {{ service.customer_town }}, {{ stateName }} {{ service.customer_zip }}
              </div>
            </div>
          </div>

          <!-- Service Details Card -->
          <div class="p-5 rounded-lg bg-neutral">
            <h3 class="mb-4 text-xl font-bold">Service Details</h3>
            <div class="grid grid-cols-1 gap-y-3 text-sm">
              <div>
                <div class="font-bold">Service Type</div>
                <div class="opacity-80">{{ serviceTypeName }}</div>
              </div>
              <div>
                <div class="font-bold">Scheduled Date</div>
                <div class="opacity-80">{{ service.scheduled_date }}</div>
              </div>
              <div v-if="service.description">
                <div class="font-bold">Description</div>
                <div class="opacity-80">{{ service.description }}</div>
              </div>
            </div>
          </div>

          <!-- Transaction History Card -->
          <div class="p-5 rounded-lg bg-neutral">
            <h3 class="mb-4 text-xl font-bold">Transaction History</h3>
            <div v-if="serviceTransactions.length === 0" class="text-sm opacity-80">
              <p>No transactions found for this service.</p>
            </div>
            <div v-else class="space-y-3">
              <div
                v-for="transaction in serviceTransactions"
                :key="transaction.id"
                class="p-3 bg-base-100 rounded-lg border border-base-300"
              >
                <div class="flex justify-between items-start mb-2">
                  <div class="text-sm">
                    <div class="font-bold">Transaction ID: {{ transaction.id }}</div>
                    <div class="opacity-70">{{ transaction.created_at ? formatDateTime(transaction.created_at) : 'N/A' }}</div>
                  </div>
                  <div class="badge"
                       :class="{
                         'badge-success': transaction.status === 0,
                         'badge-warning': transaction.status === 1,
                         'badge-error': transaction.status === 2,
                         'badge-info': transaction.status === 3,
                       }">
                    {{ getTransactionStatus(transaction.status) }}
                  </div>
                </div>

                <div class="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <div class="font-bold">Preauth Amount</div>
                    <div class="font-mono">${{ formatCurrency(transaction.preauthorize_amount) }}</div>
                  </div>
                  <div>
                    <div class="font-bold">Charge Amount</div>
                    <div class="font-mono">${{ formatCurrency(transaction.charge_amount) }}</div>
                  </div>
                  <div>
                    <div class="font-bold">Transaction Type</div>
                    <div>{{ getTransactionType(transaction.transaction_type) }}</div>
                  </div>
                  <div>
                    <div class="font-bold">Auth Transaction ID</div>
                    <div class="font-mono text-xs">{{ transaction.auth_net_transaction_id || 'N/A' }}</div>
                  </div>
                </div>

                <div v-if="transaction.rejection_reason" class="mt-2 p-2 bg-error/10 border border-error/20 rounded text-sm">
                  <div class="font-bold text-error">Rejection Reason:</div>
                  <div class="text-error">{{ transaction.rejection_reason }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- RIGHT COLUMN: Cards and Payment Form -->
        <div class="space-y-6">
          <!-- Credit Cards Display -->
          <div class="p-5 rounded-lg bg-neutral">
            <h3 class="text-xl font-bold mb-4">Pre-authorized Card</h3>
            <div v-if="!preAuthCard" class="mt-2 text-sm opacity-70">
              <p class="font-semibold text-warning">No pre-authorized card found.</p>
            </div>
            <div class="mt-4">
              <div class="p-2 border rounded-lg bg-base-200 border-base-300" v-if="preAuthCard">
                <div class="flex items-start justify-between">
                  <div>
                    <div class="text-sm font-bold">{{ preAuthCard.name_on_card }}</div>
                    <div class="text-xs opacity-70">{{ preAuthCard.type_of_card }}</div>
                  </div>
                  <div v-if="preAuthCard.main_card" class="badge badge-primary badge-sm">Primary</div>
                </div>
                <div class="mt-1 font-mono text-sm tracking-wider">
                  <p>{{ preAuthCard.card_number }}</p>
                  <p>Exp: {{ formattedExpiration(preAuthCard) }}</p>
                  <p>{{ preAuthCard.security_number }}</p>
                </div>
              </div>
            </div>

            <!-- Payment Form - always shown -->
            <div class="pt-4 mt-6 space-y-4 border-t border-base-300">
              <div v-if="preAuthAmount && preAuthAmount > 0" class="mb-2 text-sm text-orange-600">Preauthorization amount: ${{ preAuthAmount.toFixed(2) }}</div>
              <div class="form-control">
                <div class="relative">
                  <span class="absolute left-3 top-1/2 transform -translate-y-1/2 text-sm z-10">$</span>
                  <input
                    v-model="chargeAmount"
                    class="w-full input input-bordered input-sm pl-6"
                    type="number"
                    step="0.01"
                    placeholder="0.00"
                  />
                </div>
              </div>

              <div class="flex gap-4">
                <button
                  class="flex-1 btn btn-success"
                  :disabled="isSubmitting || !chargeAmount || chargeAmount <= 0 || !selectedCard"
                  @click="chargeService"
                >
                  <span v-if="isSubmitting" class="loading loading-spinner loading-sm"></span>
                  Capture Charge
                </button>
                <button class="btn btn-ghost" :disabled="isSubmitting" @click="cancelCharge">
                  Cancel
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Loading State -->
      <div v-else class="p-10 text-center">
        <span class="loading loading-spinner loading-lg"></span>
        <p class="mt-2">Loading service details...</p>
      </div>
    </div>
  </div>

  <!-- Payment Capture Success Modal -->
  <div class="modal" :class="{ 'modal-open': showPaymentModal }">
    <div class="modal-box">
      <h3 class="font-bold text-lg">Payment Captured Successfully</h3>
      <div class="py-4">
        <div v-if="modalStep === 0" class="text-center">
          <span class="text-lg mb-3">Transaction ID: {{ transaction?.auth_net_transaction_id }}</span>
          <div class="loading loading-spinner loading-lg text-success mb-3"></div>
          <p class="text-sm text-gray-600">Processing payment capture...</p>
        </div>
        <div v-else-if="modalStep === 1" class="text-center">
          <span class="text-lg mb-3">Transaction ID: {{ transaction?.auth_net_transaction_id }}</span>
          <p class="text-lg">Captured Amount: ${{ modalCapturedAmount }}</p>
        </div>
      </div>
    </div>
  </div>
  
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import authHeader from '../../../services/auth.header';
import { notify } from "@kyvg/vue3-notification";

// --- Interfaces for Type Safety ---
interface UserCard {
  id: number;
  name_on_card: string;
  type_of_card: string;
  main_card: boolean;
  card_number: string;
  expiration_month: number;
  expiration_year: number;
  security_number: string;
}

interface ServiceTransaction {
  id: number;
  preauthorize_amount: number;
  charge_amount: number;
  transaction_type: number;
  status: number;
  created_at: string;
  auth_net_transaction_id?: string;
  rejection_reason?: string;
  delivery_id?: number;
  service_id?: number;
  card_id?: number;
}

interface Service {
  id: number;
  customer_id: number;
  customer_name: string;
  customer_address: string;
  customer_apt: string;
  customer_town: string;
  customer_state: number;
  customer_zip: string;
  type_service_call: number;
  scheduled_date: string;
  description: string;
  service_cost: number;
  payment_card_id?: number;
}

// --- Component State ---
const route = useRoute();
const router = useRouter();

const isSubmitting = ref(false);
const service = ref<Service | null>(null);
const preAuthCard = ref<UserCard | null>(null);
const selectedCard = ref<UserCard | null>(null);
const chargeAmount = ref<number>(0);
const transaction = ref<ServiceTransaction | null>(null);
const preAuthAmount = ref<number>(0);
const serviceTransactions = ref<ServiceTransaction[]>([]);
const showPaymentModal = ref(false);
const modalStep = ref(0);
const modalCapturedAmount = ref(0);

// --- Computed Properties for Cleaner Template ---
const stateName = computed(() => {
  const stateMap: Record<number, string> = {
    0: 'Massachusetts', 1: 'Rhode Island', 2: 'New Hampshire', 3: 'Maine',
    4: 'Vermont', 5: 'Maine', 6: 'New York',
  };
  return service.value ? stateMap[service.value.customer_state] || 'Unknown state' : '';
});

const serviceTypeName = computed(() => {
  const typeMap: Record<number, string> = {
    0: 'Tune-up', 1: 'No Heat', 2: 'Fix', 3: 'Tank Install', 4: 'Other',
  };
  return service.value ? typeMap[service.value.type_service_call] || 'Unknown' : '';
});

// --- Additional Utility Functions ---
const formattedExpiration = (card: UserCard) => {
  const month = String(card.expiration_month).padStart(2, '0');
  return `${month} / ${card.expiration_year}`;
};

const formatCurrency = (value: number): string => {
  if (value === null || value === undefined || isNaN(value)) return '$0.00';
  return value.toFixed(2);
};

const formatDateTime = (dateString: string): string => {
  if (!dateString) return 'N/A';
  try {
    const date = new Date(dateString);
    return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  } catch {
    return 'N/A';
  }
};

const getTransactionStatus = (status: number): string => {
  const statuses: { [key: number]: string } = {
    0: 'Approved',
    1: 'Pending',
    2: 'Declined',
    3: 'Captured',
    4: 'Voided',
    5: 'Settled',
  };
  return statuses[status] || 'Unknown';
};

const getTransactionType = (type: number): string => {
  const types: { [key: number]: string } = {
    0: 'Charge',
    1: 'Pre-authorization',
    2: 'Void',
    3: 'Refund',
    4: 'Capture',
  };
  return types[type] || 'Unknown';
};


// --- Methods ---



/**
 * Dedicated function to update the service cost using the new dedicated API
 */
const updateServiceCost = async (serviceId: number, newCost: number): Promise<boolean> => {
  try {
    console.log(`🎯 UPDATING SERVICE COST: Service ${serviceId} → $${newCost}`);

    const response = await axios.put(
      `${import.meta.env.VITE_BASE_URL}/service/update-cost/${serviceId}`,
      { service_cost: newCost },
      { withCredentials: true, headers: authHeader() }
    );

    if (response.data.ok) {
      console.log(`✅ SERVICE COST UPDATED SUCCESSFULLY: ${response.data.message}`);
      return true;
    } else {
      console.error(`❌ SERVICE COST UPDATE FAILED:`, response.data);
      return false;
    }
  } catch (err: unknown) {
    const error = err as { response?: { data?: unknown }; message?: string };
    console.error(`💥 ERROR UPDATING SERVICE COST:`, error.response?.data || error.message);
    return false;
  }
};

const chargeService = async () => {
  if (!selectedCard.value || !chargeAmount.value || chargeAmount.value <= 0) {
    notify({ title: "Error", text: "Please select a card and enter a valid amount.", type: "error" });
    return;
  }

  isSubmitting.value = true;
  try {
    // Check if we have an auth transaction ID from transaction history
    const authTransaction = serviceTransactions.value?.find(t => t.auth_net_transaction_id);

    if (!authTransaction?.auth_net_transaction_id) {
      // No auth transaction found, try the original charge flow
      const card = selectedCard.value;
      const expMonth = String(card.expiration_month).padStart(2, '0');
      const expYear = String(card.expiration_year).toString().slice(-2);

      const payload = {
        charge_amount: chargeAmount.value,
        service_id: service.value!.id,
        delivery_id: null,
        transaction_type: 0,
        card_id: card.id,
        card_number: card.card_number,
        expiration_date: `${expMonth}${expYear}`,
        cvv: card.security_number,
      };

      const response = await axios.post(
        `${import.meta.env.VITE_AUTHORIZE_URL}/api/charge/${service.value!.customer_id}`,
        payload,
        { withCredentials: true, headers: authHeader() }
      );

      if (response.data?.status === 0) {
        // Update service cost to the charged amount using the new dedicated function
        await updateServiceCost(service.value!.id, chargeAmount.value);

        // Update payment status to 3 for success
        await axios.put(
          `${import.meta.env.VITE_BASE_URL}/payment/capture/service/${service.value!.id}`,
          {
            card_id: selectedCard.value!.id,
            status: 3
          },
          { withCredentials: true, headers: authHeader() }
        );

        modalCapturedAmount.value = chargeAmount.value;
        showPaymentModal.value = true;
        setTimeout(() => { modalStep.value = 1 }, 2000);
        setTimeout(() => { showPaymentModal.value = false; router.push({ name: 'customerProfile', params: { id: service.value!.customer_id } }) }, 4000);
        return;
      } else {
        const reason = response.data?.rejection_reason || "The charge was declined.";
        notify({ title: "Charge Declined", text: reason, type: "error" });
        return;
      }
    }

    // We have an auth transaction, so capture it
    const capturePayload = {
      charge_amount: chargeAmount.value,
      auth_net_transaction_id: authTransaction.auth_net_transaction_id
    };

    const captureResponse = await axios.post(
      `${import.meta.env.VITE_AUTHORIZE_URL}/api/capture/`,
      capturePayload,
      { withCredentials: true, headers: authHeader() }
    );

    if (captureResponse.data?.status === 0) {
      // Update service cost to the captured amount using the new dedicated function
      await updateServiceCost(service.value!.id, chargeAmount.value);

      // Update service payment status
      await axios.put(
        `${import.meta.env.VITE_BASE_URL}/payment/capture/service/${service.value!.id}`,
        {
          card_id: selectedCard.value!.id,
          status: 3
        },
        { withCredentials: true, headers: authHeader() }
      );

      modalCapturedAmount.value = chargeAmount.value;
      showPaymentModal.value = true;
      setTimeout(() => { modalStep.value = 1 }, 2000);
      setTimeout(() => { showPaymentModal.value = false; router.push({ name: 'customerProfile', params: { id: service.value!.customer_id } }) }, 4000);
    } else if (captureResponse.data?.status === 1) {
      const reason = captureResponse.data.rejection_reason || "The payment was declined by the gateway.";
      notify({ title: "Payment Declined", text: reason, type: "warn" });
    } else {
      throw new Error("Invalid response from server during capture.");
    }

  } catch (err: unknown) {
    const error = err as { response?: { data?: { detail?: string } }; message?: string };
    const detail = error.response?.data?.detail || "Failed to process payment due to a server error.";
    notify({ title: "Error", text: detail, type: "error" });
    console.error("Charge/Capture Service Error:", error);
  } finally {
    isSubmitting.value = false;
  }
};

const cancelCharge = () => {
  if (service.value) {
    router.push({ name: 'customerProfile', params: { id: service.value.customer_id } });
  }
};

const getTransaction = async () => {
  const serviceId = route.params.id;
  const path = `${import.meta.env.VITE_AUTHORIZE_URL}/api/transaction/service/${serviceId}`;
  try {
    const response = await axios.get(path, { withCredentials: true, headers: authHeader() });
    transaction.value = response.data;
    preAuthAmount.value = parseFloat(response.data.preauthorize_amount || service.value?.service_cost || 0);
    if (response.data.status !== 0) {
      preAuthAmount.value = 0;
    } else if (response.data.card_id) {
      const cardResponse = await axios.get(`${import.meta.env.VITE_BASE_URL}/payment/card/${response.data.card_id}`, { withCredentials: true, headers: authHeader() });
      preAuthCard.value = cardResponse.data;
      selectedCard.value = cardResponse.data;
      chargeAmount.value = preAuthAmount.value;
    }
  } catch (error: unknown) {
    console.error("No pre-authorized transaction found for service:", error);
    preAuthAmount.value = service.value?.service_cost || 0;
  }
};

// --- Lifecycle Hook ---
onMounted(async () => {
  const serviceId = route.params.id;
  if (!serviceId) {
    notify({ title: "Error", text: "No service ID provided.", type: "error" });
    router.push({ name: 'customer' });
    return;
  }

  try {
    // Fetch Service Details
    const servicePath = `${import.meta.env.VITE_BASE_URL}/service/${serviceId}`;
    const serviceResponse = await axios.get(servicePath, { withCredentials: true, headers: authHeader() });

    if (serviceResponse.data?.ok) {
      service.value = serviceResponse.data.service;
      chargeAmount.value = service.value?.service_cost || 0;

      // Fetch transaction history for this service
      try {
        const transactionPath = `${import.meta.env.VITE_BASE_URL}/payment/transactions/service/${serviceId}`;
        const transactionResponse = await axios.get(transactionPath, { withCredentials: true, headers: authHeader() });
        serviceTransactions.value = Array.isArray(transactionResponse.data) ? transactionResponse.data : [];
      } catch (error) {
        console.error("Failed to fetch transaction history:", error);
        serviceTransactions.value = [];
      }

      // Fetch pre-auth transaction
      await getTransaction();

      // If no card from transaction but service has payment_card_id, fetch directly
      if (!preAuthCard.value && service.value?.payment_card_id) {
        try {
          const cardResponse = await axios.get(`${import.meta.env.VITE_BASE_URL}/payment/card/${service.value.payment_card_id}`, { withCredentials: true, headers: authHeader() });
          preAuthCard.value = cardResponse.data;
          selectedCard.value = cardResponse.data;
          // Keep the chargeAmount as service_cost, since there's no preauth amount
        } catch (error) {
          console.error("Failed to fetch card from service payment_card_id:", error);
        }

        // Check if we have transactions with preauth amounts to set the global preAuthAmount
        if (serviceTransactions.value.length > 0 && preAuthAmount.value === (service.value?.service_cost || 0)) {
          const firstTransaction = serviceTransactions.value.find(t => t.preauthorize_amount && t.preauthorize_amount > 0);
          if (firstTransaction) {
            preAuthAmount.value = firstTransaction.preauthorize_amount;
          }
        }
      }
    } else {
      throw new Error(serviceResponse.data?.error || "Failed to fetch service data.");
    }
  } catch (error) {
    console.error("Error loading page data:", error);
    notify({ title: "Error", text: "Service not found or could not be loaded.", type: "error" });
    router.push({ name: 'customer' });
  }
});
</script>
