<!-- src/pages/delivery/create.vue -->
<template>
  
  <div class="flex">

    <!-- Main container with reduced 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>
        </ul>
      </div>

      <!-- 
        NEW LAYOUT: A single 2-column grid for the whole page.
        Gaps and spacing are reduced for a more compact feel.
      -->
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-4 mt-4">

        <!-- LEFT COLUMN: Primary Information & Actions -->
        <div class="space-y-4">
          
          <!-- 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 v-if="customer && customer.id" :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 }}, {{ customerStateName }} {{ customer.customer_zip }}</div>
              <div class="mt-2">{{ customer.customer_phone_number }}</div>
            </div>
          </div>
          
          <!-- Create Delivery Form (now in the left column) -->
          <div class="bg-neutral rounded-lg p-4">
            <h2 class="text-2xl font-bold mb-4">Create Delivery Order</h2>
            <form class="space-y-4" @submit.prevent="onDeliverySubmit">
              <!-- Gallons & Fill -->
              <div>
                <label class="label"><span class="label-text font-bold">Gallons Ordered</span></label>
                <input v-model="formDelivery.gallons_ordered" :disabled="formDelivery.customer_asked_for_fill"
                  :class="inputClasses(v$.formDelivery.gallons_ordered, 'input input-bordered input-sm w-full max-w-xs')" type="number" placeholder="# gallons" />
                <div class="flex flex-wrap gap-2 mt-2">
                 <button v-for="amount in quickGallonAmounts" 
        :key="amount" 
        @click.prevent="setGallons(amount)" 
        :class="['btn', 'btn-xs', selectedGallonsAmount == amount ? 'bg-blue-600 text-white border-blue-600' : 'btn-outline']">
  {{ amount }} gal
