<template>
  <div class="payment-step">
    <v-card-text class="main-content pa-4">
      <div class="header-section text-center mb-8">
        <h2 class="payment-title">Pindai Kode QR untuk Pembayaran</h2>
        <p class="payment-subtitle">
          Gunakan aplikasi mobile banking atau e-wallet Anda
        </p>
      </div>

      <div class="main-content-section mb-8">
        <div :class="isPortrait ? 'content-stack' : 'content-grid'">
          <!-- QR Section -->
          <div class="qr-section">
            <div class="qr-container">
              <div class="qris-logo-container mb-4">
                <v-img
                  src="/rssalogo.png"
                  :height="isPortrait ? 100 : 60"
                  class="RSSA-logo"
                  contain
                />
                <v-img
                  src="/bankjatimlogo.png"
                  :height="isPortrait ? 50 : 30"
                  class="jatim-logo"
                  contain
                />
              </div>
              <div class="qr-wrapper">
                <div class="qr-code-bg">
                  <img
                    ref="qrCodeImage"
                    alt="QR Code"
                    class="qr-image"
                    :class="{ 'qr-loaded': qrLoaded }"
                  />
                  <div class="qr-overlay" v-if="!qrLoaded">
                    <v-progress-circular
                      indeterminate
                      color="primary"
                      size="40"
                    />
                  </div>
                </div>
              </div>

              <div class="scan-line" v-if="qrLoaded"></div>
              <div>
                <!-- Tampilkan text jika invoice number sama dengan qrvalue -->
                <div v-if="isInvoiceMatchQR" class="detail-column">
                  <div class="detail-label">
                    <v-icon size="18" class="mr-2" color="primary"
                      >mdi-credit-card-outline</v-icon
                    >
                    No Virtual Account
                  </div>
                  <div class="detail-value">
                    {{ paymentStore.qrData.qrvalue }}
                  </div>
                </div>

                <!-- Tampilkan logo QRIS jika berbeda -->
                <v-img
                  v-else
                  src="/qrislogo.png"
                  :height="isPortrait ? 70 : 50"
                  class="qris-logo mb-n3 mt-n2"
                  contain
                />
              </div>
            </div>

            <div class="qr-instructions text-center mt-4">
              <v-icon size="20" color="primary" class="mb-2"
                >mdi-qrcode-scan</v-icon
              >
              <div class="instruction-text">Arahkan kamera ke QR code</div>
            </div>
          </div>

          <!-- Details Section -->
          <div class="details-section">
            <div class="payment-details-card">
              <div class="details-header">
                <v-icon color="primary" class="mr-2"
                  >mdi-receipt-text-outline</v-icon
                >
                <span class="details-title">Detail Pembayaran</span>
              </div>

              <div class="details-content">
                <div class="detail-row-split">
                  <div class="detail-column">
                    <div class="detail-label">
                      <v-icon size="18" class="mr-2" color="primary"
                        >mdi-card-account-details-outline</v-icon
                      >
                      No RM
                    </div>
                    <div class="detail-value">
                      {{ paymentStore.qrData.display_norm || "-" }}
                    </div>
                  </div>
                  <div class="detail-column">
                    <div class="detail-label">
                      <v-icon size="18" class="detail-icon mr-2" color="primary"
                        >mdi-file-document-outline</v-icon
                      >
                      No Billing
                    </div>
                    <div class="detail-value">
                      {{ paymentStore.qrData.display_nobill || "-" }}
                    </div>
                  </div>
                </div>

                <div class="detail-row">
                  <div class="detail-label">
                    <v-icon size="18" class="mr-2" color="primary"
                      >mdi-account-outline</v-icon
                    >
                    Nama Pasien
                  </div>
                  <div class="detail-value patient-name">
                    {{
                      paymentStore.patientInfo.name &&
                      paymentStore.patientInfo.name.length > 28
                        ? paymentStore.patientInfo.name.substring(0, 25) + "..."
                        : paymentStore.patientInfo.name
                    }}
                  </div>
                </div>

                <div class="detail-row highlight-row">
                  <div class="detail-label">
                    <v-icon size="18" class="mr-2" color="success"
                      >mdi-cash</v-icon
                    >
                    Nominal
                  </div>
                  <div class="detail-value amount">
                    {{ formatCurrency(paymentStore.patientInfo.amount) }}
                  </div>
                </div>

                <div class="detail-row">
                  <div class="detail-label">
                    <v-icon size="18" class="mr-2" color="warning"
                      >mdi-clock-outline</v-icon
                    >
                    Berlaku Sampai
                  </div>
                  <div class="detail-value expired">
                    {{ expiryDisplayTime }}
                  </div>
                </div>
              </div>

              <div class="payment-status mt-4">
                <div class="status-row">
                  <div class="status-indicator-inline">
                    <div class="status-dot pulsing"></div>
                    <span class="status-text">Menunggu pembayaran...</span>
                  </div>
                  <v-chip color="warning" variant="tonal" size="small">
                    <v-icon size="14" class="mr-1">mdi-clock-fast</v-icon>
                    Pending
                  </v-chip>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- <div class="action-buttons">
        <v-btn
          color="grey-lighten-1"
          variant="outlined"
          size="large"
          class="action-btn back-btn"
          @click="paymentStore.prevStep"
        >
          <v-icon class="mr-2">mdi-arrow-left</v-icon>
          Kembali
        </v-btn>

        <v-btn
          color="success"
          variant="flat"
          size="large"
          class="action-btn"
          @click="simulateSuccess"
        >
          <v-icon class="mr-2">mdi-check-circle-outline</v-icon>
          Simulasi Sukses
        </v-btn>

        <v-btn
          color="error"
          variant="flat"
          size="large"
          class="action-btn"
          @click="simulateFailure"
        >
          <v-icon class="mr-2">mdi-close-circle-outline</v-icon>
          Simulasi Pending
        </v-btn>
      </div> -->
    </v-card-text>
  </div>
