<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-clipboard-plus</v-icon>
            </div>
            <div class="header-text">
              <h2 class="page-title">Buat Antrean</h2>
              <p class="page-subtitle">{{ currentDate }} - Manajemen Pembuatan Antrean</p>
            </div>
          </div>
          <v-chip color="white" variant="flat" class="stat-chip">
            <v-icon start size="20" color="primary">mdi-account-multiple</v-icon>
            <span class="text-semibold">{{ totalPasien }} Pasien</span>
          </v-chip>
        </div>
      </div>

      <!-- Filters & Search -->
      <v-card-text class="pa-4">
        <v-row dense class="mb-4">
          <v-col cols="12" md="8">
            <v-text-field
              v-model="search"
              placeholder="Cari nama pasien, No. RM, atau alamat..."
              prepend-inner-icon="mdi-magnify"
              variant="outlined"
              density="compact"
              hide-details
              class="search-field"
            />
          </v-col>
          <v-col cols="12" md="3">
            <v-select
              v-model="statusFilter"
              :items="['Semua Status', ...statusOptions]"
              variant="outlined"
              density="compact"
              hide-details
              class="filter-select"
            />
          </v-col>
          <v-col cols="12" md="1">
            <v-btn
              color="primary"
              variant="outlined"
              block
              :loading="loading"
              @click="refreshData"
            >
              <v-icon>mdi-refresh</v-icon>
            </v-btn>
          </v-col>
        </v-row>

        <!-- Data Table -->
        <v-data-table
          :headers="headers"
          :items="filteredPasien"
          :items-per-page="10"
          class="elevation-0 data-table"
        >
          <template #item.namaPasien="{ item }">
            <div class="patient-info">
              <div class="body-2 text-semibold">{{ item.namaPasien }}</div>
              <div class="caption-2 text-muted">{{ item.noRM }}</div>
            </div>
          </template>

          <template #item.status="{ item }">
            <v-chip
              :color="getStatusColor(item.status)"
              size="small"
              class="status-chip"
            >
              {{ item.status }}
            </v-chip>
          </template>

          <template #item.aksi="{ item }">
            <div class="action-buttons">
              <v-btn
                size="small"
                color="primary"
                variant="flat"
                class="btn-action mr-1"
                @click="openKlinikDialog(item)"
              >
                <v-icon size="16" left>mdi-hospital-box</v-icon>
                Klinik
              </v-btn>
              <v-btn
                size="small"
                color="warning"
                variant="flat"
                class="btn-action mr-1"
                @click="openKlinikRuangDialog(item)"
              >
                <v-icon size="16" left>mdi-door</v-icon>
                Ruang
              </v-btn>
              <v-btn
                size="small"
                color="#3b82f6"
                variant="flat"
                class="btn-action"
                @click="openPenunjangDialog(item)"
              >
                <v-icon size="16" left>mdi-clipboard-pulse</v-icon>
                Penunjang
              </v-btn>
            </div>
          </template>
        </v-data-table>
      </v-card-text>
    </v-card>

    <!-- Dialog Klinik -->
    <v-dialog v-model="showKlinikDialog" max-width="700px" persistent scrollable>
      <v-card class="dialog-card">
        <v-card-title class="dialog-header">
          <span class="headline-4">Pilih Klinik</span>
          <v-btn icon variant="text" size="small" class="btn-close" @click="closeKlinikDialog">
            <v-icon>mdi-close</v-icon>
          </v-btn>
        </v-card-title>

        <v-divider/>

        <v-card-text class="dialog-content">
          <div v-if="selectedPatient" 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">Nama</span>
                  <span class="body-2 text-semibold">{{ selectedPatient.namaPasien }}</span>
                </div>
              </v-col>
              <v-col cols="6">
                <div class="detail-item">
                  <span class="caption-2 text-muted">No. RM</span>
                  <span class="body-2 text-semibold">{{ selectedPatient.noRM }}</span>
                </div>
              </v-col>
            </v-row>
          </div>

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

          <v-row dense>
            <v-col
              v-for="klinik in filteredKliniks"
              :key="klinik.id"
              cols="6"
              sm="4"
            >
              <v-card
                class="option-card"
                elevation="0"
                @click="buatAntreanKlinik(klinik)"
              >
                <v-icon size="40" color="primary">mdi-hospital-box</v-icon>
                <span class="body-3 text-semibold text-center">{{ klinik.name }}</span>
              </v-card>
            </v-col>
          </v-row>
        </v-card-text>
      </v-card>
    </v-dialog>

    <!-- Dialog Klinik Ruang -->
    <v-dialog v-model="showKlinikRuangDialog" max-width="900px" persistent 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="selectedPatient" 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">Nama</span>
                  <span class="body-2 text-semibold">{{ selectedPatient.namaPasien }}</span>
                </div>
              </v-col>
              <v-col cols="6">
                <div class="detail-item">
                  <span class="caption-2 text-muted">No. RM</span>
                  <span class="body-2 text-semibold">{{ selectedPatient.noRM }}</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="primary" 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-list">
                  <div
                    v-for="ruang in klinikRuang.ruangList"
                    :key="ruang.nomorRuang"
                    class="ruang-item"
                    @click="buatAntreanKlinikRuang(klinikRuang, ruang)"
                  >
                    <v-icon color="warning" size="20">mdi-door</v-icon>
                    <div class="ruang-info">
                      <span class="body-3 text-semibold">Ruang {{ ruang.nomorRuang }} - {{ ruang.namaRuang }}</span>
                      <span class="caption-2 text-muted">Screen: {{ ruang.nomorScreen }}</span>
                    </div>
                    <v-icon size="20" color="grey">mdi-chevron-right</v-icon>
                  </div>
                </div>
              </v-expansion-panel-text>
            </v-expansion-panel>
          </v-expansion-panels>
        </v-card-text>
      </v-card>
    </v-dialog>

    <!-- Dialog Penunjang -->
    <v-dialog v-model="showPenunjangDialog" max-width="700px" persistent scrollable>
      <v-card class="dialog-card">
        <v-card-title class="dialog-header dialog-header-secondary">
          <span class="headline-4">Pilih Penunjang</span>
          <v-btn icon variant="text" size="small" class="btn-close" @click="closePenunjangDialog">
            <v-icon>mdi-close</v-icon>
          </v-btn>
        </v-card-title>

        <v-divider/>

        <v-card-text class="dialog-content">
          <div v-if="selectedPatient" 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">Nama</span>
                  <span class="body-2 text-semibold">{{ selectedPatient.namaPasien }}</span>
                </div>
              </v-col>
              <v-col cols="6">
                <div class="detail-item">
                  <span class="caption-2 text-muted">No. RM</span>
                  <span class="body-2 text-semibold">{{ selectedPatient.noRM }}</span>
                </div>
              </v-col>
            </v-row>
          </div>

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

          <v-row dense>
            <v-col
              v-for="penunjang in filteredPenunjangs"
              :key="penunjang.id"
              cols="6"
              sm="4"
            >
              <v-card
                class="option-card"
                elevation="0"
                @click="buatAntreanPenunjang(penunjang)"
              >
                <v-icon size="40" color="secondary">mdi-clipboard-pulse</v-icon>
                <span class="body-3 text-semibold text-center">{{ penunjang.name }}</span>
              </v-card>
            </v-col>
          </v-row>
        </v-card-text>
      </v-card>
    </v-dialog>

    <!-- Snackbar -->
    <v-snackbar v-model="snackbar" :color="snackbarColor" :timeout="3000" location="top right">
      <span class="body-3">{{ snackbarText }}</span>
      <template #actions>
        <v-btn variant="text" size="small" @click="snackbar = false">Tutup</v-btn>
      </template>
    </v-snackbar>
  </v-container>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useMasterStore } from '@/stores/masterStore';