</button>
                </div>
                <span v-if="v$.formDelivery.gallons_ordered.$error" class="text-red-500 text-xs mt-1">
                  Required unless "Fill" is checked.
                </span>
              </div>
              <div class="form-control">
                <label class="label cursor-pointer justify-start gap-4">
                  <span class="label-text font-bold">Fill</span>
                  <input v-model="formDelivery.customer_asked_for_fill" type="checkbox" class="checkbox checkbox-sm" />
                </label>
              </div>

              <!-- Payment Section -->
              <div class="p-4 rounded-md space-y-2 border" 
                   :class="{ 'border-red-500 bg-red-50/50': v$.isAnyPaymentMethodSelected.$error }">
                
                <label class="label-text font-bold">Payment Method</label>
              
                <div v-if="v$.isAnyPaymentMethodSelected.$error" class="text-red-600 text-sm font-medium">
                  Please select a payment method.
                </div>
              
                <div class="flex flex-wrap gap-x-6 gap-y-2">
                  <div v-if="userCards.length > 0" class="form-control">
                    <label class="label cursor-pointer gap-2">
                      <span class="label-text">Credit</span>
                      <input v-model="formDelivery.credit" type="checkbox" class="checkbox checkbox-xs" />
                    </label>
                  </div>
                  <div class="form-control">
                    <label class="label cursor-pointer gap-2">
                      <span class="label-text">Cash</span>
                      <input v-model="formDelivery.cash" type="checkbox" class="checkbox checkbox-xs" />
                    </label>
                  </div>
                  <div class="form-control">
                    <label class="label cursor-pointer gap-2">
                      <span class="label-text">Check</span>
                      <input v-model="formDelivery.check" type="checkbox" class="checkbox checkbox-xs" />
                    </label>
                  </div>
                  <div class="form-control">
                    <label class="label cursor-pointer gap-2">
                      <span class="label-text">Other</span>
                      <input v-model="formDelivery.other" type="checkbox" class="checkbox checkbox-xs" />
                    </label>
                  </div>
                </div>
              
                <div v-if="userCards.length > 0 && formDelivery.credit">
                  <label class="label"><span class="label-text">Select Card</span></label>
                  <div class="flex flex-wrap gap-2 mt-2">
                    <!-- --- MODIFICATION --- Full card display -->
                    <button v-for="card in userCards" :key="card.id" @click.prevent="selectCreditCard(card.id)" :class="['btn', 'btn-xs', formDelivery.credit_card_id === card.id ? 'bg-blue-600 text-white border-blue-600' : 'btn-outline']">
                      {{ card.name_on_card }} - {{ card.type_of_card }} - {{ card.card_number }}
                    </button>
                  </div>
                  <span v-if="v$.formDelivery.credit_card_id.$error" class="text-red-500 text-xs mt-1">
                    You must select a credit card when choosing CC option.
                  </span>
                  <!-- --- MODIFICATION --- Added display for estimated pre-auth amount -->
                  <div v-if="preAuthAmount > 0" class="mt-2 text-sm text-info">
                    Estimated Pre-Authorization: <strong>${{ preAuthAmount.toFixed(2) }}</strong>
                  </div>
                </div>
                <div v-if="userCards.length === 0" class="text-sm text-warning">No cards on file for credit payment.</div>
              </div>

              <!-- Date, Driver, Promo -->
              <div>
                <label class="label"><span class="label-text font-bold">Expected Delivery Date</span></label>
                <input v-model="formDelivery.expected_delivery_date" :class="inputClasses(v$.formDelivery.expected_delivery_date, 'input input-bordered input-sm w-full max-w-xs')" type="date" />
                <div class="flex flex-wrap gap-2 mt-2">
                <button @click.prevent="setDeliveryDate(1)" :class="['btn', 'btn-xs', isDeliveryDateSelected(1) ? 'bg-blue-600 text-white border-blue-600' : 'btn-outline']">Tomorrow</button>

                  <button @click.prevent="setDeliveryDate(2)" :class="['btn', 'btn-xs', isDeliveryDateSelected(2) ? 'bg-blue-600 text-white border-blue-600' : 'btn-outline']">In 2 Days</button>
                  <button @click.prevent="setDeliveryDate(3)" :class="['btn', 'btn-xs', isDeliveryDateSelected(3) ? 'bg-blue-600 text-white border-blue-600' : 'btn-outline']">In 3 Days</button>
                     <button @click.prevent="setDeliveryDate(0)" :class="['btn', 'btn-xs', isDeliveryDateSelected(0) ? 'bg-blue-600 text-white border-blue-600' : 'btn-outline']">Today</button>

                </div>
                <span v-if="v$.formDelivery.expected_delivery_date.$error" class="text-red-500 text-xs mt-1">Date is required.</span>
              </div>

              <!-- Optional Section Divider -->
              <div class="flex items-center my-4">
                <div class="flex-grow h-px bg-gray-300"></div>
                <span class="px-3 text-gray-500 text-sm font-medium">Optional</span>
                <div class="flex-grow h-px bg-gray-300"></div>
              </div>

               <div>
                <label class="label"><span class="label-text font-bold">Apply Promotion</span></label>
                <select class="select select-bordered select-sm w-full max-w-xs" v-model="formDelivery.promo_id">
                    <option :value="0">No Promotion</option>
                    <option v-for="promo in promos" :key="promo.id" :value="promo.id">
                        {{ promo.name_of_promotion }} (${{ promo.money_off_delivery }} off)
                    </option>
                </select>
              </div>

              <!-- Fees with Tier Selection -->
               <div class="p-4">
                  <label class="label-text font-bold">Service Fees (Select Tier)</label>
                  <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mt-3">
                      <!-- Same Day Tier -->
                      <div class="form-control">
                        <label class="label"><span class="label-text">Same Day</span></label>
                        <select v-model.number="formDelivery.pricing_tier_same_day" class="select select-bordered select-sm w-full">
                          <option :value="0">None</option>
                          <option :value="1">Tier 1 ({{ formatCurrency(tierPricing.same_day_tier1) }})</option>
                          <option :value="2">Tier 2 ({{ formatCurrency(tierPricing.same_day_tier2) }})</option>
                          <option :value="3">Tier 3 ({{ formatCurrency(tierPricing.same_day_tier3) }})</option>
                          <option :value="4">Tier 4 ({{ formatCurrency(tierPricing.same_day_tier4) }})</option>
                          <option :value="5">Tier 5 ({{ formatCurrency(tierPricing.same_day_tier5) }})</option>
                        </select>
                      </div>
                      <!-- Prime Tier -->
                      <div class="form-control">
                        <label class="label"><span class="label-text">Prime</span></label>
                        <select v-model.number="formDelivery.pricing_tier_prime" class="select select-bordered select-sm w-full">
                          <option :value="0">None</option>
                          <option :value="1">Tier 1 ({{ formatCurrency(tierPricing.prime_tier1) }})</option>
                          <option :value="2">Tier 2 ({{ formatCurrency(tierPricing.prime_tier2) }})</option>
                          <option :value="3">Tier 3 ({{ formatCurrency(tierPricing.prime_tier3) }})</option>
                          <option :value="4">Tier 4 ({{ formatCurrency(tierPricing.prime_tier4) }})</option>
                          <option :value="5">Tier 5 ({{ formatCurrency(tierPricing.prime_tier5) }})</option>
                        </select>
                      </div>
                      <!-- Emergency Tier -->
                      <div class="form-control">
                        <label class="label"><span class="label-text">Emergency</span></label>
                        <select v-model.number="formDelivery.pricing_tier_emergency" class="select select-bordered select-sm w-full">
                          <option :value="0">None</option>
                          <option :value="1">Tier 1 ({{ formatCurrency(tierPricing.emergency_tier1) }})</option>
                          <option :value="2">Tier 2 ({{ formatCurrency(tierPricing.emergency_tier2) }})</option>
                          <option :value="3">Tier 3 ({{ formatCurrency(tierPricing.emergency_tier3) }})</option>
                          <option :value="4">Tier 4 ({{ formatCurrency(tierPricing.emergency_tier4) }})</option>
                          <option :value="5">Tier 5 ({{ formatCurrency(tierPricing.emergency_tier5) }})</option>
                        </select>
                      </div>
                  </div>
              </div>

              <!-- Notes -->
              <div>
                  <label class="label"><span class="label-text font-bold">Dispatcher Notes</span></label>
                  <textarea v-model="formDelivery.dispatcher_notes_taken" rows="3" class="textarea textarea-bordered w-full" placeholder="Notes for the driver..."></textarea>
              </div>

              <!-- --- MODIFICATION --- Added loading state to button -->
              <button type="submit" class="btn btn-primary btn-sm" :disabled="isLoading">
                 <span v-if="isLoading" class="loading loading-spinner loading-xs"></span>
                 {{ isLoading ? 'Processing...' : 'Create Delivery' }}
              </button>
            </form>
          </div>

        </div>

        <!-- RIGHT COLUMN: Reference Information & Secondary Actions -->
        <div class="space-y-4">
        
          <!-- Pricing Chart Card -->
          <div class="bg-neutral rounded-lg p-5">
            <h3 class="text-xl font-bold mb-4">Today's Price Per Gallon</h3>
            <div class="overflow-x-auto">
              <table class="table table-sm w-full">
                <thead>
                  <tr>
                    <th>Gallons</th>
                    <th>Total Price</th>
                  </tr>
                </thead>
                <tbody>
                   <tr v-for="tier in pricingTiers" :key="tier.gallons" :class="isPricingTierSelected(tier.gallons) ? 'bg-blue-600 text-white hover:bg-blue-600' : 'hover'">
                      <td>{{ tier.gallons }}</td>
                      <td>${{ Number(tier.price).toFixed(2) }}</td>
                   </tr>
                </tbody>
              </table>
            </div>
          </div>
          
          <!-- Credit Cards Display -->
          <div v-if="customer && customer.id" class="bg-neutral rounded-lg p-5">
            <div class="flex justify-between items-center">
              <h2 class="text-xl font-bold">Credit Cards</h2>
              <router-link :to="{ name: 'cardadd', params: { id: customer.id } }">
                <button class="btn btn-xs btn-outline btn-success">Add New</button>
              </router-link>
            </div>
            <div class="mt-2 text-sm" v-if="userCards.length === 0">
                <p class="text-warning font-semibold">No cards on file.</p>
            </div>
            <div class="mt-4 space-y-3">
              <!-- Full card display -->
              <div v-for="card in userCards" :key="card.id" class="p-3 rounded-lg border bg-base-200 border-base-300">
                <div>
                  <div class="font-bold text-sm">{{ card.name_on_card }}</div>
                  <div class="text-sm">{{ card.type_of_card }}</div>
                  <div class="text-sm">{{ card.card_number }}</div>
                    <p class="text-sm">Exp: <span v-if="Number(card.expiration_month) < 10">0</span>{{ card.expiration_month }} / {{ card.expiration_year }}</p>
                    <p class="text-sm">CVV: {{ card.security_number }}</p>
                </div>
                <div class="flex justify-end gap-2 mt-2">
                  <a @click.prevent="editCard(card.id)" class="link link-hover text-xs">Edit</a>
                  <a @click.prevent="removeCard(card.id)" class="link link-hover text-error text-xs">Remove</a>
                </div>
              </div>
            </div>
          </div>

          <!-- Add Credit Card Form -->
          <div class="bg-base-100 rounded-lg p-4">
             <h2 class="text-xl font-bold mb-4">Quick Add Card</h2>
             <form class="space-y-3" @submit.prevent="onCardSubmit">
                  <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                    <!-- --- MODIFICATION --- This form now correctly creates a secure tokenized card -->
                    <div>
                      <label class="label py-1"><span class="label-text">Name on Card</span></label>
                      <input v-model="formCard.card_name" type="text" :class="inputClasses(v$.formCard.card_name)" />
                      <span v-if="v$.formCard.card_name.$error" class="text-red-500 text-xs mt-1">Required</span>
                    </div>
                    <div>
                      <label class="label py-1"><span class="label-text">Card Number</span></label>
                      <input v-model="formCard.card_number" type="text" :class="inputClasses(v$.formCard.card_number)" />
                      <span v-if="v$.formCard.card_number.$error" class="text-red-500 text-xs mt-1">Required</span>
                    </div>
                    <div>
                      <label class="label py-1"><span class="label-text">Card Type</span></label>
                      <select v-model="formCard.type_of_card" :class="selectClasses(v$.formCard.type_of_card)">
                        <option disabled value="">Select Type</option>
                        <option>Visa</option>
                        <option>MasterCard</option>
                        <option>Discover</option>
                        <option>American Express</option>
                      </select>
                      <span v-if="v$.formCard.type_of_card.$error" class="text-red-500 text-xs mt-1">Required</span>
                    </div>
                    <div>
                      <label class="label py-1"><span class="label-text">Expiration</span></label>
                      <div class="flex gap-2">
                        <select v-model="formCard.expiration_month" class="select select-bordered select-sm w-full"><option disabled value="">MM</option><option v-for="m in 12" :key="m">{{ String(m).padStart(2, '0') }}</option></select>
                        <select v-model="formCard.expiration_year" class="select select-bordered select-sm w-full"><option disabled value="">YYYY</option><option v-for="y in 10" :key="y">{{ new Date().getFullYear() + y - 1 }}</option></select>
                      </div>
                       <span v-if="v$.formCard.expiration_month.$error || v$.formCard.expiration_year.$error" class="text-red-500 text-xs mt-1">Required</span>
                    </div>
                     <div class="md:col-span-1">
                      <label class="label py-1"><span class="label-text">Security Number</span></label>
                      <input v-model="formCard.security_number" type="text" :class="inputClasses(v$.formCard.security_number)" />
                      <span v-if="v$.formCard.security_number.$error" class="text-red-500 text-xs mt-1">Required</span>
                    </div>
                  </div>
                  <button type="submit" class="btn btn-secondary btn-sm" :disabled="isCardSaving">
                    <span v-if="isCardSaving" class="loading loading-spinner loading-xs"></span>
                    {{ isCardSaving ? 'Saving...' : 'Save Card' }}
                  </button>
             </form>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="modal" :class="{ 'modal-open': isConfirmationModalVisible }">
    <div class="modal-box">
      <h3 class="font-bold text-lg">Confirm Payment Method</h3>
      <p class="py-4">You have selected a non-standard payment method (Cash or Check). Please confirm you wish to proceed.</p>
      <div class="modal-action">
        <button @click="proceedWithSubmission" class="btn btn-success">Confirm & Create</button>
        <button @click="isConfirmationModalVisible = false" class="btn btn-error">Cancel</button>
      </div>
    </div>
  </div>

  
