<template>
  <div>
    <!-- Compact Header -->
    <PageHeader
      icon="mdi-desktop-mac"
      :title="`Admin ${loketName}`"
      :subtitle="currentDate"
      :show-add-button="false"
      theme="primary"
    >
      <template #actions>
        <v-btn
          variant="text"
          prepend-icon="mdi-arrow-left"
          @click="router.push('/adminloket')"
          class="mr-2"
        >
          Kembali
        </v-btn>
      </template>
    </PageHeader>

    <div class="loket-container">
      <!-- Main Content Grid -->
      <v-row class="content-grid" dense>
        <!-- Left Column: Current Patient & Queue Actions -->
        <v-col cols="12" md="5" class="sticky-column">
          <div class="sticky-wrapper">
            <!-- Current Patient Card -->
            <CurrentPatientCard
              :patient="currentProcessingPatient"
              :has-next-queue="(diLoketPatients || []).length > 0"
              :next-queue-info="nextQueueInfo"
              @action="handlePatientAction"
              @change-klinik="showChangeKlinikDialog = true"
              @process-next="handleProcessNext"
              @call="handleCallPatient"
              @open-klinik-ruang="openKlinikRuangDialog"
              @open-penunjang="openPenunjangDialog"
            />

            <QueueActionsCard
              class="mt-3"
              :total-quota="loketQuota"
              :used-quota="quotaUsed"
              :menunggu-count="filteredMenungguCount"
              :has-next="!!nextPatient || filteredMenungguCount > 0"
              @call="handleCall"
            />
          </div>
        </v-col>

        <!-- Right Column: Patient Table -->
        <v-col cols="12" md="7">
          <v-card class="patient-data-container" elevation="0">
            <v-card-text class="pa-4">
              <div class="data-header mb-4">
                <div class="section-label mb-3">PANGGIL ANTREAN</div>
              <div v-if="filteredMenungguCount > 0" class="waiting-badge mb-2">
                <v-icon start size="14">mdi-clock-outline</v-icon>
                {{ filteredMenungguCount }} Antrean Menunggu
              </div>
                
                <div class="filters">
                  <!-- Search Field -->
                  <v-text-field
                    v-model="searchQuery"
                    placeholder="Cari barcode, nomor antrian..."
                    density="compact"
                    hide-details
                    class="search-field"
                    prepend-inner-icon="mdi-magnify"
                  />
                </div>
              </div>

              <PatientDataTable
                :items="allPatientsForStage"
                v-model:selected-status="selectedStatus"
                v-model:search-query="searchQuery"
                v-model:selected-fast-track="selectedFastTrack"
                :di-loket-count="filteredDiLoketCount"
                :diproses-count="currentProcessingPatient ? 1 : 0"
                :anjungan-count="filteredAnjunganCount"
                :terlambat-count="filteredTerlambatCount"
                :pending-count="filteredPendingCount"
                :show-diproses="false"
                :fast-track-options="fastTrackOptions"
                @action="handleTableAction"
              />
            </v-card-text>
          </v-card>
        </v-col>
      </v-row>

      <!-- Klinik Dialog -->
      <SelectionDialog
        v-model="showKlinikDialog"
        title="Pilih Klinik"
        :items="filteredKliniks"
        v-model:search-query="klinikSearch"
        search-placeholder="Cari klinik..."
        @select="selectKlinik"
      />

      <!-- Penunjang Dialog -->
      <SelectionDialog
        v-model="showPenunjangDialog"
        title="Pilih Penunjang"
        :items="filteredPenunjangs"
        v-model:search-query="penunjangSearch"
        search-placeholder="Cari penunjang..."
        @select="selectPenunjang"
      />

      <!-- Change Klinik Dialog -->
      <SelectionDialog
        v-model="showChangeKlinikDialog"
        title="Ubah Klinik"
        :items="filteredChangeKliniks"
        v-model:search-query="changeKlinikSearch"
        search-placeholder="Cari klinik..."
        @select="changeKlinik"
      />

      <!-- Dialog Klinik Ruang -->
      <v-dialog v-model="showKlinikRuangDialog" max-width="900px" scrollable>
        <v-card class="dialog-card">
          <v-card-title class="dialog-header dialog-header-warning">
            <span class="headline-4">Pilih Klinik Ruang</span>
            <v-btn icon variant="text" size="small" class="btn-close" @click="closeKlinikRuangDialog">
              <v-icon>mdi-close</v-icon>
            </v-btn>
          </v-card-title>

          <v-divider/>

          <v-card-text class="dialog-content">
            <div v-if="currentProcessingPatient" class="patient-card mb-4">
              <h4 class="headline-5 mb-3">Informasi Pasien</h4>
              <v-row dense>
                <v-col cols="6">
                  <div class="detail-item">
                    <span class="caption-2 text-muted">Barcode</span>
                    <span class="body-2 text-semibold">{{ currentProcessingPatient.barcode }}</span>
                  </div>
                </v-col>
                <v-col cols="6">
                  <div class="detail-item">
                    <span class="caption-2 text-muted">No. Antrian</span>
                    <span class="body-2 text-semibold">{{ currentProcessingPatient.noAntrian }}</span>
                  </div>
                </v-col>
              </v-row>
            </div>

            <v-text-field
              v-model="klinikRuangSearch"
              placeholder="Cari Klinik Ruang..."
              prepend-inner-icon="mdi-magnify"
              variant="outlined"
              density="compact"
              hide-details
              class="mb-4"
            />

            <v-expansion-panels class="expansion-panels">
              <v-expansion-panel
                v-for="klinikRuang in filteredKlinikRuang"
                :key="klinikRuang.id"
                class="expansion-panel"
              >
                <v-expansion-panel-title class="expansion-title">
                  <div class="expansion-header">
                    <v-chip size="small" color="warning" class="mr-2">
                      {{ klinikRuang.kodeKlinik }}
                    </v-chip>
                    <span class="body-2 text-semibold">{{ klinikRuang.namaKlinik }}</span>
                  </div>
                  <template #actions>
                    <v-chip size="x-small" variant="outlined">
                      {{ klinikRuang.ruangList.length }} Ruang
                    </v-chip>
                  </template>
                </v-expansion-panel-title>

                <v-expansion-panel-text>
                  <div class="ruang-card-grid">
                    <div
                      v-for="ruang in klinikRuang.ruangList"
                      :key="ruang.nomorRuang"
                      class="ruang-card-item"
                      @click="buatAntreanKlinikRuang(klinikRuang, ruang)"
                    >
                      <v-icon color="warning" size="24" class="mb-2">mdi-door</v-icon>
                      <div class="ruang-card-name">Ruang {{ ruang.nomorRuang }}</div>
                    </div>
                  </div>
                </v-expansion-panel-text>
              </v-expansion-panel>
            </v-expansion-panels>
          </v-card-text>
        </v-card>
      </v-dialog>

      <!-- Snackbar -->
      <AppSnackbar
        v-model="snackbar"
        :message="snackbarText"
        :color="snackbarColor"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useQueue } from "@/composables/useQueue";
