<template>
  <div>
    <PageHeader
      icon="mdi-door-open"
      title="Admin Klinik Ruang"
      subtitle="Pilih Klinik untuk mengelola antrian ruang"
      :show-add-button="false"
      theme="primary"
    />

    <div class="admin-klinik-ruang-index">
      <div v-if="klinikRuangList.length > 0" class="klinik-grid">
        <div
          v-for="klinikRuang in klinikRuangList"
          :key="`${klinikRuang.kodeKlinik}-${klinikRuang.jenisLayanan}`"
          class="klinik-card"
          @click="navigateToKlinik(klinikRuang.kodeKlinik, klinikRuang.jenisLayanan)"
        >
          <div class="klinik-card-header">
            <div class="klinik-info">
              <h3 class="klinik-name">{{ klinikRuang.namaKlinik }}</h3>
              <div class="klinik-details">
                <v-chip 
                  size="x-small" 
                  :class="klinikRuang.jenisLayanan === 'Reguler' ? 'chip-reguler' : 'chip-eksekutif'"
                >
                  {{ klinikRuang.jenisLayanan }}
                </v-chip>
                <span class="kode-chip">{{ klinikRuang.kodeKlinik }}</span>
              </div>
            </div>
          </div>
          
          <div class="klinik-preview">
            <div class="klinik-room-count">
              <v-icon size="18" color="primary-600">mdi-door</v-icon>
              <span>{{ klinikRuang.ruangList.length }} Ruang</span>
            </div>
            <div class="klinik-tags">
              <v-chip
                v-for="(ruang, idx) in klinikRuang.ruangList.slice(0, 3)"
                :key="idx"
                size="small"
                class="ma-1 chip-preview"
              >
                {{ ruang.namaRuang }}
              </v-chip>
              <v-chip
                v-if="klinikRuang.ruangList.length > 3"
                size="small"
                class="ma-1 chip-more"
              >
                +{{ klinikRuang.ruangList.length - 3 }}
              </v-chip>
            </div>
          </div>

          <!-- <div class="klinik-card-footer">
            <v-btn
              color="primary-600"
              variant="flat"
              size="large"
              block
              class="btn-view text-white"
            >
              <v-icon left>mdi-clipboard-list</v-icon>
              Kelola Antrian
            </v-btn>
          </div> -->
        </div>
      </div>

      <div v-else class="empty-state">
        <v-icon size="64" color="grey-lighten-1">mdi-hospital-building-outline</v-icon>
        <h3>Tidak Ada Klinik Ruang Tersedia</h3>
        <p>Silakan tambah klinik ruang terlebih dahulu di halaman master</p>
        <v-btn
          color="primary-600"
          variant="flat"
          class="mt-4"
          @click="navigateToSettings"
        >
          <v-icon left>mdi-cog</v-icon>
          Ke Halaman Master
        </v-btn>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useMasterStore } from '@/stores/masterStore';
import { useClinicStore } from '@/stores/clinicStore';
import { useRuangStore } from '@/stores/ruangStore';
import PageHeader from '@/components/common/PageHeader.vue';

const router = useRouter();
const masterStore = useMasterStore();
const clinicStore = useClinicStore();
const ruangStore = useRuangStore();

const loading = ref(false);

const klinikRuangList = computed(() => {
  return masterStore.ruangData || [];
});

const navigateToKlinik = (kodeKlinik, jenisLayanan) => {
  // Include jenisLayanan as query parameter to differentiate same clinic code with different service types
  router.push({
    path: `/adminklinikruang/${kodeKlinik}`,
    query: { jenisLayanan }
  });
};

const navigateToSettings = () => {
  router.push('/setting/masterklinikruang');
};