</template>
<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'
import authHeader from '../../services/auth.header'
import { Customer, CreditCard, CreateCardRequest, ChargeDirectRequest } from '../../types/models'
import Header from '../../layouts/headers/headerauth.vue'
import SideBar from '../../layouts/sidebar/sidebar.vue'
import { useVuelidate } from "@vuelidate/core";
import { notify } from "@kyvg/vue3-notification"
import { minLength, required, requiredIf } from "@vuelidate/validators";
import { useFormValidation } from '../../composables/useFormValidation';
import deliveryService from '../../services/deliveryService';

const { inputClasses, selectClasses, validateForm } = useFormValidation();
import customerService from '../../services/customerService';
import paymentService from '../../services/paymentService';
import adminService from '../../services/adminService';
import queryService from '../../services/queryService';

// --- TYPE DEFINITIONS (MODIFIED) ---
interface Promo { id: number; name_of_promotion: string; money_off_delivery: number; }
interface Driver { id: number; employee_first_name: string; employee_last_name: string; }
interface PricingTier { gallons: number | string; price: number | string; }
interface DeliveryFormData {
  gallons_ordered?: string;
  customer_asked_for_fill?: boolean;
  expected_delivery_date?: string;
  dispatcher_notes_taken?: string;
  prime?: boolean;
  emergency?: boolean;
  same_day?: boolean;
  credit?: boolean;
  cash?: boolean;
  check?: boolean;
  other?: boolean;
  credit_card_id?: number;
  promo_id?: number;
  driver_employee_id?: number;
  payment_type?: number;
  // Tier fields
  pricing_tier_same_day?: number;
  pricing_tier_prime?: number;
  pricing_tier_emergency?: number;
}
// Simplified Quick Add Card form data
interface CardFormData {
    card_number: string;
    expiration_month: string;
    expiration_year: string;
    security_number: string; // Changed from cvv to match working validation
    card_name: string; // Changed from name_on_card to match working validation
    type_of_card: string;
}

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

