<template>
  <div>
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <div class="header-icon">
            <v-icon size="28" color="white">mdi-monitor-dashboard</v-icon>
          </div>
          <div class="header-text">
            <h2 class="page-title">Master Anjungan</h2>
            <p class="page-subtitle">Kelola anjungan dan klinik yang ditampilkan</p>
          </div>
        </div>
      </div>
    </div>

    <v-container>
      <!-- Action Bar -->
      <div class="action-bar mb-4">
        <v-spacer></v-spacer>
        <v-btn
          color="primary-600"
          variant="flat"
          @click="openTambahDialog"
          elevation="0"
          class="action-btn text-white"
        >
          <v-icon left size="20">mdi-plus-circle</v-icon>
          Tambah Anjungan
        </v-btn>
      </div>

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

          <template v-slot:item.jenisPasien="{ item }">
            <v-chip 
              size="small" 
              :class="item.jenisPasien === 'Reguler' ? 'chip-reguler' : 'chip-eksekutif'"
            >
              {{ item.jenisPasien }}
            </v-chip>
          </template>

          <template v-slot:item.klinik="{ item }">
            <div class="klinik-tags">
              <v-chip
                v-for="(kode, idx) in item.klinik.slice(0, 3)"
                :key="idx"
                size="small"
                class="mr-1 mb-1 chip-primary-outline"
              >
                {{ masterStore.getKlinikNameByKode(kode) }}
              </v-chip>
              <v-chip
                v-if="item.klinik.length > 3"
                size="small"
                class="chip-neutral"
              >
                +{{ item.klinik.length - 3 }}
              </v-chip>
            </div>
          </template>

          <template v-slot:item.layarInformasi="{ item }">
            <v-btn
              size="small"
              variant="outlined"
              color="primary-600"
              @click="openPreviewDialog(item)"
              class="btn-preview mr-2"
            >
              <v-icon size="16" left>mdi-eye</v-icon>
              Preview
            </v-btn>
          </template>

          <template v-slot:item.actions="{ item }">
            <v-btn
              size="small"
              variant="flat"
              color="warning-600"
              @click="openEditDialog(item)"
              class="btn-edit mr-2"
            >
              <v-icon size="16" left>mdi-cog</v-icon>
              Edit
            </v-btn>
            <v-btn
              size="small"
              variant="flat"
              color="error-600"
              @click="handleDelete(item)"
              class="btn-delete"
            >
              <v-icon size="16" left>mdi-delete</v-icon>
              Delete
            </v-btn>
          </template>
        </v-data-table>
      </v-card-text>
    </v-card>

    <v-dialog v-model="dialog" max-width="700px" persistent scrollable>
      <v-card class="dialog-card">
        <v-card-title class="dialog-header">
          <span class="headline-4">{{ isEdit ? 'Edit Anjungan' : 'Tambah Anjungan Baru' }}</span>
          <v-btn icon variant="text" @click="closeDialog" size="small" class="btn-close">
            <v-icon>mdi-close</v-icon>
          </v-btn>
        </v-card-title>
        <v-divider></v-divider>

        <v-card-text class="dialog-content">
          <v-form ref="formRef">
            <div class="field-group">
              <div class="group-label">Informasi Anjungan</div>

              <v-text-field
                label="Nama Anjungan"
                v-model="formData.namaAnjungan"
                variant="outlined"
                density="compact"
                :rules="[v => !!v || 'Nama anjungan harus diisi']"
                hide-details="auto"
                class="mb-3 input-field"
                placeholder="Anjungan Lobby"
              ></v-text-field>

              <v-select
                label="Jenis Pasien"
                :items="jenisPasienOptions"
                v-model="formData.jenisPasien"
                variant="outlined"
                density="compact"
                :rules="[v => !!v || 'Pilih jenis pasien']"
                hide-details="auto"
                class="mb-3 input-field"
                placeholder="Reguler atau BPJS"
              ></v-select>

              <v-select
                label="Pilih Klinik"
                :items="availableClinics"
                v-model="formData.klinik"
                item-title="name"
                item-value="kode"
                variant="outlined"
                density="compact"
                multiple
                chips
                closable-chips
                :rules="[v => v.length > 0 || 'Pilih minimal 1 klinik']"
                hide-details="auto"
                class="input-field"
                :disabled="!formData.jenisPasien"
              >
                <template v-slot:chip="{ props, item }">
                  <v-chip
                    v-bind="props"
                    closable
                    size="small"
                    class="chip-secondary"
                  >
                    {{ item.raw.name }}
                  </v-chip>
                </template>
                <template v-slot:item="{ props, item }">
                  <v-list-item v-bind="props">
                    <template v-slot:prepend>
                      <v-chip size="x-small" class="chip-secondary-small">{{ item.raw.kode }}</v-chip>
                    </template>
                    <v-list-item-title class="body-3">{{ item.raw.name }}</v-list-item-title>
                  </v-list-item>
                </template>
              </v-select>

              <div v-if="formData.klinik.length > 0" class="selected-preview">
                <v-icon size="14" class="icon-success">mdi-check-circle</v-icon>
                <small class="caption-2">{{ formData.klinik.length }} klinik dipilih</small>
              </div>
            </div>
          </v-form>
        </v-card-text>

        <v-divider></v-divider>

        <v-card-actions class="dialog-actions">
          <v-spacer></v-spacer>
          <v-btn variant="outlined" @click="closeDialog" class="btn-cancel">
            <v-icon left size="18">mdi-close</v-icon>
            Batal
          </v-btn>
          <v-btn variant="flat" @click="submitForm" class="btn-submit">
            <v-icon left size="18">mdi-content-save</v-icon>
            Simpan
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

    <!-- Preview Dialog -->
    <v-dialog v-model="previewDialog" max-width="95vw" max-height="95vh" persistent>
      <v-card class="preview-dialog-card">
        <v-card-title class="preview-dialog-header">
          <div class="preview-header-content">
            <v-icon size="24" class="mr-2">mdi-monitor-dashboard</v-icon>
            <span class="headline-4">Preview Anjungan: {{ previewItem?.namaAnjungan || '' }}</span>
          </div>
          <v-btn icon variant="text" size="small" class="btn-close" @click="closePreviewDialog">
            <v-icon>mdi-close</v-icon>
          </v-btn>
        </v-card-title>
        <v-divider></v-divider>
        <v-card-text class="preview-content">
          <iframe
            v-if="previewUrl"
            :src="previewUrl"
            class="preview-iframe"
            frameborder="0"
            allowfullscreen
          ></iframe>
          <div v-else class="preview-loading">
            <v-progress-circular indeterminate color="primary"></v-progress-circular>
            <p class="mt-4">Memuat preview...</p>
          </div>
        </v-card-text>
      </v-card>
    </v-dialog>

      <v-snackbar v-model="snackbar.show" :color="snackbar.color" :timeout="3000">
        <span class="body-3">{{ snackbar.message }}</span>
        <template v-slot:actions>
          <v-btn variant="text" @click="snackbar.show = false" size="small">Tutup</v-btn>
        </template>
      </v-snackbar>
    </v-container>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useMasterStore } from '@/stores/masterStore';