import { useQueueStore } from "@/stores/queueStore";
import { useMasterStore } from "@/stores/masterStore";
import { useLoketStore } from "@/stores/loketStore";
import { useClinicStore } from "@/stores/clinicStore";
import PageHeader from "@/components/common/PageHeader.vue";
import CurrentPatientCard from "@/components/features/queue/CurrentPatientCard.vue";
import QueueActionsCard from "@/components/features/queue/QueueActionsCard.vue";
import PatientDataTable from "@/components/features/queue/TabelPatientData.vue";
import SelectionDialog from "@/components/common/SelectionDialog.vue";
import AppSnackbar from "@/components/common/AppSnackbar.vue";
import { useThermalPrint } from "@/composables/useThermalPrint";

const route = useRoute();
const router = useRouter();
const masterStore = useMasterStore();
const queueStore = useQueueStore();
const loketStore = useLoketStore();
const clinicStore = useClinicStore();
const { printTicketFromPatient } = useThermalPrint();

// Broadcast Channel
let broadcastChannel = null;
let resetCheckInterval = null;

const loketId = computed(() => route.params.id);
const loketName = computed(() => {
  const loket = loketStore.getLoketById(parseInt(loketId.value));
  return loket ? loket.namaLoket : 'Loket';
});

const {
  snackbar,
  snackbarText,
  snackbarColor,
  showKlinikDialog,
  showPenunjangDialog,
  showChangeKlinikDialog,
  klinikSearch,
  penunjangSearch,
  changeKlinikSearch,
  currentProcessingPatient,
  diLoketPatients,
  terlambatPatients,
  pendingPatients,
  anjunganPatients,
  menungguPatients,
  nextPatient,
  menungguCount,
  quotaUsed,
  filteredKliniks,
  filteredPenunjangs,
  filteredChangeKliniks,
  callNext,
  callMultiplePatients,
  processPatient,
  selectKlinik,
  selectPenunjang,
  openPenunjangDialog,
  changeKlinik,
  processNextQueue,
} = useQueue("loket", loketId);

