<template>
  <v-container>
    <v-card>
      <!-- Header -->
      <div class="page-header">
        <div class="header-content">
          <div class="header-left">
            <div class="header-icon">
              <v-icon size="32" color="white">mdi-shield-check</v-icon>
            </div>
            <div class="header-text">
              <h2 class="page-title">Verifikasi Akun</h2>
              <p class="page-subtitle">{{ currentDate }} - Manajemen Pasien Digital</p>
            </div>
          </div>
          <div class="header-stats">
            <v-chip color="white" variant="flat" class="stat-chip mr-2">
              <v-icon start size="16">mdi-account-group</v-icon>
              {{ patients.length }} User
            </v-chip>
            <v-chip color="white" variant="flat" class="stat-chip mr-2">
              <v-icon start size="16">mdi-clock-alert</v-icon>
              {{ unverifiedPatients.length }} Pending
            </v-chip>
            <v-chip color="white" variant="flat" class="stat-chip">
              <v-icon start size="16">mdi-check-decagram</v-icon>
              {{ verifiedPatients.length }} Terverifikasi
            </v-chip>
          </div>
        </div>
      </div>

      <!-- Search & Content -->
      <v-card-text class="pa-0">
        <!-- Search & Tabs -->
        <VerificationSearchTabs
          v-model:search-query="search"
          v-model:selected-tab="filterStatus"
          :all-count="patients.length"
          :pending-count="unverifiedPatients.length"
          :verified-count="verifiedPatients.length"
        />

        <!-- Patient List -->
        <PatientVerificationList
          :patients="filteredPatients"
          :empty-message="noDataText"
          @verify="openDaftarModal"
        />
      </v-card-text>
    </v-card>

    <!-- QR Verification Dialog -->
    <QRVerificationDialog
      v-model="isModalOpen"
      v-model:phone-number="tempTelepon"
      :patient="selectedPatient"
      :qr-generated="qrCodeGenerated"
      :is-mobile="display.xs.value"
      @generate="generateQrCode"
      @reload="reloadQr"
      @complete="completeVerification"
      @close="closeModal"
    >
      <template #qr-code>
        <qrcode-vue 
          :value="qrCodeData" 
          :size="qrSize" 
          level="H" 
          :foreground="'#FFA532'"
          :background="'#FFFFFF'"
          class="qr-code"
        />
      </template>
    </QRVerificationDialog>
  </v-container>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useDisplay } from 'vuetify';
import QrcodeVue from 'qrcode.vue';
import VerificationSearchTabs from '@/components/verification/VerificationSearchTabs.vue';
import PatientVerificationList from '@/components/verification/PatientVerificationList.vue';
import QRVerificationDialog from '@/components/verification/QRVerificationDialog.vue';

definePageMeta({
  middleware: ['auth']
});

const display = useDisplay();

// Data
const patients = ref([
  { nama: 'Budi Santoso', rm: '00123456', alamat: 'Jl. Melati No. 10', telepon: '', status: 'Belum Terverifikasi' },
  { nama: 'Siti Aminah', rm: '00123457', alamat: 'Perum. Indah Blok A', telepon: '081234567890', status: 'Terverifikasi' },
  { nama: 'Joko Susilo', rm: '00123458', alamat: 'Jl. Pahlawan 5', telepon: '', status: 'Belum Terverifikasi' },
  { nama: 'Dewi Lestari', rm: '00123459', alamat: 'Gang Mawar 12', telepon: '089876543210', status: 'Terverifikasi' },
  { nama: 'Rina Wijaya', rm: '00123460', alamat: 'Jl. Sudirman 21', telepon: '', status: 'Belum Terverifikasi' },
]);

const filterStatus = ref(0);
const search = ref('');
const isModalOpen = ref(false);
const selectedPatient = ref({});
const tempTelepon = ref('');
const qrCodeGenerated = ref(false);