// Reactive data
const user = ref(null as any)
const customer = ref({} as any)
const isLoading = ref(false) // For main form submission
const isCardSaving = ref(false) // For quick add card form
const quickGallonAmounts = ref([100, 125, 150, 175, 200, 220])
const userCards = ref<CreditCard[]>([])
const promos = ref([] as Promo[])
const truckDriversList = ref([] as Driver[])
const pricingTiers = ref([] as PricingTier[])
const isLoadingAuthorize = ref(true)
const authorizeCheck = ref({ profile_exists: false, has_payment_methods: false, missing_components: [] as string[], valid_for_charging: false })
const isConfirmationModalVisible = ref(false)
const formDelivery = ref({
  gallons_ordered: '',
  customer_asked_for_fill: false,
  expected_delivery_date: '',
  dispatcher_notes_taken: '',
  prime: false,
  emergency: false,
  same_day: false,
  pricing_tier_same_day: 0,
  pricing_tier_prime: 0,
  pricing_tier_emergency: 0,
  credit: false,
  cash: false,
  check: false,
  other: false,
  credit_card_id: 0,
  promo_id: 0,
  driver_employee_id: 0,
} as DeliveryFormData)

// Tier pricing from API
const tierPricing = ref({
  same_day_tier1: 0, same_day_tier2: 0, same_day_tier3: 0, same_day_tier4: 0, same_day_tier5: 0,
  prime_tier1: 0, prime_tier2: 0, prime_tier3: 0, prime_tier4: 0, prime_tier5: 0,
  emergency_tier1: 0, emergency_tier2: 0, emergency_tier3: 0, emergency_tier4: 0, emergency_tier5: 0,
})
// Simplified formCard data
const formCard = ref({
  card_number: '',
  expiration_month: '',
  expiration_year: '',
  security_number: '',
  card_name: '',
  type_of_card: '',
} as CardFormData)