const masterStore = useMasterStore();

// State
const loading = ref(false);
const search = ref('');
const statusFilter = ref('Semua Status');
const snackbar = ref(false);
const snackbarText = ref('');
const snackbarColor = ref('success');

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

// Dialog states
const showKlinikDialog = ref(false);
const showKlinikRuangDialog = ref(false);
const showPenunjangDialog = ref(false);
const selectedPatient = ref(null);

// Search states
const klinikSearch = ref('');
const klinikRuangSearch = ref('');
const penunjangSearch = ref('');

// Status options
const statusOptions = ref(['Terdaftar', 'Belum Terdaftar', 'Proses']);

// Table headers
const headers = ref([
  { title: 'Nama Pasien', value: 'namaPasien', sortable: true },
  { title: 'No. RM', value: 'noRM', sortable: true },
  { title: 'Alamat', value: 'alamat', sortable: true },
  { title: 'Status', value: 'status', sortable: true },
  { title: 'Aksi', value: 'aksi', sortable: false },
]);

// Mock data
const pasienList = ref([
  { id: 1, namaPasien: 'Ahmad Fauzi', noRM: '250811100163', alamat: 'Jl. Merdeka No. 123', status: 'Terdaftar' },
  { id: 2, namaPasien: 'Siti Aminah', noRM: '250811100155', alamat: 'Jl. Sudirman No. 45', status: 'Terdaftar' },
  { id: 3, namaPasien: 'Budi Santoso', noRM: '250811100200', alamat: 'Jl. Gatot Subroto No. 78', status: 'Belum Terdaftar' },
  { id: 4, namaPasien: 'Dewi Lestari', noRM: '250811100210', alamat: 'Jl. Ahmad Yani No. 90', status: 'Terdaftar' },
  { id: 5, namaPasien: 'Eko Prasetyo', noRM: '250811100220', alamat: 'Jl. Diponegoro No. 15', status: 'Proses' },
]);