// PERSISTENCE FIX: Ensure data exists on mount
onMounted(async () => {
  await nextTick();
  queueStore.ensureInitialData();

  // 1. Ensure CLINIC data is loaded first (critical for mapping codes like "25" -> "MT")
  // Check if we need to fetch reguler clinics (e.g. if we only have local exec clinics)
  const hasRegulerClinics = clinicStore.clinics.some(c => c.jenisLayanan === 'Reguler');
  if (!hasRegulerClinics) {
      console.log('AdminLoket: Fetching reguler clinics...');
      await clinicStore.fetchRegulerClinics();
  }
  
  // 2. Ensure LOKET data is loaded next (needs clinic data for mapping)
  // Fix: Don't just check length (which might include local exec data). Check for API data (id < 1000)
  const hasRegularLokets = loketStore.lokets.some(l => l.id < 1000);
  const targetId = parseInt(loketId.value);
  const currentLoketExists = loketStore.getLoketById(targetId);

  if (!hasRegularLokets || !currentLoketExists) {
     console.log('AdminLoket: Fetching lokets (missing regular data or specific loket)...');
     await loketStore.fetchLoketFromAPI();
  }
  
  // 3. Fetch specific quota/loket data from API to ensure fresh counts
  // This matches MasterLoket.vue implementation
  await fetchQuotaFromAPI();

  // 4. Fetch patient data for this loket
  await fetchPatientsForCurrentLoket();

  // 5. Periodic check for daily reset (2 AM)
  resetCheckInterval = setInterval(() => {
    const didReset = queueStore.checkAndResetDaily();
    if (didReset) {
      console.log('🕒 [AdminLoket] 2 AM threshold reached. Data reset performed.');
      fetchPatientsForCurrentLoket(); // Refresh after reset
    }
  }, 60000); // Check every minute
});

onUnmounted(() => {
  if (resetCheckInterval) clearInterval(resetCheckInterval);
});

const apiQuota = ref(null);

// Fetch latest quota data specifically for this loket
const fetchQuotaFromAPI = async () => {
  try {
    const response = await fetch('http://10.10.150.131:8089/api/v1/klinik/loket');
    const data = await response.json();
    
    if (data && data.metadata && data.metadata.code === 200) {
      // Find our specific loket
      const targetId = parseInt(loketId.value);
      const loketData = data.response.find(l => l.loketid === targetId);
      
      if (loketData) {
        // Update local quota state
        apiQuota.value = loketData.kuota;
        console.log(`✅ [AdminLoket] API Quota Refreshed for Loket ${targetId}:`, apiQuota.value);
      }
    }
  } catch (error) {
    console.error('Error fetching fresh quota:', error);
  }
};

