<template>
  <div class="medical-payment-app">
    <v-container fluid class="pa-0">
      <v-row justify="center" no-gutters>
        <v-col cols="12">
          <v-card
            class="payment-card mx-auto"
            elevation="0"
            :class="{
              'contact-fullscreen': paymentStore.currentStep === 1,
              'payment-centered': paymentStore.currentStep !== 1,
            }"
          >
            <component :is="activeComponent" />
          </v-card>
        </v-col>
      </v-row>
    </v-container>
  </div>
</template>

<script setup>
import { usePaymentStore } from '~/stores/payment';
import Home from '~/components/Home.vue';
import QRISPayment from '~/components/QRISPayment.vue';
import Success from '~/components/PembayaranSukses.vue';

const paymentStore = usePaymentStore();
const apiURL = 'http://10.10.150.37:8084/api/v1/qris';

const paymentSteps = {
  1: Home,
  2: QRISPayment,
  3: Success,
};

const activeComponent = computed(() => {
  return paymentSteps[paymentStore.currentStep] || Home;
});

const { data: apiData, refresh } = await useFetch(apiURL, {
  server: false,
  immediate: false,
});

watch(apiData, (newData) => {
  if (newData && newData.data && newData.data.length > 0) {
    const relevantData = newData.data[0];
    if (relevantData) {
      paymentStore.updatePayment({ data: [relevantData] });
      clearInterval(pollingInterval);
      console.log('Polling stopped. Data received from API.');
    }
  }
});

let pollingInterval = null;

onMounted(() => {
  if (paymentStore.currentStep === 1) {
    pollingInterval = setInterval(() => {
      refresh();
    }, 500000);
  }
});

onUnmounted(() => {
  if (pollingInterval) {
    clearInterval(pollingInterval);
    console.log('Polling stopped on unmount.');
  }
});

watch(() => paymentStore.currentStep, (newStep, oldStep) => {
  if (newStep === 1 && oldStep !== 1) {
    pollingInterval = setInterval(() => {
      refresh();
    }, 5000);
  } else if (newStep !== 1 && pollingInterval) {
    clearInterval(pollingInterval);
  }
});
</script>

<style scoped>
.medical-payment-app {
  min-height: 100vh;
  background: linear-gradient(135deg, #ffd7b5 20%, #ff9248 100%);
}

.contact-fullscreen {
  height: 100vh !important;
  max-width: none !important;
  border-radius: 0 !important;
}
.payment-centered {
  max-width: 500px !important;
  margin-top: 2rem !important;
  border-radius: 16px !important;
}

.payment-card {
  background: white;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
}
</style>