<template>
  <div>
    <!-- Compact Header -->
    <PageHeader
      icon="mdi-shield-check"
      title="Verifikasi Akun"
      :subtitle="currentDate"
      :show-add-button="false"
      theme="primary"
    />

    <div class="verification-container">
      <!-- Main Content -->
      <v-card class="verification-card" elevation="0">
        <!-- Search & Content -->
        <v-card-text class="pa-4">
        <!-- Search & Filter -->
        <div class="search-filter-section">
          <div class="section-label">DATA PASIEN</div>
          
          <!-- Status Filter Chips -->
          <v-chip-group 
            v-model="filterStatus" 
            mandatory 
            class="status-filter mb-3"
          >
            <v-chip 
              :value="0"
              :class="{ 'active-chip': filterStatus === 0 }"
            >
              <v-icon start size="16">mdi-account-group</v-icon>
              Semua ({{ patients.length }})
            </v-chip>
            <v-chip 
              :value="1"
              :class="{ 'active-chip': filterStatus === 1 }"
            >
              <v-icon start size="16">mdi-clock-alert</v-icon>
              Belum Verifikasi ({{ unverifiedPatients.length }})
            </v-chip>
            <v-chip 
              :value="2"
              :class="{ 'active-chip': filterStatus === 2 }"
            >
              <v-icon start size="16">mdi-check-decagram</v-icon>
              Terverifikasi ({{ verifiedPatients.length }})
            </v-chip>
          </v-chip-group>

          <!-- Search Field -->
          <v-text-field
            v-model="search"
            prepend-inner-icon="mdi-magnify"
            placeholder="Cari nama atau No. RM..."
            variant="outlined"
            density="compact"
            hide-details
            clearable
            class="search-field"
          ></v-text-field>
        </div>

        <!-- Data Table -->
        <v-data-table
          :headers="headers"
          :items="filteredPatients"
          :items-per-page="10"
          class="elevation-0 data-table"
        >
          <template v-slot:item.no="{ index }">
            {{ index + 1 }}
          </template>

          <template v-slot:item.status="{ item }">
            <v-chip
              size="small"
              :class="item.status === 'Terverifikasi' ? 'chip-success' : 'chip-warning'"
            >
              <v-icon
                :icon="item.status === 'Terverifikasi' ? 'mdi-check-circle' : 'mdi-clock-alert'"
                size="14"
                class="mr-1"
              ></v-icon>
              {{ item.status }}
            </v-chip>
          </template>

          <template v-slot:item.telepon="{ item }">
            <span v-if="item.telepon">{{ item.telepon }}</span>
            <v-chip v-else size="small" class="chip-neutral">Belum diisi</v-chip>
          </template>

          <template v-slot:item.actions="{ item }">
            <v-btn
              v-if="item.status === 'Belum Terverifikasi'"
              size="small"
              @click="openDaftarModal(item)"
              variant="flat"
              class="btn-verify"
            >
              <v-icon size="16" left>mdi-qrcode-scan</v-icon>
              Verifikasi
            </v-btn>
          </template>
        </v-data-table>
      </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="'#3A61C9'"
          :background="'#FFFFFF'"
          class="qr-code"
        />
      </template>
    </QRVerificationDialog>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue';
import { useDisplay } from 'vuetify';
import { storeToRefs } from 'pinia';
import QrcodeVue from 'qrcode.vue';
import PageHeader from '@/components/common/PageHeader.vue';
import QRVerificationDialog from '@/components/verification/QRVerificationDialog.vue';
import { useVerificationStore } from '~/stores/verificationStore';

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

const display = useDisplay();
const verificationStore = useVerificationStore();
const { patients, loading, error } = storeToRefs(verificationStore);

// Load initial patients on mount
onMounted(() => {
  verificationStore.fetchAllPatients();
});

// Table Headers
const headers = ref([
  { title: 'No', value: 'no', sortable: false, width: '60px', align: 'center' },
  { title: 'Nama Pasien', value: 'nama', sortable: true, align: 'center' },
  { title: 'No. RM', value: 'rm', sortable: true, align: 'center' },
  { title: 'Alamat', value: 'alamat', sortable: false, align: 'center' },
  { title: 'No. Telepon', value: 'telepon', sortable: false, align: 'center' },
  { title: 'Status', value: 'status', sortable: true, width: '180px', align: 'center' },
  { title: 'Actions', value: 'actions', sortable: false, width: '200px', align: 'center' },
]);

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