// Fetch patient data for current loket
const fetchPatientsForCurrentLoket = async () => {
  const targetId = parseInt(loketId.value);
  const currentLoket = loketStore.getLoketById(targetId);
  
  // Check if loket is REGULER (not EKSEKUTIF)
  const isEksekutif = currentLoket?.tipeloket === 'EKSEKUTIF' || 
                      currentLoket?.tipeLoket === 'EKSEKUTIF' ||
                      (currentLoket?.namaLoket || '').toUpperCase().includes('EKSEKUTIF');
  
  if (!isEksekutif) {
    // For REGULER loket, fetch from API
    console.log(`🔄 [AdminLoket] Fetching patients for REGULER loket ${targetId}...`);
    await queueStore.fetchPatientsForLoket(targetId);
  } else {
    console.log(`📋 [AdminLoket] Using seed data for EKSEKUTIF loket ${targetId}`);
  }
};

const currentDate = ref(
  new Date().toLocaleDateString("id-ID", {
    weekday: "long",
    day: "numeric",
    month: "long",
    year: "numeric",
  })
);

const selectedStatus = ref("all");
const searchQuery = ref("");
const selectedFastTrack = ref(null);

// Dialog Klinik Ruang
const showKlinikRuangDialog = ref(false);
const klinikRuangSearch = ref("");

// Watch dialog state to reset search when closed
watch(showKlinikRuangDialog, (newValue) => {
  if (!newValue) {
    klinikRuangSearch.value = "";
  }
});

// Get klinik ruang data from masterStore
const klinikRuangList = computed(() => {
  return masterStore.ruangData || [];
});

const filteredKlinikRuang = computed(() => {
  if (!klinikRuangSearch.value) return klinikRuangList.value;
  return klinikRuangList.value.filter(
    (k) =>
      k.namaKlinik.toLowerCase().includes(klinikRuangSearch.value.toLowerCase()) ||
      k.kodeKlinik.toLowerCase().includes(klinikRuangSearch.value.toLowerCase())
  );
});

// Fast Track options from all patients
const fastTrackOptions = computed(() => {
  const normalizedValues = allPatientsForStage.value
    .map((p) => (p.fastTrack ?? "").toString().trim().toUpperCase())
    .filter((v) => v.length > 0);
  const uniqueTracks = [...new Set(normalizedValues)];
  return uniqueTracks.sort();
});

// Loket quota from configuration
const loketQuota = computed(() => {
  const currentLoket = loketStore.getLoketById(parseInt(loketId.value));
  return currentLoket?.kuota || apiQuota.value || 150;
});