// Computed
const preAuthAmount = computed((): number => {
  if (!formDelivery.value.credit || formDelivery.value.customer_asked_for_fill) return 0;
  const gallons = Number(formDelivery.value.gallons_ordered);
  if (isNaN(gallons) || gallons <= 0 || pricingTiers.value.length === 0) return 0;

  // Find the correct price tier. Assumes tiers are for total price, not price/gallon.
  let priceForGallons = 0;
  const sortedTiers = [...pricingTiers.value].sort((a, b) => Number(a.gallons) - Number(b.gallons));

  // Find the highest tier that is less than or equal to the gallons ordered
  let applicableTier = sortedTiers.filter(t => gallons >= Number(t.gallons)).pop();

  if (applicableTier) {
      const pricePerGallon = Number(applicableTier.price) / Number(applicableTier.gallons);
      priceForGallons = gallons * pricePerGallon;
  } else if (sortedTiers.length > 0) {
      // Fallback to the lowest tier's price/gallon if no tier is met (e.g., ordering 50 gallons when lowest tier is 100)
      const lowestTier = sortedTiers[0];
      const pricePerGallon = Number(lowestTier.price) / Number(lowestTier.gallons);
      priceForGallons = gallons * pricePerGallon;
  }

  return priceForGallons;
})

const customerStateName = computed((): string => {
    const states: Record<number, string> = { 0: 'Massachusetts', 1: 'Rhode Island', 2: 'New Hampshire', 3: 'Maine', 4: 'Vermont', 5: 'Connecticut', 6: 'New York' };
    return states[customer.value.customer_state] || 'Unknown state';
})