</template>

<script setup>
import { usePaymentStore } from "~/stores/payment";
import QRCode from "qrcode";
import { ref, onMounted, watch, onBeforeUnmount, computed } from "vue";

const paymentStore = usePaymentStore();
const qrCodeImage = ref(null);
const qrLoaded = ref(false);
const windowWidth = ref(window.innerWidth);
const windowHeight = ref(window.innerHeight);

const isPortrait = computed(() => windowHeight.value > windowWidth.value);
const qrSize = computed(() => (isPortrait.value ? 280 : 240));

// Computed untuk mengecek apakah invoice number sama dengan qrvalue
const isInvoiceMatchQR = computed(() => {
  const invoiceNumber = paymentStore.qrData.invoice_number;
  const qrValue = paymentStore.qrData.qrvalue;
  return invoiceNumber && qrValue && invoiceNumber === qrValue;
});

const expiryDisplayTime = ref("Menghitung...");
let countdownInterval = null;

const handleResize = () => {
  windowWidth.value = window.innerWidth;
  windowHeight.value = window.innerHeight;
};

const formatTimeLeft = (seconds) => {
  if (seconds <= 0) {
    clearInterval(countdownInterval);
    return "KEDALUWARSA";
  }

  const h = String(Math.floor(seconds / 3600)).padStart(2, "0");
  const m = String(Math.floor((seconds % 3600) / 60)).padStart(2, "0");
  const s = String(seconds % 60).padStart(2, "0");
  return `${h}:${m}:${s}`;
};

/**
 * Memulai hitungan mundur berdasarkan string waktu kedaluwarsa (expired_at).
 * @param {string} expiryTimeString - String waktu kedaluwarsa, misal: "2025-10-29 13:10:49".
 */
const startCountdown = (expiryTimeString) => {
  const isoDateString = expiryTimeString
    ? expiryTimeString.replace(" ", "T")
    : null;
  const expiryDate = isoDateString ? new Date(isoDateString) : null;

  if (!expiryDate || isNaN(expiryDate.getTime())) {
    expiryDisplayTime.value = "Waktu tidak valid";
    return;
  }

  if (countdownInterval) {
    clearInterval(countdownInterval);
  }

  const updateCountdown = () => {
    const now = new Date().getTime();
    const timeRemainingMs = expiryDate.getTime() - now;

    const timeRemainingSeconds = Math.max(
      0,
      Math.floor(timeRemainingMs / 1000)
    );

    expiryDisplayTime.value = formatTimeLeft(timeRemainingSeconds);
  };

  updateCountdown();

  countdownInterval = setInterval(updateCountdown, 1000);
};