// Combine all patients with status - PRESERVE ALL PROPERTIES
const allPatientsForStage = computed(() => {
  const currentPatientNo = currentProcessingPatient.value?.no;
  const targetLoketId = loketId.value;
  const currentLoket = loketStore.getLoketById(parseInt(targetLoketId));
  
  // Check if loket is EKSEKUTIF or REGULER
  const isLoketEksekutif = currentLoket?.tipeloket === 'EKSEKUTIF' || 
                           currentLoket?.tipeLoket === 'EKSEKUTIF' ||
                           (currentLoket?.namaLoket || '').toUpperCase().includes('EKSEKUTIF');
  
  let basePatients = [];
  
  if (isLoketEksekutif) {
    // For EKSEKUTIF loket, use seed data (filter from allPatients)
    // IMPORTANT: Do NOT include menungguPatients - they are only called via QueueActionsCard
    basePatients = diLoketPatients.value.concat(anjunganPatients.value, terlambatPatients.value, pendingPatients.value);
  } else {
    // For REGULER loket, use API data from allPatients (which is reactive)
    // Filter patients that belong to this loket and are from API
    const apiPatients = queueStore.allPatients.filter(p => 
      p.registrationType === 'api' && 
      p.processStage === 'loket' &&
      String(p.loketId) === String(targetLoketId)
    );
    basePatients = apiPatients;
  }
  
  // Helper to check if patient belongs to this loket (for seed data only)
  const isPatientForThisLoket = (p) => {
    // Only check for EKSEKUTIF patients (seed data)
    const isPatientEksekutif = (p.pembayaran || '').toUpperCase().includes('EKSEKUTIF') || 
                                (p.pembayaran || '').toUpperCase().includes('VIP');

    if (isLoketEksekutif) {
      // Loket Eksekutif HANYA melayani pasien Eksekutif
      if (!isPatientEksekutif) return false;
      
      // For EKSEKUTIF loket: accept all EKSEKUTIF patients
      // EKSEKUTIF lokets typically serve ALL clinics for executive patients
      // So we don't need to check kodeKlinik matching
      // Only check explicit loketId assignment if present
      if (p.loketId) {
        return String(p.loketId) === String(targetLoketId);
      }
      
      // If no loketId assigned, accept all EKSEKUTIF patients
      return true;
    } else {
      // Loket Reguler TIDAK melayani pasien Eksekutif (this shouldn't happen with API data)
      if (isPatientEksekutif) return false;
    }

    // For REGULER seed data only: check loket assignment
    // Priority 1: Explicit loketId match
    if (p.loketId) {
      return String(p.loketId) === String(targetLoketId);
    }
    
    // Priority 2: Service (kodeKlinik) match
    const allowedServices = currentLoket?.pelayanan || [];
    if (p.kodeKlinik) {
      return allowedServices.includes(p.kodeKlinik);
    }
    
    // Priority 3: Fallback for seed/legacy data (Match by clinic name)
    if (p.klinik && currentLoket) {
      const normalizedKlinik = p.klinik.trim().toUpperCase();
      // Check if any allowed service matches this clinic name in _spesialisDetail
      const matchByDetail = (currentLoket._spesialisDetail || []).some(s => 
        s.namaklinik && s.namaklinik.trim().toUpperCase() === normalizedKlinik
      );
      if (matchByDetail) return true;
    }
    
    return false;
  };
  
  // If using seed data (EKSEKUTIF), filter by loket
  // If using API data (REGULER), basePatients already contains only relevant patients
  let combined = [];
  
  if (isLoketEksekutif) {
    // Filter seed data by loket assignment
    const diLoket = (diLoketPatients.value || [])
      .filter(isPatientForThisLoket)
      .map((p) => ({
        ...p,
        status: p.no === currentPatientNo ? "diproses" : "di-loket",
      }));
    
    const terlambat = (terlambatPatients.value || [])
      .filter(isPatientForThisLoket)
      .map((p) => ({
        ...p,
        status: "terlambat",
      }));
    
    const pending = (pendingPatients.value || [])
      .filter(isPatientForThisLoket)
      .map((p) => ({
        ...p,
        status: "pending",
      }));
    
    const anjungan = (anjunganPatients.value || [])
      .filter(isPatientForThisLoket)
      .map((p) => ({
        ...p,
        status: "anjungan",
      }));

    combined = [...diLoket, ...anjungan, ...terlambat, ...pending];
  } else {
    // Use API data, but EXCLUDE patients with status "menunggu"
    // They should only be called via QueueActionsCard, not displayed in table
    combined = basePatients
      .filter(p => p.status !== 'menunggu')  // IMPORTANT: Filter out menunggu
      .map((p) => ({
        ...p,
        status: p.no === currentPatientNo ? "diproses" : (p.status || "menunggu"),
      }));
  }
  
  return combined;
});

// Computed status counts based on filtered allPatientsForStage
// These counts are ONLY for patients that belong to this specific loket
const filteredAnjunganCount = computed(() => {
  return allPatientsForStage.value.filter(p => p.status === 'anjungan').length;
});