const customerHomeTypeName = computed((): string => {
    const types: Record<number, string> = { 0: 'Residential', 1: 'apartment', 2: 'condo', 3: 'commercial', 4: 'business', 5: 'construction', 6: 'container' };
    return types[customer.value.customer_home_type] || 'Unknown type';
})

const isAnyPaymentMethodSelected = computed((): boolean => {
  return !!(formDelivery.value?.credit || formDelivery.value?.cash || formDelivery.value?.check || formDelivery.value?.other);
})

const selectedGallonsAmount = computed((): number => {
  const value = formDelivery.value.gallons_ordered ?? '';
  return Number(value);
})

// Validations
const validations = {
  formDelivery: {
    gallons_ordered: {
      required: requiredIf(() => !formDelivery.value.customer_asked_for_fill),
      minValue: (value: string) => {
        if (formDelivery.value.customer_asked_for_fill) return true;
        if (!value) return true;
        const num = parseInt(value, 10);
        return num >= 1;
      }
    },
    expected_delivery_date: { required },
    driver_employee_id: { required },
    credit_card_id: {
      creditCardRequired: (value: number) => {
        if (formDelivery.value.credit) { return value !== 0; }
        return true;
      }
    },
  },
  isAnyPaymentMethodSelected: { mustBeTrue: (value: boolean) => value === true, },
  // Simplified validations for quick add card
  formCard: {
    card_name: { required, minLength: minLength(1) },
    security_number: { required, minLength: minLength(1) },
    type_of_card: { required },
    card_number: { required, minLength: minLength(1) },
    expiration_month: { required },
    expiration_year: { required },
  },
}

const v$ = useVuelidate(validations, { formDelivery, formCard, isAnyPaymentMethodSelected })

// Functions
const setGallons = (amount: number) => {
  formDelivery.value.gallons_ordered = String(amount);
  formDelivery.value.customer_asked_for_fill = false;
}

const selectCreditCard = (cardId: number) => {
  formDelivery.value.credit_card_id = cardId;
}

const setDeliveryDate = (days: number) => {
  const date = new Date();
  date.setDate(date.getDate() + days);
  formDelivery.value.expected_delivery_date = date.toISOString().split('T')[0];
}

const isDeliveryDateSelected = (days: number): boolean => {
  const date = new Date();
  date.setDate(date.getDate() + days);
  return formDelivery.value.expected_delivery_date === date.toISOString().split('T')[0];
}

const isPricingTierSelected = (tierGallons: number | string): boolean => {
  if (!formDelivery.value.gallons_ordered) return false;
  const selectedGallons = Number(formDelivery.value.gallons_ordered);
  if (isNaN(selectedGallons)) return false;
  const tierNum = Number(tierGallons);
  if (isNaN(tierNum)) return false;
  return selectedGallons === tierNum;
}

const formatCurrency = (value: number | string | undefined) => {
  if (value === undefined || value === null) return '$0.00';
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
  }).format(Number(value));
}

const getPricingTiers = async () => {
  try {
    const response = await queryService.getOilPriceTiers();
    const data = (response.data as any).pricing_tiers || (response.data as any).tiers || (response.data as any).prices || response.data;
    if (data && typeof data === 'object' && !Array.isArray(data)) {
        pricingTiers.value = Object.entries(data)
          .filter(([key]) => !isNaN(parseInt(key, 10)))
          .map(([gallons, price]) => ({ gallons: parseInt(gallons, 10), price: String(price) }));
    }
  } catch (error) {
      notify({ title: "Pricing Error", text: "Could not retrieve today's pricing.", type: "error" });
  }
}