onBeforeUnmount(() => {
  if (countdownInterval) {
    clearInterval(countdownInterval);
  }
  window.removeEventListener("resize", handleResize);
});

const formatCurrency = (amountString) => {
  const cleanString = amountString.replace(/\./g, "").replace(",", ".");
  const amount = parseFloat(cleanString);

  if (isNaN(amount)) {
    return "Invalid Amount";
  }

  return new Intl.NumberFormat("id-ID", {
    style: "currency",
    currency: "IDR",
    minimumFractionDigits: 0,
  }).format(amount);
};

const generateQRCode = async () => {
  const qrValue = paymentStore.qrData.qrvalue;
  if (qrValue) {
    try {
      qrLoaded.value = false;
      const dataUrl = await QRCode.toDataURL(qrValue, {
        width: qrSize.value,
        margin: 1,
        color: {
          dark: "#000000",
          light: "#FFFFFF",
        },
        errorCorrectionLevel: "M",
      });
      if (qrCodeImage.value) {
        qrCodeImage.value.src = dataUrl;
        qrCodeImage.value.onload = () => {
          qrLoaded.value = true;
        };
      }
    } catch (error) {
      console.error("Failed to generate QR Code:", error);
    }
  }
};

const simulateSuccess = () => {
  console.log("--- DEBUG: SIMULASI SUKSES ---");
  const currentData = paymentStore.qrData;

  const successData = {
    data: [
      {
        ...currentData,
        status: "2",
        transaction_id: `TRX-SIM-SUKSES-${Date.now()}`,
      },
    ],
  };

  paymentStore.updatePayment(successData);
};

const simulateFailure = () => {
  console.log("--- DEBUG: SIMULASI GAGAL ---");
  const currentData = paymentStore.qrData;

  const failureData = {
    data: [
      {
        ...currentData,
        status: "0",
        reason: "SIMULASI: Transaksi dibatalkan atau kedaluwarsa.",
      },
    ],
  };

  paymentStore.updatePayment(failureData);
};

onMounted(() => {
  generateQRCode();
  window.addEventListener("resize", handleResize);

  const expiryTimeString = paymentStore.qrData.expired_at;
  if (expiryTimeString) {
    startCountdown(expiryTimeString);
  }
});

watch(
  () => paymentStore.qrData,
  (newQrData) => {
    generateQRCode();

    const expiryTimeString = newQrData.expired_at;
    if (expiryTimeString) {
      startCountdown(expiryTimeString);
      console.log(
        `[QRISPayment] Waktu kedaluwarsa diperbarui: ${expiryTimeString}`
      );
    } else {
      expiryDisplayTime.value = "Data Waktu Tidak Tersedia";
    }
  },
  { deep: true }
);

watch(isPortrait, () => {
  generateQRCode();
});
</script>

<style scoped>
.payment-step {
  background: #ff9248;
}

