<template>
  <div class="setup-container">
    <v-card class="setup-card" elevation="4">
      <v-card-title class="text-h5 text-center font-weight-bold">
        Setup Loket Pembayaran
      </v-card-title>
      <v-card-text>
        <div v-if="currentIp" class="mb-4 text-center">
          <p class="text-subtitle-1 text-grey-darken-1">IP Loket Saat Ini:</p>
          <p class="text-h5 font-weight-bold">{{ currentIp }}</p>
          <v-btn
            color="red"
            variant="text"
            size="small"
            class="mt-2"
            @click="clearIp"
          >
            Hapus IP
          </v-btn>
        </div>

        <v-text-field
          v-model="loketIp"
          label="Masukkan IP Address Baru"
          variant="outlined"
          :rules="[rules.required, rules.ipAddress]"
          hide-details="auto"
          class="mt-4"
        ></v-text-field>
      </v-card-text>
      <v-card-actions class="justify-center">
        <v-btn
          color="white"
          @click="saveIpAddress"
          :disabled="!isValidIp"
          variant="flat"
        >
          Simpan dan Lanjutkan
        </v-btn>
      </v-card-actions>
    </v-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';

const loketIp = ref('');
const currentIp = ref(null);
const router = useRouter();

const rules = {
  required: value => !!value || 'IP Address wajib diisi.',
  ipAddress: value => {
    const pattern = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/;
    return pattern.test(value) || 'Format IP Address tidak valid.';
  }
};

const isValidIp = computed(() => {
  return loketIp.value && rules.ipAddress(loketIp.value) === true;
});

const saveIpAddress = () => {
  if (isValidIp.value) {
    localStorage.setItem('loketIp', loketIp.value);
    console.log('IP Address disimpan:', loketIp.value);
    router.push('/');
  }
};

const clearIp = () => {
  localStorage.removeItem('loketIp');
  currentIp.value = null;
  loketIp.value = '';
};

onMounted(() => {
  currentIp.value = localStorage.getItem('loketIp');
});
</script>

<style scoped>
.setup-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #ffd7b5 20%, #ff9248 100%);
}
.setup-card {
  max-width: 400px;
  width: 100%;
  padding: 20px;
  border-radius: 12px;
}
</style>