// Computed
const currentDate = computed(() => {
  const now = new Date();
  const days = ['Minggu', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu'];
  const months = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
  return `${days[now.getDay()]}, ${now.getDate()} ${months[now.getMonth()]} ${now.getFullYear()}`;
});

const noDataText = computed(() => 
  search.value 
    ? 'Tidak ada data pasien yang cocok dengan pencarian.' 
    : 'Tidak ada pasien dengan status ini.'
);

const unverifiedPatients = computed(() =>
  patients.value.filter((p) => p.status === 'Belum Terverifikasi')
);

const verifiedPatients = computed(() =>
  patients.value.filter((p) => p.status === 'Terverifikasi')
);

const filteredPatients = computed(() => {
  let statusFiltered = patients.value;

  if (filterStatus.value === 1) {
    statusFiltered = unverifiedPatients.value;
  } else if (filterStatus.value === 2) {
    statusFiltered = verifiedPatients.value;
  }
    
  if (!search.value) return statusFiltered;
  
  const searchTerm = search.value.toLowerCase();
  return statusFiltered.filter(p => 
    p.nama.toLowerCase().includes(searchTerm) || 
    p.rm.includes(searchTerm)
  );
});

const qrCodeData = computed(() => {
  return qrCodeGenerated.value 
    ? JSON.stringify({
        rm: selectedPatient.value.rm,
        phone: tempTelepon.value,
        action: 'verify-account',
        timestamp: Date.now()
      })
    : '';
});

const qrSize = computed(() => {
  if (display.xs.value) return 120;
  if (display.sm.value) return 200;
  return 220;
});

// Methods
const openDaftarModal = (patient) => {
  selectedPatient.value = patient;
  tempTelepon.value = patient.telepon || '';
  qrCodeGenerated.value = false;
  isModalOpen.value = true;
};

const closeModal = () => {
  isModalOpen.value = false;
  selectedPatient.value = {};
  tempTelepon.value = '';
  qrCodeGenerated.value = false;
};

const generateQrCode = () => {
  if (tempTelepon.value.length >= 8) {
    console.log(`[API CALL] Generating QR for ${selectedPatient.value.nama}. QR Data: ${qrCodeData.value}`);
    setTimeout(() => {
      qrCodeGenerated.value = true;
    }, 200);
  }
};

const reloadQr = () => {
  console.log('[API CALL] Reloading QR Code...');
  qrCodeGenerated.value = false;
  setTimeout(() => {
    qrCodeGenerated.value = true;
    console.log('QR Code reloaded.');
  }, 500);
};

const completeVerification = () => {
  const patientIndex = patients.value.findIndex(
    (p) => p.rm === selectedPatient.value.rm
  );

  if (patientIndex !== -1) {
    patients.value[patientIndex].status = 'Terverifikasi';
    patients.value[patientIndex].telepon = tempTelepon.value;
  }

  filterStatus.value = 2;
  closeModal();
};
</script>

<style scoped lang="scss">
// Colors from Design System
$neutral-900: #212121;
$neutral-800: #4D4D4D;
$neutral-700: #717171;
$neutral-600: #89939E;
$neutral-500: #ABBED1;
$neutral-400: #E5F7FA;
$neutral-300: #F5F7FA;
$neutral-100: #FFFFFF;

// Orange/Primary Colors
$primary-700: #FF9B1B;
$primary-600: #FFA532;
$primary-500: #FFB95F;
$primary-400: #FFCD8D;
$primary-300: #FFDCAF;
$primary-200: #FFE6C6;

$danger-600: #E02B1D;

// Font Family & Weights
$font-family-base: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
$font-weight-regular: 400;
$font-weight-medium: 500;
$font-weight-semibold: 600;

// Apply font family
* {
  font-family: $font-family-base;
}

// ============================================
// PAGE HEADER
// ============================================
.page-header {
  background: linear-gradient(135deg, $primary-600 0%, $primary-700 100%);
  border-radius: 16px 16px 0 0;
  box-shadow: 0 4px 16px rgba(255, 165, 50, 0.2);
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32px;
  color: $neutral-100;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-icon {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 16px;
  padding: 16px;
  margin-right: 20px;
  backdrop-filter: blur(10px);
}

.page-title {
  font-size: 36px;
  line-height: 44px;
  font-weight: $font-weight-semibold;
  margin: 0;
  color: $neutral-100;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-subtitle {
  margin: 4px 0 0 0;
  opacity: 0.9;
  font-size: 16px;
  line-height: 24px;
  font-weight: $font-weight-regular;
  color: $neutral-100;
}

.header-stats {
  display: flex;
  align-items: center;
  gap: 8px;
}

.stat-chip {
  color: $primary-600 !important;
  font-weight: $font-weight-semibold;
  font-size: 14px;
  line-height: 20px;
}

.qr-code {
  border-radius: 8px;
  display: block;
}

// ============================================
// RESPONSIVE
// ============================================
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .header-stats {
    width: 100%;
    flex-wrap: wrap;
  }

  .page-title {
    font-size: 28px;
    line-height: 36px;
  }
}
</style>