.main-content {
  background: linear-gradient(135deg, #f8f9ff 0%, #e8f2ff 100%);
  margin-top: 10px;
  margin-bottom: 10px;
  border-radius: 16px;
  height: fit-content;
}

.header-section {
  padding-top: 0px;
}

.qris-logo-container {
  display: flex;
  gap: 0rem;
  align-items: center;
  flex-wrap: wrap;
  justify-content: center;
}

.jatim-logo {
  filter: drop-shadow(0 2px 8px rgba(0, 0, 0, 0.1));
  transition: transform 0.3s ease;
  align-items: baseline;
  margin-right: 5px;
}

.RSSA-logo {
  filter: drop-shadow(0 2px 8px rgba(0, 0, 0, 0.1));
  transition: transform 0.3s ease;
  align-items: end;
  margin-right: -50px !important;
}

.payment-title {
  font-size: 1.5rem;
  font-weight: 700;
  color: #1a1a1a;
  margin-top: 0;
  margin-bottom: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.payment-subtitle {
  color: #666;
  font-size: 0.9rem;
  margin-bottom: 0;
}

.main-content-section {
  width: 100%;
}

.qr-section {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.details-section {
  display: flex;
  flex-direction: column;
}

.qr-container {
  position: center;
  background: linear-gradient(145deg, #ffffff, #f0f4f8);
  border-radius: 24px;
  padding: 1rem;
  box-shadow:
    0 20px 40px rgba(0, 0, 0, 0.08),
    0 8px 16px rgba(0, 0, 0, 0.04),
    inset 0 1px 0 rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
  width: 100%;
  transition: all 0.3s ease;
}

.qr-wrapper {
  position: relative;
  display: inline-block;
}

.qr-code-bg {
  background: #00000000;
  border-radius: 16px;
  padding: 1rem;
  position: relative;
  overflow: hidden;
}

.qr-image {
  border-radius: 8px;
  transition:
    opacity 0.3s ease,
    transform 0.3s ease,
    width 0.3s ease,
    height 0.3s ease;
  opacity: 0;
  transform: scale(0.9);
}

.qr-image.qr-loaded {
  opacity: 1;
  transform: scale(1);
}

.qr-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(48, 72, 97, 0.9);
  border-radius: 8px;
}

.scan-line {
  position: absolute;
  left: 2rem;
  right: 2rem;
  height: 2px;
  background: linear-gradient(90deg, transparent, #667eea, transparent);
  animation: scanning 2s ease-in-out infinite;
}

.qris-logo {
  filter: drop-shadow(0 2px 8px rgba(0, 0, 0, 0.1));
  transition: transform 0.3s ease;
  align-items: baseline;
  margin-right: 5px;
}

.invoice-text {
  color: #1a1a1a;
  font-weight: 700;
  font-size: 1.2rem;
  margin-left: 1.5rem;
}

@keyframes scanning {
  0% {
    top: 2rem;
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  100% {
    top: calc(100% - 2rem);
    opacity: 0;
  }
}

.qr-instructions {
  margin-top: 1rem;
  display: flex;
  gap: 8px;
}

.instruction-text {
  color: #666;
  font-size: 0.8rem;
  font-weight: 500;
  margin: 0;
}

.payment-details-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 1.5rem;
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.06),
    inset 0 1px 0 rgba(255, 255, 255, 0.8);
  height: fit-content;
  width: 100%;
}

.details-header {
  display: flex;
  align-items: center;
  margin-bottom: 1rem;
  padding-bottom: 0.5rem;
  border-bottom: 2px solid rgba(0, 0, 0, 0.06);
}

.details-title {
  font-weight: 700;
  color: #1a1a1a;
  font-size: 1.2rem;
}

.details-content {
  display: flex;
  flex-direction: column;
  gap: 0.4rem;
}

.detail-row {
  display: flex;
  flex-direction: column;
  gap: 0.2rem;
  padding: 0.5rem;
  border-radius: 12px;
  background: rgba(248, 250, 252, 0.6);
  border: 1px solid rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.detail-row:hover {
  background: rgba(248, 250, 252, 0.9);
  transform: translateY(-1px);
}

.detail-row-split {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 0.5rem;
  padding: 0.5rem;
  border-radius: 12px;
  background: rgba(248, 250, 252, 0.6);
  border: 1px solid rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.detail-row-split:hover {
  background: rgba(248, 250, 252, 0.9);
  transform: translateY(-1px);
}

.detail-column {
  display: flex;
  flex-direction: column;
  gap: 0.2rem;
  padding: 0.5rem;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.5);
  border: 1px solid rgba(0, 0, 0, 0.04);
}

.highlight-row {
  background: rgba(46, 204, 113, 0.08) !important;
  border: 1px solid rgba(46, 204, 113, 0.2) !important;
}

.highlight-row:hover {
  background: rgba(46, 204, 113, 0.12) !important;
}

.detail-label {
  display: flex;
  align-items: center;
  color: #666;
  font-size: 0.8rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.detail-value {
  color: #1a1a1a;
  font-weight: 700;
  font-size: 1.2rem;
  margin-left: 1.5rem;
}

.detail-value.patient-name {
  color: #2c3e50;
  font-size: 1.2rem;
}

.details-icon {
  size: 18;
}

.detail-value.amount {
  color: #27ae60;
  font-size: 1.4rem;
  font-weight: 800;
}

.detail-value.expired {
  color: #e67e22;
  font-size: 1rem;
}

.payment-status {
  padding: 1rem;
  background: rgba(255, 193, 7, 0.08);
  border-radius: 12px;
  border: 1px solid rgba(255, 193, 7, 0.2);
}

.status-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-indicator-inline {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #f39c12;
}

.status-dot.pulsing {
  animation: pulse 1.5s ease-in-out infinite;
}

@keyframes pulse {
  0%,
  100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.5;
    transform: scale(1.2);
  }
}

.status-text {
  color: #666;
  font-size: 0.9rem;
  font-weight: 500;
}

.action-buttons {
  display: flex;
  gap: 1rem;
  justify-content: center;
  transition: flex-direction 0.3s ease;
}

.action-btn {
  border-radius: 16px !important;
  font-weight: 600 !important;
  text-transform: none !important;
  padding: 0 2rem !important;
  min-width: 140px;
  transition: all 0.3s ease !important;
}

.back-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15) !important;
}

.action-btn:not(.back-btn):hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2) !important;
}