const filteredDiLoketCount = computed(() => {
  return allPatientsForStage.value.filter(p => p.status === 'di-loket').length;
});

const filteredTerlambatCount = computed(() => {
  return allPatientsForStage.value.filter(p => p.status === 'terlambat').length;
});

const filteredPendingCount = computed(() => {
  return allPatientsForStage.value.filter(p => p.status === 'pending').length;
});

// Menunggu count from API or seed data based on loket type
const filteredMenungguCount = computed(() => {
  const targetLoketId = loketId.value;
  const currentLoket = loketStore.getLoketById(parseInt(targetLoketId));
  
  const isLoketEksekutif = currentLoket?.tipeloket === 'EKSEKUTIF' || 
                           currentLoket?.tipeLoket === 'EKSEKUTIF' ||
                           (currentLoket?.namaLoket || '').toUpperCase().includes('EKSEKUTIF');
  
  if (isLoketEksekutif) {
    // For EKSEKUTIF, use seed data menunggu count (filtered by loket)
    return menungguPatients.value.filter(p => {
      const isPatientEksekutif = (p.pembayaran || '').toUpperCase().includes('EKSEKUTIF') || 
                                  (p.pembayaran || '').toUpperCase().includes('VIP');
      if (!isPatientEksekutif) return false;
      
      // Accept all EKSEKUTIF patients if no explicit loketId
      if (p.loketId) {
        return String(p.loketId) === String(targetLoketId);
      }
      return true;
    }).length;
  } else {
    // For REGULER, count from allPatients (reactive) not apiPatientsPerLoket (snapshot)
    const apiPatients = queueStore.allPatients.filter(p =>
      p.registrationType === 'api' &&
      p.processStage === 'loket' &&
      String(p.loketId) === String(targetLoketId)
    );
    return apiPatients.filter(p => p.status === 'menunggu').length;
  }
});

const anjunganCount = computed(() => {
  return (anjunganPatients.value || []).length;
});

const nextQueueInfo = computed(() => {
  const currentPatientNo = currentProcessingPatient.value?.no;
  const nextPatient = (diLoketPatients.value || []).find(p => p.no !== currentPatientNo) || (diLoketPatients.value || [])[0];
  if (nextPatient) {
    return `Antrian berikutnya: ${nextPatient.noAntrian.split(" |")[0]}`;
  }
  return null;
});

const handlePatientAction = (action) => {
  if (currentProcessingPatient.value) {
    processPatient(currentProcessingPatient.value, action);
  }
};

const handleCall = async (count) => {
  if (count === 1) {
    callNext(loketId.value);
  } else {
    callMultiplePatients(count, loketId.value);
  }
  // Force Vue to process reactivity updates
  await nextTick();
};

const handleTableAction = (item, action) => {
  processPatient(item, action);
};

const handleProcessNext = () => {
  processNextQueue();
};

const handleCallPatient = () => {
  if (currentProcessingPatient.value) {
    const result = queueStore.callProcessingPatient('loket', loketId.value);
    if (result.success) {
      snackbarText.value = result.message;
      snackbarColor.value = "success";
      snackbar.value = true;
      
      // BROADCAST CALL EVENT
      if (broadcastChannel) {
        broadcastChannel.postMessage({
          type: 'CALL_PATIENT',
          patient: JSON.parse(JSON.stringify(currentProcessingPatient.value)),
          loketId: loketId.value,
          loketName: loketName.value
        });
      }
    } else {
      snackbarText.value = result.message;
      snackbarColor.value = "error";
      snackbar.value = true;
    }
  }
};

const openKlinikRuangDialog = () => {
  showKlinikRuangDialog.value = true;
};

// Calculate sticky top offset based on header height
const stickyTopOffset = ref(100);

const updateStickyOffset = () => {
  const header = document.querySelector('.page-header');
  if (header) {
    const headerHeight = header.offsetHeight;
    const containerPadding = 16;
    stickyTopOffset.value = headerHeight + containerPadding + 8;
  }
};