const getCustomer = async (user_id: string | number | string[]) => {
  try {
    const response = await customerService.getById(Number(user_id));
    customer.value = response.data?.customer || response.data;
  } catch (error) {
    notify({ title: "Error", text: "Could not find customer", type: "error" });
  }
}

const getPaymentCards = async (user_id: string | number | string[]) => {
  try {
      const response = await paymentService.getCards(Number(user_id));
      userCards.value = response.data?.cards || [];
  } catch (error) {
      userCards.value = [];
  }
}

const getPromos = async () => {
    try {
        const response = await adminService.promos.getAll();
        const data = response.data;
        promos.value = Array.isArray(data) ? data : ((data as any)?.promos || []);
    } catch (error) {
        promos.value = [];
    }
}

const getDriversList = async () => {
    try {
        const response = await adminService.employees.getDrivers();
        const data = response.data;
        truckDriversList.value = Array.isArray(data) ? data : ((data as any)?.drivers || []);
    } catch (error) {
         /* empty */
    }
}

const editCard = (card_id: number) => {
  router.push({ name: "cardedit", params: { id: card_id } });
}

const removeCard = async (card_id: number) => {
  if (window.confirm("Are you sure you want to remove this card?")) {
      try {
          await paymentService.removeCard(card_id);
          notify({ title: "Card Removed", type: "success" });
          getPaymentCards(customer.value.id);
      } catch (error) {
           notify({ title: "Error", text: "Could not remove card.", type: "error" });
      }
  }
}

const onDeliverySubmit = async () => {
  const isFormValid = await v$.value.formDelivery.$validate();
  if (!isFormValid) {
    notify({ title: "Form Incomplete", text: "Please review the fields marked in red.", type: "warn" });
    return;
  }
  if (formDelivery.value.cash || formDelivery.value.check) {
    isConfirmationModalVisible.value = true;
  } else {
    proceedWithSubmission();
  }
}

const proceedWithSubmission = async () => {
  isConfirmationModalVisible.value = false;
  isLoading.value = true;

  // Derive payment type
  let paymentType = 0;
  if(formDelivery.value.credit) paymentType = 1;
  else if(formDelivery.value.cash) paymentType = 0;
  else if(formDelivery.value.check) paymentType = 3;
  else if(formDelivery.value.other) paymentType = 4;
  
  // Update boolean flags based on tier selection for backward compatibility and logic
  formDelivery.value.same_day = (formDelivery.value.pricing_tier_same_day || 0) > 0;
  formDelivery.value.prime = (formDelivery.value.pricing_tier_prime || 0) > 0;
  formDelivery.value.emergency = (formDelivery.value.pricing_tier_emergency || 0) > 0;

  const payload = {
    ...formDelivery.value,
    payment_type: paymentType,
    customer_id: customer.value.id
  };

  try {
    const response = await deliveryService.create(customer.value.id, payload as any);
    const deliveryData = response.data;
    const deliveryId = (deliveryData as any).delivery_id || (deliveryData.delivery && deliveryData.delivery.id);

    if (!deliveryData.ok || !deliveryId) {
      throw new Error(deliveryData.error || "Failed to create delivery record.");
    }

    // Delivery created successfully - redirect to payment page
    notify({
      title: "Success!",
      text: `Delivery #${deliveryId} created. ${
        formDelivery.value.credit
          ? "Redirecting to payment page."
          : ""
      }`,
      type: "success"
    });
    router.push({ name: "payOil", params: { id: deliveryId } });

  } catch (error: any) {
    const errorMessage = error.response?.data?.detail || "An error occurred during submission.";
    notify({ title: "Submission Error", text: errorMessage, type: "error" });
  } finally {
    isLoading.value = false;
  }
}

const checkAuthorizeAccount = async () => {
  if (!customer.value.id) return;

  isLoadingAuthorize.value = true;

  try {
    const path = `${import.meta.env.VITE_AUTHORIZE_URL}/user/check-authorize-account/${customer.value.id}`;
    const response = await axios.get(path, { headers: authHeader() });
    authorizeCheck.value = response.data?.authorize_check || 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
    authorizeCheck.value = {
      profile_exists: false,
      has_payment_methods: false,
      missing_components: ['api_error'],
      valid_for_charging: false
    };
  } finally {
    isLoadingAuthorize.value = false;
  }
}