// Generate rooms from clinics based on spesialis field (same logic as MasterKlinikRuang)
const generateRoomsFromClinics = () => {
  console.log('🔄 AdminKlinikRuang/index - Generating rooms from clinics...');
  const allRooms = [];
  let roomIdCounter = 1;
  
  const allClinics = clinicStore.clinics;
  console.log('📊 Total clinics:', allClinics.length);
  
  allClinics.forEach(clinic => {
    if (clinic.jenisLayanan === 'Reguler') {
      if (clinic.spesialis && Array.isArray(clinic.spesialis) && clinic.spesialis.length > 0) {
        // Create room ONLY for each specialist (no duplicate clinic-name room)
        clinic.spesialis.forEach((spec, index) => {
          allRooms.push({
            id: roomIdCounter++,
            kodeKlinik: clinic.kode,
            namaKlinik: clinic.name,
            kodeRuang: `${clinic.kode}-${spec.idspesialis}`,
            namaRuang: spec.Spesialis,
            nomorRuang: (index + 1).toString(),
            nomorScreen: `${clinic.kode}${index + 1}`,
            jenisLayanan: 'Reguler'
          });
        });
      } else {
        // Only create 1 room with clinic name when NO spesialis
        allRooms.push({
          id: roomIdCounter++,
          kodeKlinik: clinic.kode,
          namaKlinik: clinic.name,
          kodeRuang: clinic.kode,
          namaRuang: clinic.name,
          nomorRuang: '1',
          nomorScreen: `${clinic.kode}1`,
          jenisLayanan: 'Reguler'
        });
      }
    } else if (clinic.jenisLayanan === 'Eksekutif') {
      // For Eksekutif: always 1 room (no spesialis in seed data)
      allRooms.push({
        id: roomIdCounter++,
        kodeKlinik: clinic.kode,
        namaKlinik: clinic.name,
        kodeRuang: clinic.kode,
        namaRuang: clinic.name,
        nomorRuang: '1',
        nomorScreen: `${clinic.kode}1`,
        jenisLayanan: 'Eksekutif'
      });
    }
  });
  
  console.log(`✅ Generated ${allRooms.length} rooms from ${allClinics.length} clinics`);
  
  // Update ruangStore with generated rooms
  const result = ruangStore.replaceAllRooms(allRooms);
  console.log('💾 Rooms saved to ruangStore:', result.message);
  
  return result;
};

// Load data on mount (same as MasterKlinikRuang)
onMounted(async () => {
  console.log('🚀 AdminKlinikRuang/index mounted, loading data...');
  loading.value = true;
  
  try {
    // Fetch clinics from API (uses cache if available)
    const fetchResult = await clinicStore.fetchRegulerClinics();
    console.log('📥 Fetch result:', fetchResult);
    
    // Generate rooms based on fetched data
    generateRoomsFromClinics();
  } catch (error) {
    console.error('❌ Error loading data:', error);
  } finally {
    loading.value = false;
  }
});
</script>

<style scoped lang="scss">
.admin-klinik-ruang-index {
  background: var(--color-neutral-300);
  min-height: calc(100vh - 80px);
  padding: 16px;
  font-family: 'Inter', 'Roboto', sans-serif;
}

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

.klinik-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
  max-width: 1400px;
  margin: 0 auto;
}

.klinik-card {
  background: var(--color-neutral-100);
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border: 2px solid var(--color-neutral-400);
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  gap: 16px;

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 24px rgba(33, 150, 243, 0.2);
    border-color: var(--color-primary-600);
  }
}

.klinik-card-header {
  display: flex;
  align-items: center;
  gap: 16px;
  padding-bottom: 16px;
  border-bottom: 2px solid var(--color-neutral-400);
}

.klinik-info {
  flex: 1;
}

.klinik-name {
  font-size: 20px;
  font-weight: 700;
  margin: 0 0 8px 0;
  color: var(--color-neutral-900);
  line-height: 1.2;
}

.klinik-details {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 4px;
}

.chip-reguler {
  background-color: var(--color-primary-600) !important;
  color: var(--color-neutral-100) !important;
  font-weight: 600;
  font-size: 11px;
}

.chip-eksekutif {
  background-color: var(--color-secondary-600) !important;
  color: var(--color-neutral-100) !important;
  font-weight: 600;
  font-size: 11px;
}

.kode-chip {
  font-size: 12px;
  font-weight: 600;
  color: var(--color-neutral-700);
  background: var(--color-neutral-400);
  padding: 2px 8px;
  border-radius: 4px;
}

.klinik-preview {
  flex: 1;
}

.klinik-room-count {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 600;
  color: var(--color-primary-600);
  margin-bottom: 12px;
}

.klinik-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.chip-preview {
  background-color: var(--color-primary-600) !important;
  color: var(--color-neutral-100) !important;
  font-weight: 500;
  font-size: 12px;
}

.chip-more {
  background-color: var(--color-neutral-600) !important;
  color: var(--color-neutral-100) !important;
  font-weight: 600;
  font-size: 12px;
}

.klinik-card-footer {
  margin-top: auto;
}

.btn-view {
  font-weight: 600;
  text-transform: none;
  letter-spacing: 0.5px;
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  color: var(--color-neutral-700);

  h3 {
    font-size: 24px;
    font-weight: 700;
    margin: 24px 0 8px 0;
    color: var(--color-neutral-800);
  }

  p {
    font-size: 16px;
    color: var(--color-neutral-600);
  }
}

@media (max-width: 768px) {
  .admin-klinik-ruang-index {
    padding: 12px;
  }

  .klinik-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
}
</style>