import { useAnjunganStore } from '@/stores/anjunganStore';
import { useClinicStore } from '@/stores/clinicStore';

const masterStore = useMasterStore();
const anjunganStore = useAnjunganStore();
const clinicStore = useClinicStore();

const dialog = ref(false);
const isEdit = ref(false);
const formRef = ref(null);
const previewDialog = ref(false);
const previewItem = ref(null);
const previewUrl = ref('');

const snackbar = ref({
  show: false,
  message: '',
  color: 'success'
});

const headers = ref([
  { title: 'No', value: 'no', sortable: false, width: '60px' },
  { title: 'Nama Anjungan', value: 'namaAnjungan', sortable: true },
  { title: 'Jenis Pasien', value: 'jenisPasien', sortable: false },
  { title: 'Klinik Ditampilkan', value: 'klinik', sortable: false },
  { title: 'Layar Informasi', value: 'layarInformasi', sortable: false, width: '150px' },
  { title: 'Actions', value: 'actions', sortable: false, width: 'auto' },
]);

const jenisPasienOptions = ['Reguler', 'Eksekutif'];

const anjunganItems = computed(() => anjunganStore.getAllAnjungan);

const formData = ref({
  id: null,
  namaAnjungan: '',
  jenisPasien: '',
  klinik: [],
});

// Computed property to get filtered clinics based on selected jenisPasien
const availableClinics = computed(() => {
  if (!formData.value.jenisPasien) {
    return clinicStore.getClinicsForDropdown();
  }
  return clinicStore.getClinicsForDropdown(formData.value.jenisPasien);
});

// Watch jenisPasien changes and clear clinic selection
watch(() => formData.value.jenisPasien, (newVal, oldVal) => {
  if (newVal !== oldVal && oldVal !== '') {
    formData.value.klinik = [];
  }
});

const openTambahDialog = () => {
  isEdit.value = false;
  resetForm();
  dialog.value = true;
};

const openEditDialog = (item) => {
  isEdit.value = true;
  formData.value = {
    id: item.id,
    namaAnjungan: item.namaAnjungan,
    jenisPasien: item.jenisPasien,
    klinik: [...item.klinik],
  };
  dialog.value = true;
};

const closeDialog = () => {
  dialog.value = false;
  resetForm();
};

const resetForm = () => {
  formData.value = {
    id: null,
    namaAnjungan: '',
    jenisPasien: '',
    klinik: [],
  };
  if (formRef.value) {
    formRef.value.reset();
  }
};

const submitForm = async () => {
  const { valid } = await formRef.value.validate();
  if (!valid) return;

  let result;
  if (isEdit.value) {
    result = anjunganStore.updateAnjungan(formData.value);
  } else {
    result = anjunganStore.addAnjungan(formData.value);
  }

  snackbar.value = {
    show: true,
    message: result.message,
    color: result.success ? 'success' : 'error',
  };

  if (result.success) {
    closeDialog();
  }
};