onMounted(() => {
  updateStickyOffset();
  window.addEventListener('resize', updateStickyOffset);
  setTimeout(updateStickyOffset, 100);
  
  // Initialize Broadcast Channel
  broadcastChannel = new BroadcastChannel('antrian-loket-channel');

  // Ensure initial data is loaded if store is empty (after hydration)
  setTimeout(() => {
    queueStore.ensureInitialData();
  }, 200);
});

onUnmounted(() => {
  window.removeEventListener('resize', updateStickyOffset);
  if (broadcastChannel) {
    broadcastChannel.close();
  }
});

const closeKlinikRuangDialog = () => {
  showKlinikRuangDialog.value = false;
  klinikRuangSearch.value = "";
};

const buatAntreanKlinikRuang = async (klinikRuang, ruang) => {
  let patient = currentProcessingPatient.value;
  // ... (keeping existing logic to find patient)
  if (!patient) {
     // ... fallback logic as in original file
     // simplified for brevity in this manual copy, but we should keep original robustness
      try {
        const processingPatient = queueStore.currentProcessingPatient?.loket;
        if (processingPatient) {
          let allPatients = [];
          if (queueStore.allPatients) {
            allPatients = Array.isArray(queueStore.allPatients) 
              ? queueStore.allPatients 
              : (queueStore.allPatients.value || []);
          }
          const latestPatient = allPatients.find(
            p => (p && p.no === processingPatient.no) || 
                 (p && p.barcode && p.barcode === processingPatient.barcode) ||
                 (p && p.noAntrian && p.noAntrian === processingPatient.noAntrian)
          );
          patient = latestPatient || processingPatient;
        }
      } catch (error) {
        console.error('Error getting patient from store:', error);
      }
  }
  
  if (!patient) {
    snackbarText.value = "Tidak ada pasien yang sedang diproses";
    snackbarColor.value = "error";
    snackbar.value = true;
    closeKlinikRuangDialog();
    return;
  }
  
  const result = queueStore.createAntreanKlinikRuang(
    klinikRuang,
    ruang,
    patient,
    "loket"
  );
  
  if (result.success && result.patient) {
    try {
      await printTicketFromPatient(result.patient);
    } catch (error) {
      console.error('Error printing ticket:', error);
      snackbarText.value = `${result.message}. Gagal print tiket.`;
      snackbarColor.value = "warning";
      snackbar.value = true;
      closeKlinikRuangDialog();
      return;
    }
  }
  
  snackbarText.value = result.message;
  snackbarColor.value = result.success ? "success" : "error";
  snackbar.value = true;
  
  closeKlinikRuangDialog();
};
</script>

<style scoped lang="scss">
.loket-container {
  background: var(--color-neutral-300);
  min-height: 100vh;
  padding: 16px;
  width: 100%;
  max-width: 100vw;
  box-sizing: border-box;
  border-radius: 0 !important;
}

/* Remove rounded edges from PageHeader component */
:deep(.page-header) {
  border-radius: 0 !important;
}

.content-grid {
  margin: 0 -8px;
}

.content-grid > .v-col {
  padding: 8px;
}

.content-grid > .v-col:first-child {
  padding-left: 0;
}

.content-grid > .v-col:last-child {
  padding-right: 0;
}

.sticky-wrapper {
  position: -webkit-sticky; /* Safari */
  position: sticky;
  top: 16px;
  z-index: 10;
}