/* PORTRAIT MODE */
@media (orientation: portrait) {
  .payment-title {
    font-size: 2.5rem;
    margin-top: 8px;
    margin-bottom: 0;
  }

  .payment-subtitle {
    color: #666;
    font-size: 1.5rem;
    margin-bottom: 0;
  }

  .content-stack {
    display: flex;
    flex-direction: column;
    gap: 1.5rem;
    align-items: center;
    max-width: 800px;
    margin: 0 auto;
  }

  .qr-section {
    width: 100%;
  }

  .details-section {
    width: 100%;
  }

  .qr-container {
    max-width: fit-content;
    padding: 2rem;
  }

  .qr-code-bg {
    padding: 0.5rem;
  }

  .qr-image {
    width: 500px;
    height: 500px;
  }

  .RSSA-logo {
    margin-right: -40px !important;
  }

  .qris-logo {
    margin-right: 20px;
  }

  .invoice-text {
    font-size: 2rem;
    padding: 1rem 1.5rem;
  }

  .scan-line {
    top: 2.5rem;
  }

  .qr-instructions {
    align-items: center;
    gap: 12px;
  }
  .qr-instructions .v-icon {
    font-size: 40px !important;
    width: 25px !important;
    height: 25px !important;
  }
  .instruction-text {
    color: #666;
    font-size: 1.5rem;
    font-weight: 500;
    margin: 0;
  }

  .details-title {
    font-size: 2rem;
  }
  .details-icon {
    size: 20 !important;
  }

  .detail-label {
    font-size: 1.3em;
  }
  .detail-label .v-icon {
    font-size: 25px !important;
    width: 25px !important;
    height: 25px !important;
  }

  .detail-value {
    font-size: 1.8rem;
    margin-left: 1.25rem;
  }

  .detail-value.patient-name {
    font-size: 1.8rem;
  }

  .detail-value.amount {
    font-size: 1.8rem;
  }

  .detail-value.expired {
    font-size: 1.8rem;
  }

  .status-dot {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    background: #f39c12;
  }

  .status-text {
    font-size: 1.5rem;
    font-weight: 600;
  }

  .action-buttons {
    flex-direction: row;
    flex-wrap: wrap;
    gap: 0.75rem;
  }

  .action-btn {
    width: 100%;
    padding: 0 1.5rem !important;
    border-radius: 12px !important;
  }
}

/* LANDSCAPE MODE */
@media (orientation: landscape) {
  .content-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 0.5rem;
    align-items: start;
    max-width: 1000px;
    margin: 0 auto;
  }

  .qr-container {
    max-width: 350px;
  }

  .qr-image {
    width: 240px;
    height: 240px;
  }

  .scan-line {
    top: 2rem;
  }

  .action-buttons {
    flex-direction: row;
  }
}

/* Small portrait */
/* @media (max-width: 480px) and (orientation: portrait) {
  .qr-container {
    padding: 1rem;
    max-width: 320px;
  }

  .qr-image {
    width: 240px;
    height: 240px;
  }

  .qr-code-bg {
    padding: 1rem;
  }

  .payment-title {
    font-size: 1.3rem;
  }

  .payment-details-card {
    padding: 1.25rem;
  }

  .details-title {
    font-size: rem;
  }

  .detail-value {
    font-size: 0.95rem;
  }

  .detail-value.amount {
    font-size: 1.2rem;
  }
} */
</style>