// Computed - Get data from Master Store
const kliniksList = computed(() => {
  return masterStore.klinikList.map(k => ({
    id: k.id,
    name: k.nama,
    kode: k.kode
  }));
});

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

const penunjangsList = computed(() => {
  return masterStore.getActivePenunjangList();
});

const totalPasien = computed(() => pasienList.value.length);

const filteredPasien = computed(() => {
  let filtered = pasienList.value;

  if (statusFilter.value && statusFilter.value !== 'Semua Status') {
    filtered = filtered.filter((p) => p.status === statusFilter.value);
  }

  if (search.value) {
    const query = search.value.toLowerCase();
    filtered = filtered.filter(
      (p) =>
        p.namaPasien.toLowerCase().includes(query) ||
        p.noRM.toLowerCase().includes(query) ||
        p.alamat.toLowerCase().includes(query)
    );
  }

  return filtered;
});

const filteredKliniks = computed(() => {
  if (!klinikSearch.value) return kliniksList.value;
  return kliniksList.value.filter((k) =>
    k.name.toLowerCase().includes(klinikSearch.value.toLowerCase())
  );
});

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())
  );
});

const filteredPenunjangs = computed(() => {
  if (!penunjangSearch.value) return penunjangsList.value;
  return penunjangsList.value.filter((p) =>
    p.name.toLowerCase().includes(penunjangSearch.value.toLowerCase())
  );
});

// Methods
const showSnackbarMessage = (text, color = 'success') => {
  snackbarText.value = text;
  snackbarColor.value = color;
  snackbar.value = true;
};

const getStatusColor = (status) => {
  const colors = {
    Terdaftar: 'success',
    'Belum Terdaftar': 'warning',
    Proses: 'info',
  };
  return colors[status] || 'default';
};

const refreshData = () => {
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
    showSnackbarMessage('Data berhasil diperbarui', 'success');
  }, 1000);
};

const openKlinikDialog = (patient) => {
  selectedPatient.value = patient;
  showKlinikDialog.value = true;
};

const closeKlinikDialog = () => {
  showKlinikDialog.value = false;
  selectedPatient.value = null;
  klinikSearch.value = '';
};

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

const closeKlinikRuangDialog = () => {
  showKlinikRuangDialog.value = false;
  selectedPatient.value = null;
  klinikRuangSearch.value = '';
};

