<script setup>
import { useAuthStore } from "@/stores/authStore";
import { useSettingStore } from "@/stores/settingStore";
import { countries } from "@/utils/countryCodes";
import { storeToRefs } from "pinia";
import { useToast } from "primevue/usetoast";
import { computed, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";

const tab = ref("stripe"); // default active tab
const route = useRoute();
const router = useRouter();

const settingStore = useSettingStore();
const authStore = useAuthStore();
const { setting } = storeToRefs(settingStore);
const { user: authUser } = storeToRefs(authStore);
const toast = useToast();

// Reactive data
const paymentForm = ref();
const isSubmitting = ref(false);
const isConnecting = ref(false);
const isUpdatingAccount = ref(false);
const isRegisteringWallet = ref(false);
const stripeRawData = ref(null);
const walletDomain = ref(null);

// Form fields
const paymentMethodName = ref("stripe");
const country = ref("");
const email = ref("");
const stripeAccountId = ref("");
const setupUrl = ref("");
const status = ref("active");
/** Email/country tied to the currently linked Stripe account */
const linkedEmail = ref("");
const linkedCountry = ref("");
const isReplacingAccount = ref(false);

// Status options
const statusOptions = [
  { title: "Active", value: "active" },
  { title: "Inactive", value: "inactive" },
];

// Check if user is super admin
const isSuperAdmin = computed(() => {
  return authUser.value?.data?.role === "super_admin";
});

// Load existing payment settings from store
const loadPaymentSettings = (settingsData) => {
  if (settingsData?.payment_gateway_configuration?.stripe) {
    const paymentData = settingsData.payment_gateway_configuration.stripe;
    stripeRawData.value = { ...paymentData };
    const stripeResponse = paymentData.response || {};

    // Basic fields
    paymentMethodName.value = "stripe";
    // Convert country to lowercase to match iso field in countries array
    country.value = (
      paymentData.country ||
      stripeResponse.country ||
      ""
    ).toLowerCase();
    email.value = paymentData.email || stripeResponse.email || "";
    stripeAccountId.value = paymentData.stripe_account_id || "";
    setupUrl.value = paymentData.setup_url || "";
    status.value = paymentData.status || "active";
    linkedEmail.value = email.value;
    linkedCountry.value = country.value;
    isReplacingAccount.value = false;
    walletDomain.value = paymentData.wallet_domain
      ? { ...paymentData.wallet_domain }
      : null;
  }
};

const franchiseDomain = computed(
  () => authUser.value?.data?.franchisee?.franchise_domain || "",
);

const walletDomainAlertType = computed(() => {
  const w = walletDomain.value;
  if (!w) {
    return "info";
  }
  if (w.skipped) {
    return "warning";
  }
  if (w.last_error) {
    return "error";
  }
  if (w.apple_pay_status === "active" && w.google_pay_status === "active") {
    return "success";
  }
  return "info";
});

const walletDomainSummary = computed(() => {
  const w = walletDomain.value;
  if (!w) {
    if (!franchiseDomain.value) {
      return "Set your franchise domain in franchise settings, then register it for Apple Pay and Google Pay after Stripe onboarding.";
    }
    return `Customer site domain: ${franchiseDomain.value}. Register it after Stripe onboarding to enable wallet payments on your registration form.`;
  }
  if (w.skipped) {
    return w.skip_reason || "Wallet domain registration was skipped.";
  }
  if (w.last_error) {
    return w.last_error;
  }
  const apple = w.apple_pay_status || "unknown";
  const google = w.google_pay_status || "unknown";
  return `Domain ${w.domain_name || franchiseDomain.value} — Apple Pay: ${apple}, Google Pay: ${google}.`;
});

const normalizeEmail = (value) => (value || "").trim().toLowerCase();

const hasConnectDetailsChanged = computed(() => {
  if (!stripeAccountId.value) {
    return false;
  }

  return (
    normalizeEmail(email.value) !== normalizeEmail(linkedEmail.value) ||
    (country.value || "").trim().toLowerCase() !==
      (linkedCountry.value || "").trim().toLowerCase()
  );
});

/** Allow connect when not linked yet, when replacing, or when email/country changed (reuse or new account on server). */
const canConnectStripe = computed(() => {
  if (!email.value || !country.value) {
    return false;
  }

  if (!stripeAccountId.value) {
    return true;
  }

  return hasConnectDetailsChanged.value || isReplacingAccount.value;
});

const connectButtonLabel = computed(() => {
  if (!stripeAccountId.value) {
    return "Connect Stripe Account";
  }

  if (isReplacingAccount.value) {
    return "Connect new Stripe account";
  }

  if (hasConnectDetailsChanged.value) {
    return "Reconnect Stripe account";
  }

  if (canConnectStripe.value) {
    return "Connect Stripe account";
  }

  return "Connected";
});

const startChangeStripeAccount = () => {
  isReplacingAccount.value = true;
  toast.add({
    severity: "info",
    summary: "Change Stripe account",
    detail:
      "This creates a brand-new Stripe connected account. To reconnect the same email and country, cancel and use Regenerate Account Link or Reconnect instead.",
    life: 5000,
  });
};

const cancelChangeStripeAccount = () => {
  isReplacingAccount.value = false;
  email.value = linkedEmail.value;
  country.value = linkedCountry.value;
};

const isReturningFromStripe = () =>
  route.query.stripe_onboarding === "1" ||
  route.query.stripe_onboarding === "true";

// Watch for settings changes and prefill form
watch(
  () => setting.value?.payment_gateway_configuration?.stripe,
  () => {
    if (setting.value) {
      loadPaymentSettings(setting.value);
    }
  },
  { immediate: true, deep: true },
);

onMounted(() => {
  if (!isReturningFromStripe()) {
    return;
  }

  const stripe = settingStore.setting?.payment_gateway_configuration?.stripe;
  if (stripe?.stripe_account_id) {
    const wallet = stripe.wallet_domain;
    let detail =
      "Stripe account connected. Your account details are shown below.";
    if (wallet && !wallet.skipped && !wallet.last_error) {
      detail += ` Wallet domain registered for ${wallet.domain_name || franchiseDomain.value}.`;
    } else if (wallet?.skip_reason) {
      detail += ` ${wallet.skip_reason}`;
    }
    toast.add({
      severity: wallet?.last_error ? "warn" : "success",
      summary: "Stripe onboarding",
      detail,
      life: 8000,
    });
  }

  const nextQuery = { ...route.query };
  delete nextQuery.stripe_onboarding;
  router.replace({ path: route.path, query: nextQuery });
});

const registerWalletDomain = async () => {
  if (!stripeAccountId.value) {
    toast.add({
      severity: "warning",
      summary: "Stripe required",
      detail: "Connect Stripe before registering a wallet domain.",
      life: 4000,
    });
    return;
  }

  isRegisteringWallet.value = true;
  try {
    const response = await settingStore.registerWalletDomain();
    const stripe = response?.data?.stripe;
    if (stripe?.wallet_domain) {
      walletDomain.value = { ...stripe.wallet_domain };
      if (stripeRawData.value) {
        stripeRawData.value = { ...stripeRawData.value, wallet_domain: walletDomain.value };
      }
    }
    toast.add({
      severity: response?.status === false ? "error" : "success",
      summary: "Wallet domain",
      detail: response?.message || "Wallet domain registration completed.",
      life: 6000,
    });
  } catch (error) {
    const errorMessage =
      error.response?.data?.message ||
      error.message ||
      "Failed to register wallet domain";
    toast.add({
      severity: "error",
      summary: "Error",
      detail: errorMessage,
      life: 5000,
    });
  } finally {
    isRegisteringWallet.value = false;
  }
};

// Save payment settings
const savePaymentSettings = async () => {
  if (!paymentForm.value?.validate()) {
    return;
  }

  isSubmitting.value = true;
  try {
    const payload = {
      payment_gateway_configuration: {
        stripe: {
          ...(stripeRawData.value || {}),
          country: country.value,
          email: email.value,
          stripe_account_id: stripeAccountId.value,
          setup_url: setupUrl.value,
          status: status.value,
        },
      },
    };

    const response = await settingStore.saveSettings(payload);

    if (response.status === true) {
      toast.add({
        severity: "success",
        summary: "Success",
        detail: "Payment settings saved successfully",
        life: 3000,
      });
    } else {
      toast.add({
        severity: "error",
        summary: "Error",
        detail: response.message || "Failed to save payment settings",
        life: 3000,
      });
    }
  } catch (error) {
    console.error("Error saving payment settings:", error);
    const errorMessage = error.response?.data?.message || error.message || "Failed to save payment settings";
    toast.add({
      severity: "error",
      summary: "Error",
      detail: errorMessage,
      life: 3000,
    });
  } finally {
    isSubmitting.value = false;
  }
};

// Reset form
const resetForm = () => {
  loadPaymentSettings(setting.value);
};

// Connect Stripe Account
const connectStripeAccount = async () => {
  if (!email.value || !country.value) {
    toast.add({
      severity: "warning",
      summary: "Validation Error",
      detail: "Please fill in email and country before connecting",
      life: 3000,
    });
    return;
  }

  isConnecting.value = true;
  try {
    const payload = {
      payment_method_name: "stripe",
      country: country.value,
      email: email.value,
      status: "active",
      franchisee_id: authUser.value?.data?.franchisee_id || "",
      replace_existing: isReplacingAccount.value,
      // Only skip reuse when user explicitly chose "Change Stripe account".
      force_new_account: isReplacingAccount.value,
    };

    const response = await settingStore.connectStripeAccount(payload);
    
    if (response.status === true) {
      // API returns data: { stripe: { stripe_account_id, setup_url, status, ... } }
      const stripeData = response.data?.stripe || {};
      
      // Update full raw data to preserve response and other fields
      stripeRawData.value = { ...stripeData };

      if (stripeData.stripe_account_id) {
        stripeAccountId.value = stripeData.stripe_account_id;
      }
      if (stripeData.setup_url) {
        setupUrl.value = stripeData.setup_url;
      }
      if (stripeData.status) {
        status.value = stripeData.status;
      }

      linkedEmail.value = email.value;
      linkedCountry.value = country.value;
      isReplacingAccount.value = false;

      if (settingStore.setting?.payment_gateway_configuration) {
        settingStore.setting = {
          ...settingStore.setting,
          payment_gateway_configuration: {
            ...settingStore.setting.payment_gateway_configuration,
            stripe: {
              ...(settingStore.setting.payment_gateway_configuration.stripe || {}),
              ...stripeData,
            },
          },
        };
      }

      toast.add({
        severity: "success",
        summary: "Success",
        detail: response.message || "Stripe account connected successfully",
        life: 5000,
      });
    } else {
      toast.add({
        severity: "error",
        summary: "Error",
        detail: response.message || "Failed to connect Stripe account",
        life: 3000,
      });
    }
  } catch (error) {
    console.error("Error connecting Stripe account:", error);
    const errorMessage = error.response?.data?.message || error.message || "Failed to connect Stripe account";
    toast.add({
      severity: "error",
      summary: "Error",
      detail: errorMessage,
      life: 3000,
    });
  } finally {
    isConnecting.value = false;
  }
};

// Regenerate Account Link
const regenerateAccountLink = async () => {
  if (!stripeAccountId.value) {
    toast.add({
      severity: "warning",
      summary: "Validation Error",
      detail: "No Stripe account connected",
      life: 3000,
    });
    return;
  }

  isUpdatingAccount.value = true;
  try {
    const payload = {
      account_id: stripeAccountId.value,
    };

    const response = await settingStore.regenerateAccountLink(payload);

    if (response.status === true) {
      if (response.data?.url) {
        setupUrl.value = response.data.url;
      }
      
      // Update stripeRawData if full object is returned
      if (response.data?.stripe) {
        stripeRawData.value = { ...response.data.stripe };
      }

      // Also ensure status is synced if returned (nested or flat)
      const stripeStatus = response.data?.status || response.data?.stripe?.status;
      if (stripeStatus) {
        status.value = stripeStatus;
      }

      toast.add({
        severity: "success",
        summary: "Success",
        detail:
          response.message ||
          "Account setup link regenerated successfully. Link expires in 5 minutes.",
        life: 5000,
      });
    } else {
      toast.add({
        severity: "error",
        summary: "Error",
        detail: response.message || "Failed to regenerate account link",
        life: 3000,
      });
    }
  } catch (error) {
    console.error("Error regenerating account link:", error);
    const errorMessage = error.response?.data?.message || error.message || "Failed to regenerate account link";
    toast.add({
      severity: "error",
      summary: "Error",
      detail: errorMessage,
      life: 3000,
    });
  } finally {
    isUpdatingAccount.value = false;
  }
};

// Copy to clipboard function
const copyToClipboard = async (text) => {
  try {
    await navigator.clipboard.writeText(text);
    toast.add({
      severity: "success",
      summary: "Copied",
      detail: "URL copied to clipboard",
      life: 2000,
    });
  } catch (err) {
    console.error("Failed to copy:", err);
    toast.add({
      severity: "error",
      summary: "Error",
      detail: "Failed to copy URL",
      life: 2000,
    });
  }
};

// Computed property for loading state
const isAnyOperationLoading = computed(() => {
  return (
    isSubmitting.value ||
    isConnecting.value ||
    isUpdatingAccount.value ||
    isRegisteringWallet.value ||
    settingStore.loading
  );
});
</script>

<template>
  <VCard class="mb-6">
    <VCardItem class="pb-6">
      <VCardTitle class="d-flex align-center">
        <VIcon icon="bx-credit-card" class="me-3" size="24" />
        Payment Integration
      </VCardTitle>
      <VCardSubtitle>
        Configure your payment gateway settings for Stripe integration
      </VCardSubtitle>
    </VCardItem>

    <!-----------------Payment-tabs start-------------------------->
    <VCard class="tabs-container" elevation="2">
      <!-- NATIVE TABS -->
      <VTabs v-model="tab" bg-color="transparent" color="primary">
        <VTab value="stripe">Stripe</VTab>
        <VTab value="paypal">PayPal</VTab>
        <VTab value="viva">VIVA</VTab>
      </VTabs>

      <VDivider />

      <!-- TAB CONTENT -->
      <VWindow v-model="tab" class="pa-4">
        <!-- STRIPE TAB -->
        <VWindowItem value="stripe" class="tab-content">
          <VForm ref="paymentForm">
            <!-- Account Information -->
            <div class="mb-1">
              <h6 class="text-h6 mb-4">Account Information</h6>
              <VRow>
                <VCol cols="12" md="6">
                  <VTextField
                    v-model="email"
                    label="Stripe Account Email"
                    placeholder="deepak19k96@gmail.com"
                    variant="outlined"
                    density="comfortable"
                    type="email"
                    required
                  />
                </VCol>
                <VCol cols="12" md="6">
                  <v-autocomplete
                    v-model="country"
                    :items="countries"
                    item-title="name"
                    item-value="iso"
                    label="Country"
                    placeholder="Select Country"
                    variant="outlined"
                    density="comfortable"
                    clearable
                    required
                  >
                    <!-- Dropdown items -->
                    <template #item="{ props, item }">
                      <v-list-item v-bind="props">
                        <template #prepend>
                          <span
                            v-if="item.raw && item.raw.iso"
                            :class="`fi fi-${item.raw.iso}`"
                            style="font-size: 20px"
                          ></span>
                        </template>
                      </v-list-item>
                    </template>

                    <!-- Selected value -->
                    <template #selection="{ item }">
                      <span
                        v-if="item.raw && item.raw.iso"
                        :class="`fi fi-${item.raw.iso}`"
                        style="font-size: 20px"
                      ></span>
                      <span class="ml-2">{{
                        item.raw ? item.raw.name : country
                      }}</span>
                    </template>
                  </v-autocomplete>
                </VCol>
              </VRow>

              <VAlert
                v-if="stripeAccountId && hasConnectDetailsChanged && !isReplacingAccount"
                type="info"
                variant="tonal"
                density="compact"
                class="mt-2 mb-2"
              >
                Email or country changed. Click “Reconnect Stripe account” to link an
                account with the updated details (existing account is reused when email and country match).
              </VAlert>

              <VRow class="mt-4">
                <VCol>
                  <VBtn
                    color="primary"
                    @click="connectStripeAccount"
                    :loading="isConnecting"
                    :disabled="isConnecting || !canConnectStripe"
                  >
                    <VIcon
                      :icon="
                        stripeAccountId && !canConnectStripe
                          ? 'bx-check-circle'
                          : 'bx-link'
                      "
                      class="me-2"
                    />
                    {{ connectButtonLabel }}
                  </VBtn>
                  <VBtn
                    v-if="stripeAccountId && !canConnectStripe"
                    color="secondary"
                    variant="tonal"
                    @click="startChangeStripeAccount"
                    :disabled="isConnecting"
                    class="ms-3"
                  >
                    <VIcon icon="bx-transfer" class="me-2" />
                    Change Stripe account
                  </VBtn>
                  <VBtn
                    v-if="isReplacingAccount"
                    color="secondary"
                    variant="text"
                    @click="cancelChangeStripeAccount"
                    :disabled="isConnecting"
                    class="ms-1"
                  >
                    Cancel
                  </VBtn>
                  <VBtn
                    v-if="stripeAccountId"
                    color="primary"
                    @click="regenerateAccountLink"
                    :loading="isUpdatingAccount"
                    :disabled="isUpdatingAccount || isReplacingAccount"
                    class="ms-3"
                  >
                    <VIcon icon="bx-refresh" class="me-2" />
                    Regenerate Account Link
                  </VBtn>
                </VCol>
              </VRow>

              <!-- Account ID and Setup URL in single row -->
              <VRow class="mt-4">
                <VCol cols="12" md="6">
                  <div class="flex items-center gap-1 tool-tip">
                   <label class="field-label">Stripe Account ID</label>

                   <VTooltip location="top" max-width="250">
                     <template #activator="{ props }">
                       <VIcon
                         v-bind="props"
                         icon="bx-info-circle"
                         size="16"
                         class="cursor-pointer text-medium-emphasis"
                       />
                     </template>

                     <span>
                       This unique ID is generated after connecting your Stripe account.
                     </span>
                   </VTooltip>
                 </div>



                  <VTextField
                    :model-value="
                      stripeAccountId
                        ? `acc${'*'.repeat(Math.max(0, stripeAccountId.length - 6))}${stripeAccountId.slice(-6)}`
                        : ''
                    "
                    placeholder="Stripe Account ID"
                    variant="outlined"
                    density="comfortable"
                    readonly
                    persistent-placeholder
                    hide-details
                  >
              </VTextField>

                </VCol>
                <VCol cols="12" md="6">
                  <div class="flex items-center gap-1 tool-tip">
                   <label class="field-label">Setup URL</label>
                   <VTooltip location="top" max-width="250">
                     <template #activator="{ props }">
                       <VIcon
                         v-bind="props"
                         icon="bx-info-circle"
                         size="16"
                         class="cursor-pointer text-medium-emphasis"
                       />
                     </template>

                     <span>
                       After connecting, use this link to verify your details and start receiving payments.
                     </span>
                   </VTooltip>
                 </div>

                  <div v-if="setupUrl" class="setup-url-wrapper">
                    <a
                      :href="setupUrl"
                      target="_blank"
                      rel="noopener noreferrer"
                      class="preview-link"
                      :title="setupUrl"
                      :class="{ 'disabled-link': isAnyOperationLoading }"
                    >
                      <span class="url-text">{{ setupUrl }}</span>
                      <i class="bx bx-link-external external-icon"></i>
                    </a>
                    <VBtn
                      icon
                      size="small"
                      variant="text"
                      class="copy-btn"
                      :disabled="isAnyOperationLoading"
                      @click="copyToClipboard(setupUrl)"
                    >
                      <i class="bx bx-copy"></i>
                    </VBtn>
                  </div>
                  <div v-if="setupUrl" class="text-caption text-primary mt-1">
                    <VIcon icon="bx-time-five" size="14" class="me-1" />
This link will expire 5 minutes after it is generated. Please regenerate the account link if it expires before completion.                  </div>
                  <div v-else class="no-url-placeholder">
                    <span class="text-muted">
                      Setup URL will appear after connecting
                    </span>
                  </div>
                  
                </VCol>
              </VRow>

              <!-- Apple Pay / Google Pay domain -->
              <div v-if="stripeAccountId" class="mt-6">
                <h6 class="text-h6 mb-3">Apple Pay &amp; Google Pay</h6>
                <VAlert
                  :type="walletDomainAlertType"
                  variant="tonal"
                  density="comfortable"
                  class="mb-4"
                >
                  {{ walletDomainSummary }}
                </VAlert>
                <VBtn
                  color="primary"
                  variant="tonal"
                  :loading="isRegisteringWallet"
                  :disabled="isAnyOperationLoading || !franchiseDomain"
                  @click="registerWalletDomain"
                >
                  <VIcon icon="bx-globe" class="me-2" />
                  Register wallet domain
                </VBtn>
                <p
                  v-if="!franchiseDomain"
                  class="text-caption text-medium-emphasis mt-2 mb-0"
                >
                  Franchise domain is missing. Add it under franchise settings first.
                </p>
              </div>
            </div>

            <!-- Status -->
            <v-col cols="12" class="stripe-toggle">
                <v-switch 
                  v-model="status"
                  label="Enable Stripe Payments" 
                  color="primary" 
                  true-value="active"
                  false-value="inactive"
                  hide-details
                  @change="savePaymentSettings"
                />
            </v-col>
           
           <VDivider class="mb-6" />

            <!-- Save Actions -->
            <VRow class="mt-4">
              <VCol>
                <VBtn
                  color="primary"
                  class="me-3"
                  @click="savePaymentSettings"
                  :loading="isSubmitting || settingStore.loading"
                  :disabled="isSubmitting || settingStore.loading"
                >
                  <VIcon icon="bx-save" class="me-2" />
                  Save Payment Settings
                </VBtn>
                <VBtn
                  color="secondary"
                  variant="tonal"
                  @click="resetForm"
                  :disabled="isSubmitting || settingStore.loading"
                >
                  <VIcon icon="bx-refresh" class="me-2" />
                  Reset
                </VBtn>
              </VCol>
            </VRow>
          </VForm>
        </VWindowItem>

        <!-- PAYPAL TAB -->
        <VWindowItem value="paypal" class="tab-content">
          <VCard class="pa-6" elevation="1">
            <h3 class="text-h6 mb-4">PayPal Integration Settings</h3>
            <v-row>
              <!-- PayPal Email -->
              <v-col cols="12" md="6">
                <v-text-field
                  label="PayPal Account Email"
                  variant="outlined"
                  density="comfortable"
                />
              </v-col>

              <!-- Environment -->
              <v-col cols="12" md="6">
                <v-select
                  label="Environment"
                  :items="['Sandbox', 'Live']"
                  variant="outlined"
                  density="comfortable"
                />
              </v-col>

              <!-- Client ID -->
              <v-col cols="12" md="6">
                <v-text-field
                  label="Client ID"
                  variant="outlined"
                  density="comfortable"
                />
              </v-col>

              <!-- Secret Key-->
              <v-col cols="12" md="6">
                <v-text-field
                  label="Secret Key"
                  variant="outlined"
                  type="password"
                  density="comfortable"
                />
              </v-col>

              <!-- Webhook URL -->
              <v-col cols="12">
                <v-text-field
                  label="Webhook URL"
                  variant="outlined"
                  density="comfortable"
                />
              </v-col>

              <!-- Enable Toggle -->
              <v-col cols="12">
                <v-switch label="Enable PayPal Payments" color="primary" />
              </v-col>
            </v-row>

            <v-divider class="my-4"></v-divider>

            <!-- Save Actions -->
            <VRow class="mt-6">
              <VCol>
                <VBtn
                  color="primary"
                  class="me-3"
                  @click="savePaymentSettings"
                  :loading="isSubmitting || settingStore.loading"
                  :disabled="isSubmitting || settingStore.loading"
                >
                  <VIcon icon="bx-save" class="me-2" />
                  Save Payment Settings
                </VBtn>
                <VBtn
                  color="secondary"
                  variant="tonal"
                  @click="resetForm"
                  :disabled="isSubmitting || settingStore.loading"
                >
                  <VIcon icon="bx-refresh" class="me-2" />
                  Reset
                </VBtn>
              </VCol>
            </VRow>
          </VCard>
        </VWindowItem>

        <!-- VIVA TAB -->
        <VWindowItem value="viva" class="tab-content">
          <VCard class="pa-6" elevation="1">
            <h3 class="text-h6 mb-4">Visa Payment Settings</h3>
            <v-row>
              <!-- Merchant Name -->
              <v-col cols="12" md="6">
                <v-text-field
                  label="Merchant Name"
                  variant="outlined"
                  density="comfortable"
                />
              </v-col>

              <!-- Card No -->
              <v-col cols="12" md="6">
                <v-text-field
                  label="Card Number"
                  variant="outlined"
                  density="comfortable"
                />
              </v-col>

              <!-- Holder NameL -->
              <v-col cols="12" md="6">
                <v-text-field
                  label="Card Holder Name"
                  variant="outlined"
                  density="comfortable"
                />
              </v-col>

              <!-- Expiration Date -->
              <v-col cols="12" md="6">
                <v-text-field
                  label="Expiration Date"
                  placeholder="MM / YY"
                  variant="outlined"
                  density="comfortable"
                />
              </v-col>

              <!-- cvv no-->
              <v-col cols="12" md="6">
                <v-select
                  label="CVV"
                  variant="outlined"
                  density="comfortable"
                />
              </v-col>

              <!-- Card Pin  -->
              <v-col cols="12" md="6">
                <v-text-field
                  label="Card Pin "
                  type="password"
                  variant="outlined"
                  density="comfortable"
                />
              </v-col>

              <!-- Enable Toggle -->
              <v-col cols="12">
                <v-switch label="Enable Visa Payments" color="primary" />
              </v-col>
            </v-row>

            <v-divider class="my-4"></v-divider>

            <!-- Save Actions -->
            <VRow class="mt-6">
              <VCol>
                <VBtn
                  color="primary"
                  class="me-3"
                  @click="savePaymentSettings"
                  :loading="isSubmitting || settingStore.loading"
                  :disabled="isSubmitting || settingStore.loading"
                >
                  <VIcon icon="bx-save" class="me-2" />
                  Save Payment Settings
                </VBtn>
                <VBtn
                  color="secondary"
                  variant="tonal"
                  @click="resetForm"
                  :disabled="isSubmitting || settingStore.loading"
                >
                  <VIcon icon="bx-refresh" class="me-2" />
                  Reset
                </VBtn>
              </VCol>
            </VRow>
          </VCard>
        </VWindowItem>
      </VWindow>
    </VCard>

    <!-----------------Payment-tabs-ends--------------------------->

    <!--
    <VCardText>
      <VForm ref="paymentForm">
        <!-- Payment Method (Read-only) --
        <div class="mb-8">
          <h6 class="text-h6 mb-4">Payment Gateway</h6>
          <VRow>
            <VCol cols="12" md="6">
              <VTextField
                v-model="paymentMethodName"
                label="Payment Method"
                placeholder="stripe"
                variant="outlined"
                density="comfortable"
                readonly
                disabled
                prepend-icon="bx-lock"
                hint="Stripe is the default payment method"
              />
            </VCol>
          </VRow>
        </div>

        <VDivider class="mb-6" />

        <!-- Account Information --
        <div class="mb-8">
          <h6 class="text-h6 mb-4">Account Information</h6>
          <VRow>
            <VCol cols="12" md="6">
              <VTextField
                v-model="email"
                label="Stripe Account Email"
                placeholder="deepak19k96@gmail.com"
                variant="outlined"
                density="comfortable"
                type="email"
                required
              />
            </VCol>
            <VCol cols="12" md="6">
              <v-autocomplete
                v-model="country"
                :items="countries"
                item-title="name"
                item-value="iso"
                label="Country"
                placeholder="Select Country"
                variant="outlined"
                density="comfortable"
                clearable
                required
              >
                <!-- Dropdown items --
                <template #item="{ props, item }">
                  <v-list-item v-bind="props">
                    <template #prepend>
                      <span
                        v-if="item.raw && item.raw.iso"
                        :class="`fi fi-${item.raw.iso}`"
                        style="font-size: 20px"
                      ></span>
                    </template>
                  </v-list-item>
                </template>

                <!-- Selected value --
                <template #selection="{ item }">
                  <span
                    v-if="item.raw && item.raw.iso"
                    :class="`fi fi-${item.raw.iso}`"
                    style="font-size: 20px"
                  ></span>
                  <span class="ml-2">{{
                    item.raw ? item.raw.name : country
                  }}</span>
                </template>
              </v-autocomplete>
            </VCol>
          </VRow>

          <VRow class="mt-4">
            <VCol>
              <VBtn
                color="primary"
                @click="connectStripeAccount"
                :loading="isConnecting"
                :disabled="
                  isConnecting || !email || !country || !!stripeAccountId
                "
              >
                <VIcon
                  :icon="stripeAccountId ? 'bx-check-circle' : 'bx-link'"
                  class="me-2"
                />
                {{ stripeAccountId ? "Connected" : "Connect Stripe Account" }}
              </VBtn>
              <VBtn
                v-if="stripeAccountId"
                color="primary"
                @click="regenerateAccountLink"
                :loading="isUpdatingAccount"
                :disabled="isUpdatingAccount"
                class="ms-3"
              >
                <VIcon icon="bx-refresh" class="me-2" />
                Regenerate Account Link
              </VBtn>
            </VCol>
          </VRow>

          <!-- Account ID and Setup URL in single row --
          <VRow class="mt-4">
            <VCol cols="12" md="6">
              <label class="field-label">Stripe Account ID</label>
              <VTextField
                :model-value="
                  stripeAccountId
                    ? `acc${'*'.repeat(Math.max(0, stripeAccountId.length - 6))}${stripeAccountId.slice(-6)}`
                    : ''
                "
                placeholder="Stripe Account ID"
                variant="outlined"
                density="comfortable"
                readonly
                persistent-placeholder
                hide-details
              />
            </VCol>
            <VCol cols="12" md="6">
              <label class="field-label">Setup URL</label>
              <div v-if="setupUrl" class="setup-url-wrapper">
                <a
                  :href="setupUrl"
                  target="_blank"
                  rel="noopener noreferrer"
                  class="preview-link"
                  :title="setupUrl"
                  :class="{ 'disabled-link': isAnyOperationLoading }"
                >
                  <span class="url-text">{{ setupUrl }}</span>
                  <i class="bx bx-link-external external-icon"></i>
                </a>
                <VBtn
                  icon
                  size="small"
                  variant="text"
                  class="copy-btn"
                  :disabled="isAnyOperationLoading"
                  @click="copyToClipboard(setupUrl)"
                >
                  <i class="bx bx-copy"></i>
                </VBtn>
              </div>
              <div v-else class="no-url-placeholder">
                <span class="text-muted">
                  Setup URL will appear after connecting
                </span>
              </div>

            </VCol>
          </VRow>
        </div>

        <VDivider class="mb-6" />

        <!-- Status --
        <div class="mb-8">
          <h6 class="text-h6 mb-4">Status</h6>
          <VRow>
            <VCol cols="12" md="6">
              <VSelect
                v-model="status"
                :items="statusOptions"
                item-title="title"
                item-value="value"
                label="Status"
                variant="outlined"
                density="comfortable"
              />
            </VCol>
          </VRow>
        </div>

        <!-- Save Actions --
        <VRow class="mt-6">
          <VCol>
            <VBtn
              color="primary"
              class="me-3"
              @click="savePaymentSettings"
              :loading="isSubmitting || settingStore.loading"
              :disabled="isSubmitting || settingStore.loading"
            >
              <VIcon icon="bx-save" class="me-2" />
              Save Payment Settings
            </VBtn>
            <VBtn
              color="secondary"
              variant="outlined"
              @click="resetForm"
              :disabled="isSubmitting || settingStore.loading"
            >
              <VIcon icon="bx-reset" class="me-2" />
              Reset
            </VBtn>
          </VCol>
        </VRow>
      </VForm>
    </VCardText>
    -->
  </VCard>
</template>

<style scoped>
.text-muted {
  color: rgba(var(--v-theme-on-surface), 0.6);
}

.mt-6 {
  margin-top: 24px !important;
}

.mb-8 {
  margin-bottom: 32px !important;
}

.mb-6 {
  margin-bottom: 24px !important;
}

.mb-4 {
  margin-bottom: 16px !important;
}

.mt-4 {
  margin-top: 16px !important;
}

/* Field Label - Matches Vuetify's label style */
.field-label {
  display: block;
  color: rgba(var(--v-theme-on-surface), 0.6);
  font-size: 0.75rem;
  font-weight: 400;
  letter-spacing: 0.0333333333em;
  line-height: 1rem;
  margin-bottom: 8px;
  padding-left: 4px;
}

/* Setup URL Wrapper */
.setup-url-wrapper {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  width: 100%;
  min-width: 0;
}

.preview-link {
  color: #003b6f;
  text-decoration: none;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-family: monospace;
  background: #f1f5f9;
  padding: 0.5rem 0.75rem;
  border-radius: 4px;
  font-size: 0.875rem;
  transition: all 0.2s ease;
  flex: 1;
  min-width: 0;
  overflow: hidden;
  min-height: 40px;
}

.preview-link:hover:not(.disabled-link) {
  background: #e2e8f0;
  color: #002749;
}

.preview-link.disabled-link {
  opacity: 0.6;
  pointer-events: none;
  cursor: not-allowed;
}

.url-text {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.external-icon {
  flex-shrink: 0;
  margin-left: 0.25rem;
  font-size: 1rem;
}

.copy-btn {
  flex-shrink: 0;
}

.no-url-placeholder {
  display: flex;
  align-items: center;
  min-height: 40px;
  padding: 0.5rem 0.75rem;
  background: #f5f5f5;
  border-radius: 4px;
}

/* Responsive */
@media (max-width: 960px) {
  .setup-url-wrapper {
    flex-direction: column;
    align-items: stretch;
    gap: 0.25rem;
  }

  .preview-link {
    width: 100%;
  }
}

/* Disabled states */
:deep(.v-field--disabled) {
  opacity: 0.6;
}

:deep(.v-btn--disabled) {
  opacity: 0.6 !important;
  pointer-events: none;
}

/*==========Payment-tabs-css============*/
.v-card.tabs-container {
  padding: 0 24px 8px;
}
.tabs-container .v-window.v-theme--light.pa-4 {
  padding-left: 0 !important;
  padding-right: 0 !important;
}
.tab-content .v-card {
  padding: 0 !important;
  box-shadow: none !important;
}
i.bx-important {
  color: #003b6f;
  margin-top: 5px;
}
.tab-content .text-caption {
  font-size: 12px !important;
}
i.bx-question.v-icon.notranslate.v-theme--light.v-icon--size-default.me-0 {
  width: 16px;
  height: 14px;
  margin-top: 3px;
}
.no-url-placeholder {
    justify-content: space-between;
}
.no-url-placeholder i.bx-info-circle {
    width: 18px;
    height: 18px;
    cursor: pointer;
}
.stripe-toggle {
    padding-left: 0;
}
.tool-tip i.bx-info-circle.v-icon {
    margin-top: -8px;
}
</style>