// Debounced Search
let searchTimeout;
watch(search, (newVal) => {
  clearTimeout(searchTimeout);
  if (!newVal || newVal.length < 2) {
    if (!newVal) verificationStore.fetchAllPatients();
    return;
  }

  // Set loading via store action if possible or utilize store's async nature
  // Ideally store handles loading state internally during fetch
  searchTimeout = setTimeout(() => {
    if (/^\d+$/.test(newVal)) {
        verificationStore.fetchPatientByRm(newVal);
    } else {
        verificationStore.searchPatientsByName(newVal);
    }
  }, 600);
});

// 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 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;
  }
  
  return statusFiltered;
});

const qrCodeData = computed(() => {
  return qrCodeGenerated.value 
    ? JSON.stringify({
        rm: selectedPatient.value.rm,
        phone: tempTelepon.value, // Using tempTelepon which is bound to input
        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) {
    qrCodeGenerated.value = true;
  }
};

const reloadQr = () => {
  qrCodeGenerated.value = false;
  setTimeout(() => {
    qrCodeGenerated.value = true;
  }, 500);
};

const completeVerification = () => {
  // Use store action to update local state optimistically
  verificationStore.updatePatientVerification(selectedPatient.value.rm, tempTelepon.value);
  
  // TODO: Add API call in store to save verification

  filterStatus.value = 2; // Switch tab to verified
  closeModal();
};

// Cleanup
onUnmounted(() => {
    verificationStore.clearPatients();
});
</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;

// Blue/Primary Colors
$primary-700: #3556AE;
$primary-600: #3A61C9;
$primary-500: #567EE7;
$primary-400: #7898EC;
$primary-300: #9AB2F1;
$primary-200: #BBCBF5;

$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
// ============================================
/* Header styles are now handled by PageHeader component */

.verification-container {
  background: var(--color-neutral-300);
  min-height: 100vh;
  padding: 16px;
}

.verification-card {
  border-radius: 12px;
  border: 1px solid var(--color-neutral-500);
  background: var(--color-neutral-100);
}

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

// ============================================
// SEARCH & FILTER SECTION
// ============================================
.search-filter-section {
  margin-bottom: 24px;
}

.section-label {
  font-size: 11px;
  font-weight: 700;
  letter-spacing: 0.5px;
  color: $neutral-600;
  text-transform: uppercase;
  margin-bottom: 12px;
}

.status-filter {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.status-filter .v-chip {
  font-size: 12px;
  font-weight: $font-weight-semibold;
  height: 32px;
  border: 1px solid $neutral-500;
  background: $neutral-100;
  color: $neutral-600;
  transition: all 0.2s ease;
  
  &:hover {
    background: $neutral-300;
  }
}

.status-filter .v-chip.active-chip {
  background: $primary-600;
  color: $neutral-100;
  border-color: $primary-600;
}

.search-field {
  max-width: 400px;
  font-size: 14px;
  line-height: 20px;
}

// ============================================
// DATA TABLE
// ============================================
.data-table {
  font-family: $font-family-base;
  
  :deep(.v-data-table__th) {
    font-weight: $font-weight-semibold;
    color: $neutral-800;
    font-size: 14px;
    line-height: 20px;
    text-align: center !important;
    
    .v-data-table-header__content {
      justify-content: center !important;
      width: 100%;
    }
  }
  
  :deep(.v-data-table__td) {
    font-size: 14px;
    line-height: 20px;
    color: $neutral-900;
    text-align: center !important;
  }
  
  // Ensure the cell content itself is centered if it contains flex/divs
  :deep(.v-data-table__td > *) {
    display: inline-flex;
    justify-content: center;
    align-items: center;
  }
}

// ============================================
// CHIPS
// ============================================
.chip-success {
  background-color: #009262 !important;
  color: $neutral-100 !important;
  font-weight: $font-weight-medium;
  font-size: 12px;
  line-height: 16px;
}

.chip-success-outline {
  border: 1px solid #009262;
  background-color: transparent !important;
  color: #009262 !important;
  font-weight: $font-weight-medium;
  font-size: 12px;
  line-height: 16px;
}

.chip-warning {
  background-color: #F59E0B !important;
  color: $neutral-100 !important;
  font-weight: $font-weight-medium;
  font-size: 12px;
  line-height: 16px;
}

.chip-neutral {
  background-color: $neutral-600 !important;
  color: $neutral-100 !important;
  font-weight: $font-weight-medium;
  font-size: 12px;
  line-height: 16px;
}

// ============================================
// BUTTONS
// ============================================
.btn-verify {
  background-color: $primary-600 !important;
  color: $neutral-100 !important;
  text-transform: none;
  font-weight: $font-weight-semibold;
  font-size: 14px;
  line-height: 20px;
  
  &:hover {
    background-color: $primary-700 !important;
  }
}

// ============================================
// 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>