const openPenunjangDialog = (patient) => {
  selectedPatient.value = patient;
  showPenunjangDialog.value = true;
};

const closePenunjangDialog = () => {
  showPenunjangDialog.value = false;
  selectedPatient.value = null;
  penunjangSearch.value = '';
};

const buatAntreanKlinik = (klinik) => {
  showSnackbarMessage(
    `Antrean klinik ${klinik.name} untuk ${selectedPatient.value.namaPasien} berhasil dibuat`,
    'success'
  );
  closeKlinikDialog();
};

const buatAntreanKlinikRuang = (klinikRuang, ruang) => {
  showSnackbarMessage(
    `Antrean ${klinikRuang.namaKlinik} Ruang ${ruang.nomorRuang} untuk ${selectedPatient.value.namaPasien} berhasil dibuat`,
    'success'
  );
  closeKlinikRuangDialog();
};

const buatAntreanPenunjang = (penunjang) => {
  showSnackbarMessage(
    `Antrean penunjang ${penunjang.name} untuk ${selectedPatient.value.namaPasien} berhasil dibuat`,
    'success'
  );
  closePenunjangDialog();
};
</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;

$primary-700: #FF9B1B;
$primary-600: #FFA532;

$secondary-700: #0053AD;
$secondary-600: #0671E0;

$warning-600: #FFB95F;

$success-600: #009262;
$success-300: #84DFC1;

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

* {
  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;
}

.stat-chip {
  font-weight: $font-weight-semibold;
  color: $primary-600 !important;
}

// ============================================
// FILTERS & SEARCH
// ============================================
.search-field,
.filter-select {
  font-size: 14px;
  line-height: 20px;
}

// ============================================
// DATA TABLE
// ============================================
.data-table {
  font-family: $font-family-base;
}

.patient-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.text-muted {
  color: $neutral-700;
}

.status-chip {
  font-weight: $font-weight-semibold;
  font-size: 11px;
  text-transform: uppercase;
}

.action-buttons {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.btn-action {
  text-transform: none;
  font-weight: $font-weight-semibold;
  font-size: 12px;
}

// ============================================
// DIALOG
// ============================================
.dialog-card {
  font-family: $font-family-base;
}

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

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

.dialog-header-secondary {
  background: linear-gradient(135deg, $secondary-600 0%, $secondary-700 100%);
}

.headline-4 {
  font-size: 20px;
  line-height: 28px;
  font-weight: $font-weight-semibold;
  margin: 0;
}

.headline-5 {
  font-size: 18px;
  line-height: 24px;
  font-weight: $font-weight-semibold;
  margin: 0;
  color: $neutral-900;
}

.btn-close {
  color: $neutral-100 !important;
}

.dialog-content {
  padding: 24px !important;
  background: $neutral-300;
}

// ============================================
// PATIENT CARD
// ============================================
.patient-card {
  background: $neutral-100;
  border-radius: 12px;
  padding: 20px;
  border: 1px solid $neutral-400;
}

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

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

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

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

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

// ============================================
// OPTION CARDS
// ============================================
.option-card {
  cursor: pointer;
  border: 2px solid $neutral-400;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  transition: all 0.2s ease;
  background: $neutral-100;

  &:hover {
    border-color: $secondary-600;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(6, 113, 224, 0.15);
  }
}

// ============================================
// EXPANSION PANELS
// ============================================
.expansion-panels {
  background: transparent;
}

.expansion-panel {
  background: $neutral-100;
  border: 1px solid $neutral-400;
  border-radius: 12px !important;
  margin-bottom: 12px;
  overflow: hidden;

  &::before {
    box-shadow: none !important;
  }
}

.expansion-title {
  background: $neutral-100;
  min-height: 60px;
}

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

.ruang-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 8px 0;
}

.ruang-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background: $neutral-300;
  border: 1px solid $neutral-400;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover {
    border-color: $warning-600;
    background: lighten($warning-600, 35%);
  }
}

.ruang-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

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

  .action-buttons {
    flex-direction: column;
    width: 100%;

    .btn-action {
      width: 100%;
    }
  }
}
</style>