const handleDelete = (item) => {
  if (confirm(`Hapus anjungan ${item.namaAnjungan}?`)) {
    const result = anjunganStore.deleteAnjungan(item.id);
    snackbar.value = {
      show: true,
      message: result.message,
      color: result.success ? 'success' : 'error',
    };
  }
};

const openPreviewDialog = (item) => {
  previewItem.value = item;
  // Generate preview URL untuk anjungan dengan ID
  previewUrl.value = `/anjungan/anjungan/${item.id}`;
  previewDialog.value = true;
};

const closePreviewDialog = () => {
  previewDialog.value = false;
  previewItem.value = null;
  previewUrl.value = '';
};

// Fetch Reguler clinics from API on mount
onMounted(async () => {
  await clinicStore.fetchRegulerClinics();
});
</script>

<style scoped lang="scss">
$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: #3556AE;
$primary-600: #3A61C9;

$secondary-700: #E65A0D;
$secondary-600: #F16F29;
$secondary-300: #FFB58D;

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

$danger-600: #E02B1D;

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

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

.page-header {
  background: linear-gradient(135deg, $primary-600 0%, $primary-700 100%);
  border-radius: 0 !important;
  box-shadow: 0 4px 16px rgba(58, 97, 201, 0.2);
}

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

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

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

.page-title {
  font-size: 32px;
  line-height: 40px;
  font-weight: $font-weight-semibold;
  margin: 0;
  color: $neutral-100;
}

.page-subtitle {
  margin: 2px 0 0 0;
  opacity: 0.9;
  font-size: 15px;
  line-height: 22px;
  font-weight: $font-weight-regular;
  color: $neutral-100;
}

.add-btn {
  font-weight: $font-weight-semibold;
  text-transform: none;
  letter-spacing: 0.5px;
  font-size: 16px;
  line-height: 24px;
  color: $secondary-600 !important;
}

// ============================================
// ACTION BAR
// ============================================
.action-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: $neutral-100;
  border-radius: 12px;
  border: 1px solid $neutral-400;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.action-btn {
  font-weight: $font-weight-semibold;
  text-transform: none;
  letter-spacing: 0.5px;
  font-size: 16px;
  line-height: 24px;
}

.data-table {
  font-family: $font-family-base;
}

.klinik-tags {
  display: flex;
  flex-wrap: wrap;
  max-width: 600px;
}

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

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

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

.chip-secondary-outline {
  border: 1px solid $secondary-600;
  background-color: transparent !important;
  color: $secondary-600 !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;
}

.btn-edit {
  background-color: $primary-600 !important;
  color: $neutral-100 !important;
  text-transform: none;
  font-weight: $font-weight-semibold;
  font-size: 14px;
  line-height: 20px;
}

.btn-delete {
  border-color: $danger-600 !important;
  color: $danger-600 !important;
  text-transform: none;
  font-weight: $font-weight-semibold;
  font-size: 14px;
  line-height: 20px;
}

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

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

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

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

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

.dialog-actions {
  padding: 16px 24px;
  background: $neutral-300;
}

.field-group {
  background: $neutral-100;
  padding: 20px;
  border-radius: 12px;
  margin-bottom: 0;
  border: 1px solid $neutral-400;
}

.group-label {
  font-size: 14px;
  line-height: 20px;
  font-weight: $font-weight-semibold;
  color: $secondary-600;
  margin-bottom: 12px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

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

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

.input-field {
  font-size: 14px;
  line-height: 20px;
}

.chip-secondary {
  background-color: $secondary-600 !important;
  color: $neutral-100 !important;
  font-weight: $font-weight-medium;
}

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

.selected-preview {
  margin-top: 8px;
  padding: 8px 12px;
  background: $success-200;
  border-radius: 6px;
  display: flex;
  align-items: center;
  gap: 4px;
  border: 1px solid $success-300;
}

.icon-success {
  color: $success-600 !important;
}

.btn-cancel {
  border-color: $neutral-600 !important;
  color: $neutral-800 !important;
  text-transform: none;
  font-weight: $font-weight-semibold;
  font-size: 16px;
  line-height: 24px;
  min-width: 100px;
}

.btn-submit {
  background-color: $secondary-600 !important;
  color: $neutral-100 !important;
  text-transform: none;
  font-weight: $font-weight-semibold;
  font-size: 16px;
  line-height: 24px;
  min-width: 100px;
}

// ============================================
// PREVIEW DIALOG
// ============================================
.btn-preview {
  background-color: $success-600 !important;
  color: $neutral-100 !important;
  text-transform: none;
  font-weight: $font-weight-semibold;
  font-size: 14px;
  line-height: 20px;
}

.preview-dialog-card {
  font-family: $font-family-base;
  height: 95vh;
  display: flex;
  flex-direction: column;
}

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

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

.preview-content {
  padding: 0 !important;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: $neutral-800;
  overflow: hidden;
}

.preview-iframe {
  width: 100%;
  height: 100%;
  min-height: 80vh;
  border: none;
}

.preview-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: $neutral-100;
  padding: 40px;
}
</style>

