<!-- src/pages/pay/auto/capture_authorize_autho.vue -->
<template>
  <div class="flex">

    <!-- Main container with responsive horizontal padding -->
    <div class="w-full px-4 md:px-6 py-4">
      <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 && customer.id">
            <router-link :to="{ name: 'customerProfile', params: { id: customer.id } }">
              {{ customer.customer_first_name }} {{ customer.customer_last_name }}
            </router-link>
          </li>
          <li>Capture Auto Payment #{{ autoTicket.id }}</li>
        </ul>
      </div>

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

      <!-- Main Content Grid -->
      <div v-if="autoTicket.id" class="grid grid-cols-1 lg:grid-cols-2 gap-6 mt-6">

        <!-- LEFT COLUMN: Customer and Auto Ticket Details -->
        <div class="space-y-6">

          <!-- Customer Info Card -->
          <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>)
              </div>
            </div>
          </div>

          <!-- Financial Summary Card -->
          <div class="bg-neutral rounded-lg p-5">
            <h3 class="text-xl font-bold mb-4">Financial Summary</h3>
            <div class="space-y-2">
              <div class="flex justify-between">
                <span>Gallons Delivered:</span>
                <span>{{ gallonsDelivered || 0 }} gallons</span>
              </div>
              <div class="flex justify-between">
                <span>Price per Gallon:</span>
                <span>${{ autoTicket.price_per_gallon || 0 }}</span>
              </div>
              <hr class="my-3">
              <div class="flex justify-between font-bold text-lg">
                <span>Total:</span>
                <span>${{ autoTicket.total_amount_customer || 0 }}</span>
              </div>
            </div>
          </div>

          <!-- Auto Ticket Details Card -->
          <div class="bg-neutral rounded-lg p-5">
            <h3 class="text-xl font-bold mb-4">Auto Ticket Details</h3>
            <div class="grid grid-cols-2 gap-x-4 gap-y-3 text-sm">
              <div>
                <div class="font-bold">Fill Date</div>
                <div class="opacity-80">{{ autoTicket.fill_date }}</div>
              </div>
              <div>
                <div class="font-bold">Account Number</div>
                <div class="opacity-80">{{ autoTicket.account_number }}</div>
              </div>
            </div>
          </div>

          <!-- Transaction Summary -->
          <div v-if="transaction && transaction.auth_net_transaction_id" class="bg-neutral rounded-lg p-5">
            <h3 class="text-xl font-bold mb-4">Transaction Summary</h3>
            <div class="space-y-3">
              <div class="grid grid-cols-2 gap-x-4 gap-y-3 text-sm">
                <div class="flex justify-between">
                  <span class="font-bold">Transaction ID:</span>
                  <span class="font-mono">{{ transaction.auth_net_transaction_id }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="font-bold">Pre-Auth Amount:</span>
                  <span>${{ transaction.preauthorize_amount || '0.00' }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="font-bold">Charge Amount:</span>
                  <span>${{ transaction.charge_amount || '0.00' }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="font-bold">Type:</span>
                  <span :class="getTypeColor(transaction.transaction_type)">{{ transaction.transaction_type === 0 ? 'Charge' : transaction.transaction_type === 1 ? 'Auth' : 'Capture' }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="font-bold">Date:</span>
                  <span>{{ transaction.created_at }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="font-bold">Status:</span>
                  <span :class="transaction.status === 0 ? 'text-success' : 'text-error'">
                    {{ transaction.status === 0 ? 'Approved' : 'Declined' }}
                  </span>
                </div>
              </div>
            </div>
          </div>

          <!-- Credit Card Details -->
          <div v-if="userCardfound" class="bg-neutral rounded-lg p-5">
            <h3 class="text-xl font-bold mb-4">Payment Method</h3>
            <div class="p-2 rounded-lg border" :class="userCard.main_card ? 'bg-primary/10 border-primary' : 'bg-base-200 border-base-300'">
              <div class="flex justify-between items-start">
                <div>
                  <div class="font-bold text-sm">{{ userCard.name_on_card }}</div>
                  <div class="text-xs opacity-70">{{ userCard.type_of_card }}</div>
                </div>
                <div v-if="userCard.main_card" class="badge badge-primary badge-sm">Primary</div>
              </div>
              <div class="mt-1 text-sm font-mono tracking-wider">
                <p>**** **** **** {{ userCard.last_four_digits }}</p>
                <p>Exp: <span v-if="Number(userCard.expiration_month) < 10">0</span>{{ userCard.expiration_month }} / {{ userCard.expiration_year }}</p>
              </div>
            </div>
          </div>

        </div>

        <!-- RIGHT COLUMN: Capture Form -->
        <div class="space-y-6">

          <!-- Gallons Delivered Display -->
          <div class="bg-base-100 rounded-lg p-5">
            <h2 class="text-2xl font-bold mb-4">Gallons Delivered</h2>
            <div class="text-center">
              <div class="text-4xl font-bold text-success">{{ gallonsDelivered || '0.00' }}</div>
              <div class="text-sm opacity-70">gallons</div>
            </div>
          </div>

          <!-- Capture Payment Form -->
          <div class="bg-base-100 rounded-lg p-5">
            <h2 class="text-2xl font-bold mb-4">Capture Payment</h2>
            <div class="space-y-4">
              <div class="form-control">
                <label class="label">
                  <span class="label-text font-bold">Capture Amount</span>
                </label>
                <div v-if="captureAmount > preAuthAmount" class="text-sm text-error mb-2">
                  Cannot capture more than the preauthorization amount.
                </div>
                <input
                  v-model="captureAmount"
                  class="input input-bordered input-sm w-full"
                  type="number"
                  step="0.01"
                  placeholder="0.00"
                />
              </div>



              <div class="flex gap-4">
                <button
                  v-if="Number(autoTicket.payment_status) === 1"
                  @click="capturePayment"
                  :class="`btn flex-1 ${captureAmount > 0 ? 'btn-success' : 'btn-error'}`"
                  :disabled="loading || !captureAmount || captureAmount > preAuthAmount"
                >
                  <span v-if="loading" class="loading loading-spinner loading-sm"></span>
                  Capture Payment
                </button>
                <button
                  @click="cancelCapture"
                  class="btn btn-ghost"
                  :disabled="loading"
                >
                  Cancel
                </button>
              </div>
            </div>
          </div>

        </div>
      </div>
      <div v-else class="text-center p-10">
        Loading capture details...
      </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 } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import authHeader from '../../../services/auth.header'
import { notify } from "@kyvg/vue3-notification"
import type {
  AxiosResponse,
  AxiosError,
  CustomerFormData,
  CreditCardFormData,
  PricingData,
  CustomerDescriptionData,
  AutoTicketData,
  AutoDeliveryData,
  PaymentCardResponse,
  AuthorizeNetTransactionResponse
} from '../../../types/models'

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

// Reactive data
const loading = ref(false)
const userCardfound = ref(false)
const gallonsDelivered = ref('')
const captureAmount = ref(0)
const preAuthAmount = ref(0)
const transaction = ref<AuthorizeNetTransactionResponse | null>(null)
const showPaymentModal = ref(false)
const modalStep = ref(0)
const modalCapturedAmount = ref(0)

const userCard = ref<CreditCardFormData>({
  id: 0,
  date_added: '',
  user_id: '',
  card_number: '',
  last_four_digits: '',
  name_on_card: '',
  expiration_month: '',
  expiration_year: '',
  type_of_card: '',
  security_number: '',
  accepted_or_declined: '',
  main_card: false,
})
const customerDescription = ref<CustomerDescriptionData>({
  customer_id: 0,
  account_number: '',
  company_id: 0,
  fill_location: 0,
  description: '',
})
const customer = ref<CustomerFormData>({
  id: 0,
  user_id: 0,
  customer_address: '',
  customer_first_name: '',
  customer_last_name: '',
  customer_town: '',
  customer_state: 0,
  customer_zip: '',
  customer_apt: '',
  customer_home_type: 0,
  customer_phone_number: '',
  account_number: '',
})
const autoDelivery = ref<AutoDeliveryData>({
  id: 0,
  customer_id: 0,
  account_number: '',
  customer_town: '',
  customer_state: 0,
  customer_address: '',
  customer_zip: '',
  customer_full_name: '',
  last_fill: '',
  days_since_last_fill: 0,
  last_updated: '',
  estimated_gallons_left: 0,
  estimated_gallons_left_prev_day: 0,
  tank_height: '',
  tank_size: '',
  house_factor: 0,
  auto_status: 0,
  open_ticket_id: null,
  confidence_score: 20,
  k_factor_source: 'default',
  days_remaining: 999,
  gallons_per_day: 0,
})
const autoTicket = ref<AutoTicketData>({
  id: 0,
  customer_id: '',
  account_number: '',
  customer_town: '',
  customer_state: '',
  customer_address: '',
  customer_zip: '',
  customer_full_name: '',
  oil_prices_id: '',
  fill_date: '',
  gallons_delivered: '',
  price_per_gallon: '',
  total_amount_customer: '',
  payment_type: '',
  payment_card_id: '',
  payment_status: 0,
  open_ticket_id: 0
})

const pricing = ref<PricingData>({
  price_from_supplier: 0,
  price_for_customer: 0,
  price_for_employee: 0,
  price_same_day: 0,
  price_prime: 0,
  price_emergency: 0,
  date: "",
})

const total_amount = ref(0)
const discount = ref(0)
const total_amount_after_discount = ref(0)

// Lifecycle
onMounted(() => {
  getAutoTicket(route.params.id)
  getTransaction()
})

// Functions
const getAutoTicket = (delivery_id: number | string) => {
  let path = import.meta.env.VITE_AUTO_URL + "/delivery/autoticket/" + delivery_id;
  axios({
    method: "get",
    url: path,
    withCredentials: true,
  })
    .then((response: AxiosResponse<AutoTicketData>) => {
      autoTicket.value = response.data;
      console.log(autoTicket.value)
      gallonsDelivered.value = autoTicket.value.gallons_delivered;
      captureAmount.value = parseFloat(autoTicket.value.total_amount_customer || '0');
      getCustomer(autoTicket.value.customer_id)

      getAutoDelivery(autoTicket.value.id)
      getCustomerDescription(autoTicket.value.customer_id)
      if (autoTicket.value.payment_card_id) {
        getPaymentCard(autoTicket.value.payment_card_id)
      }

    })
    .catch(() => {
      notify({
        title: "Error",
        text: "Could not get automatic",
        type: "error",
      });
    });
}

const getAutoDelivery = (delivery_id: number) => {
  let path = import.meta.env.VITE_AUTO_URL + "/delivery/finddelivery/" + delivery_id;
  axios({
    method: "get",
    url: path,
    withCredentials: true,
  })
    .then((response: AxiosResponse<AutoDeliveryData>) => {

      autoDelivery.value = response.data;
      getCustomer(autoDelivery.value.customer_id)
      getCustomerDescription(autoDelivery.value.customer_id)

    })
    .catch(() => {
      notify({
        title: "Error",
        text: "Could not get automatic",
        type: "error",
      });
    });
}

const getPaymentCard = (card_id: number | string) => {
  let path = import.meta.env.VITE_BASE_URL + "/payment/card/" + card_id;
  axios({
    method: "get",
    url: path,
    withCredentials: true,
  })
    .then((response: AxiosResponse<{ ok?: boolean; card?: CreditCardFormData }>) => {
      const card = response.data?.card;
      if (!card || card.card_number === ''){
        userCardfound.value = false;
      }
      else{
        userCard.value = card as CreditCardFormData;
        userCardfound.value = true;
      }
    })
    .catch(() => {
    });
}

const getCustomer = (user_id: number | string) => {
  const path = `${import.meta.env.VITE_BASE_URL}/customer/${user_id}`;
  axios.get(path, { withCredentials: true, headers: authHeader() })
    .then((response: AxiosResponse<{ ok?: boolean; customer?: CustomerFormData }>) => {
      customer.value = response.data?.customer || (response.data as unknown as CustomerFormData);
    })
    .catch((error: Error) => {
      notify({ title: "Error", text: "Could not find customer", type: "error" });
      console.error("Error fetching customer:", error);
    });
}

const getCustomerDescription = (user_id: number | string) => {
  let path = import.meta.env.VITE_BASE_URL + "/customer/description/" + user_id;
  axios({
    method: "get",
    url: path,
    withCredentials: true,
  })
    .then((response: AxiosResponse<{ ok?: boolean; description?: CustomerDescriptionData }>) => {
      customerDescription.value = response.data?.description || (response.data as unknown as CustomerDescriptionData);
      loading.value = false
    })
    .catch(() => {
      notify({
        title: "Error",
        text: "Could not find customer",
        type: "error",
      });
    });
}

const getTransaction = () => {
  const path = `${import.meta.env.VITE_AUTHORIZE_URL}/api/auto/transaction/delivery/${route.params.id}`;
  axios.get(path, { withCredentials: true, headers: authHeader() })
    .then((response: AxiosResponse<AuthorizeNetTransactionResponse>) => {
      transaction.value = response.data;
      preAuthAmount.value = parseFloat(String(response.data.preauthorize_amount) || '0');
      if (response.data.status !== 0) { // Not approved
        preAuthAmount.value = 0;
      }
    })
    .catch((error: AxiosError) => {
      if (error.response && error.response.status === 404) {
        notify({ title: "Info", text: "No pre-authorization found. Redirecting to customer profile to update payment method.", type: "info" });
        console.log("No transaction found for Automatic - redirecting to customer profile");
        router.push({ name: 'customerProfile', params: { id: customer.value.id } });
      } else {
        notify({ title: "Error", text: "No pre-authorized transaction found", type: "error" });
        router.push({ name: 'finalizeTicketAuto', params: { id: route.params.id } });
      }
    });
}

const capturePayment = async () => {
  if (autoTicket.value.payment_status !== 1) {
    notify({ title: "Error", text: "Payment already captured or not ready for capture", type: "error" });
    return;
  }

  if (!transaction.value || !captureAmount.value) {
    notify({ title: "Error", text: "Invalid capture amount or transaction data", type: "error" });
    return;
  }

  loading.value = true;

  try {
    const payload = {
      charge_amount: captureAmount.value,
      auth_net_transaction_id: transaction.value.auth_net_transaction_id
    };

    const url = `${import.meta.env.VITE_AUTHORIZE_URL}/api/capture/`;

    const response = await axios.post(
      url,
      payload,
      { withCredentials: true, headers: authHeader() }
    );

    if (response.data && response.data.status === 0) {
      autoTicket.value.payment_status = 3; // Update local status immediately
      modalCapturedAmount.value = captureAmount.value;
      showPaymentModal.value = true;
      // Close the ticket and unassign from delivery
      closeTicket(autoTicket.value.id);
      setTimeout(() => { modalStep.value = 1 }, 2000);
      setTimeout(() => { showPaymentModal.value = false; router.push({ name: 'auto' }) }, 4000);
    } else if (response.data && response.data.status === 1) {
      const reason = response.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 AxiosError<{ detail?: string }>;
    const detail = error.response?.data?.detail || "Failed to capture payment due to a server error.";
    notify({
      title: "Error",
      text: detail,
      type: "error",
    });
    console.error("Capture Payment Error:", error);
  } finally {
    loading.value = false;
  }
}

const cancelCapture = () => {
  router.push({ name: 'finalizeTicketAuto', params: { id: route.params.id } });
}

const closeTicket = async (ticket_id: number) => {
  const path = `${import.meta.env.VITE_AUTO_URL}/confirm/auto/close_ticket/${ticket_id}`;
  axios.put(path, {}, { withCredentials: true })
    .then(() => {
      console.log("Ticket closed successfully");
    })
    .catch((error: Error) => {
      notify({
        title: "Warning",
        text: "Payment captured, but failed to close ticket. Check manually.",
        type: "warn",
      });
      console.error("Error closing ticket:", error);
    });
}

const getTypeColor = (transactionType: number) => {
  switch (transactionType) {
    case 1: return 'text-blue-600';    // Auth
    case 0: return 'text-orange-600';   // Charge
    case 2: return 'text-purple-600';   // Capture
    case 3: return 'text-green-600';    // Delivery/Other
    default: return 'text-gray-600';
  }
}
</script>

<style scoped></style>