const onCardSubmit = async () => {
  v$.value.formCard.$validate();
  if (v$.value.formCard.$error) {
     notify({ title: "Validation Error", text: "Please fill out all required fields.", type: "error" });
     return;
  }
  isCardSaving.value = true;

  // --- STEP 1: PREPARE PAYLOADS FOR BOTH SERVICES ---
  // Payload for Flask backend
  const flaskPayload = {
    card_number: formCard.value.card_number,
    expiration_month: formCard.value.expiration_month,
    expiration_year: formCard.value.expiration_year,
    type_of_card: formCard.value.type_of_card,
    security_number: formCard.value.security_number,
    main_card: false,
    name_on_card: formCard.value.card_name,
  };

  // --- STEP 2: CRITICAL CALL - SAVE CARD TO LOCAL DATABASE ---
  try {
    const flaskResponse = await paymentService.createCard(customer.value.id, flaskPayload as CreateCardRequest);

    if (!flaskResponse.data.ok) {
      throw new Error((flaskResponse.data as any).error || "Failed to save card.");
    }
    console.log("Card successfully saved to local database via Service.");

  } catch (error: any) {
    const errorMessage = error.response?.data?.error || "A critical error occurred while saving the card.";
    notify({ title: "Error", text: errorMessage, type: "error" });
    isCardSaving.value = false; // Stop loading spinner
    return; // End the function here
  }

  // --- STEP 3: BEST-EFFORT CALL - TOKENIZE CARD VIA FASTAPI ---
 if (authorizeCheck.value.profile_exists) {
        // Payload for FastAPI backend
  const fastapiPayload = {
    card_number: formCard.value.card_number.replace(/\s/g, ''),
    expiration_date: `${formCard.value.expiration_year}-${formCard.value.expiration_month}`,
    cvv: formCard.value.security_number,
    main_card: false,
  };

  try {
    await paymentService.authorize.tokenizeCard(customer.value.id, fastapiPayload as any);
    console.log("Card successfully tokenized with Authorize.Net via Service.");
  } 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: Tokenization with Authorize.Net failed, but the card was saved locally.", error.response?.data || error.message);
  }
}else{
   console.log("Skipping Authorize.Net tokenization as no profile exists for customer.");
}
  // --- STEP 4: ALWAYS SHOW SUCCESS, REFRESH CARDS, STAY ON PAGE ---
  notify({ type: 'success', title: 'Card Saved!' });

  // Refresh the card list and try to auto-select if possible
  await getPaymentCards(customer.value.id);
  if (userCards.value.length > 0) {
    formDelivery.value.credit = true;
    formDelivery.value.credit_card_id = userCards.value[userCards.value.length - 1].id;
  }

  // Reset the quick add form
  Object.assign(formCard.value, { card_number: '', expiration_month: '', expiration_year: '', security_number: '', card_name: '', type_of_card: '' });
  v$.value.formCard.$reset();
  isCardSaving.value = false;
}

// Watchers
watch(route, () => {
  const customerId = route.params.id;
  getCustomer(customerId);
  getPaymentCards(customerId);
})

// Lifecycle
onMounted(() => {
  getDriversList()
  getPromos()
  getPricingTiers()
  
  // Fetch full pricing table to populate tier dropdowns
  queryService.getOilPriceTable().then((response: any) => {
    const data = response.data.pricing;
    if (data) {
      tierPricing.value = {
        same_day_tier1: data.price_same_day_tier1 || data.price_same_day,
        same_day_tier2: data.price_same_day_tier2,
        same_day_tier3: data.price_same_day_tier3,
        same_day_tier4: data.price_same_day_tier4,
        same_day_tier5: data.price_same_day_tier5,
        
        prime_tier1: data.price_prime_tier1 || data.price_prime,
        prime_tier2: data.price_prime_tier2,
        prime_tier3: data.price_prime_tier3,
        prime_tier4: data.price_prime_tier4,
        prime_tier5: data.price_prime_tier5,
        
        emergency_tier1: data.price_emergency_tier1 || data.price_emergency,
        emergency_tier2: data.price_emergency_tier2,
        emergency_tier3: data.price_emergency_tier3,
        emergency_tier4: data.price_emergency_tier4,
        emergency_tier5: data.price_emergency_tier5,
      };
    }
  });

  const customerId = route.params.id;
  getCustomer(customerId)
  getPaymentCards(customerId);
})
</script>