.filters {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.status-filter {
  flex: 1;
  min-width: 300px;
}

.status-filter .v-chip {
  font-size: 12px;
  font-weight: 600;
  height: 32px;
  border: 1px solid var(--color-neutral-500);
  background: var(--color-neutral-100);
  color: var(--color-neutral-600);
  transition: all 0.2s ease;
}

.status-filter .v-chip:hover {
  background: var(--color-neutral-300);
}

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

.search-field {
  max-width: 300px;
  min-width: 250px;
}

.section-label {
  font-size: 11px;
  font-weight: 700;
  letter-spacing: 0.5px;
  color: var(--color-neutral-600);
  text-transform: uppercase;
}

.waiting-badge {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  background: var(--color-warning-100);
  color: var(--color-warning-700);
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 13px;
  font-weight: 600;
  border: 1px solid var(--color-warning-300);
}

.data-header {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

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

/* Dialog Klinik Ruang Styles */
.dialog-card {
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}

.dialog-header {
  background: linear-gradient(135deg, var(--color-primary-600) 0%, var(--color-primary-700) 100%);
  color: var(--color-neutral-100);
  padding: 20px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-header-warning {
  background: linear-gradient(135deg, var(--color-primary-600) 0%, var(--color-primary-700) 100%);
}

.headline-4 {
  font-size: 20px;
  line-height: 28px;
  font-weight: 600;
  margin: 0;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}

.headline-5 {
  font-size: 18px;
  line-height: 24px;
  font-weight: 600;
  margin: 0;
  color: var(--color-neutral-900);
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}

.btn-close {
  color: var(--color-neutral-100) !important;
  transition: all 0.2s ease;
}

.btn-close:hover {
  background: rgba(255, 255, 255, 0.2) !important;
  transform: rotate(90deg);
}

.dialog-content {
  padding: 24px !important;
  background: var(--color-neutral-300);
}

.dialog-actions {
  padding: 16px 24px;
  background: var(--color-neutral-300);
}

.dialog-actions .v-btn {
  text-transform: none;
  font-weight: 600;
  font-size: 16px;
  line-height: 24px;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
  min-width: 100px;
}

.btn-cancel {
  border-color: var(--color-neutral-600) !important;
  color: var(--color-neutral-800) !important;
}

.btn-submit {
  background-color: var(--color-secondary-600) !important;
  color: var(--color-neutral-100) !important;
}

.patient-card {
  background: var(--color-neutral-100);
  border-radius: 12px;
  padding: 20px;
  border: 1px solid var(--color-neutral-400);
}

.detail-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.caption-2 {
  font-size: 12px;
  line-height: 16px;
  font-weight: 400;
}

.body-2 {
  font-size: 16px;
  line-height: 24px;
  font-weight: 400;
}

.body-3 {
  font-size: 14px;
  line-height: 20px;
  font-weight: 400;
}

.text-semibold {
  font-weight: 600 !important;
}

.text-muted {
  color: var(--color-neutral-700);
  line-height: 16px;
}

.expansion-panels {
  background: transparent;
}

.expansion-panel {
  background: var(--color-neutral-100);
  border: 1px solid var(--color-neutral-400);
  border-radius: 12px !important;
  margin-bottom: 12px;
  overflow: hidden;
}

.expansion-panel::before {
  box-shadow: none !important;
}

.expansion-title {
  background: var(--color-neutral-100);
  min-height: 60px;
}

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

.ruang-card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  gap: 12px;
  padding: 8px 0;
}

.ruang-card-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 12px 8px;
  background: var(--color-neutral-100);
  border: 1px solid var(--color-neutral-400);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  text-align: center;
  min-height: 80px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.ruang-card-item:hover {
  border-color: var(--color-warning-600);
  background: var(--color-neutral-200);
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.ruang-card-item:active {
  transform: translateY(0);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.ruang-card-name {
  font-size: 14px;
  line-height: 20px;
  font-weight: 600;
  color: var(--color-neutral-900);
  margin-bottom: 4px;
}

.ruang-card-detail {
  font-size: 12px;
  line-height: 16px;
  color: var(--color-neutral-700);
  margin-bottom: 4px;
}

.ruang-card-screen {
  font-size: 11px;
  line-height: 14px;
  color: var(--color-neutral-600);
}
</style>
