<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-monitor</v-icon>
            </div>
            <div class="header-text">
              <h2 class="page-title">Screen Configuration</h2>
              <p class="page-subtitle">Rabu, 13 Agustus 2025 - Konfigurasi Layar Antrian</p>
            </div>
          </div>
          <v-btn 
            color="white" 
            @click="openTambahDialog"
            elevation="0"
            class="add-btn"
          >
            <v-icon left size="20">mdi-plus-circle</v-icon>
            Tambah Screen
          </v-btn>
        </div>
      </div>

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

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

          <template v-slot:item.layarInformasi="{ item }">
            <v-btn
              size="small"
              @click="openPreviewDialog(item)"
              variant="flat"
              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"
              @click="openEditDialog(item)"
              variant="flat"
              class="btn-edit mr-2"
            >
              <v-icon size="16" left>mdi-cog</v-icon>
              Konfigurasi
            </v-btn>
            <v-btn
              size="small"
              @click="handleDelete(item)"
              variant="outlined"
              class="btn-delete"
            >
              <v-icon size="16" left>mdi-delete</v-icon>
              Delete
            </v-btn>
          </template>
        </v-data-table>
      </v-card-text>
    </v-card>

    <!-- Dialog Tambah/Edit -->
    <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 ? 'Konfigurasi Screen' : 'Tambah Screen 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">
            <!-- Informasi Screen -->
            <div class="field-group">
              <div class="group-label">Informasi Screen</div>
              
              <v-text-field
                label="Nama Screen"
                v-model="formData.namaScreen"
                variant="outlined"
                density="compact"
                :rules="[v => !!v || 'Nama screen harus diisi']"
                hide-details="auto"
                class="mb-3 input-field"
                placeholder="Layar Screen 1"
              ></v-text-field>

              <v-text-field
                label="Nomor Screen"
                v-model="formData.nomorScreen"
                variant="outlined"
                density="compact"
                hide-details="auto"
                class="mb-3 input-field"
                placeholder="Screen-001"
              ></v-text-field>
              <small class="caption-2">Nomor identifikasi unik untuk screen</small>
            </div>

            <v-divider class="my-4 divider-section"></v-divider>

            <!-- Klinik Selection -->
            <div class="field-group">
              <div class="group-label">
                <v-icon size="18" class="icon-label">mdi-hospital-box</v-icon>
                <span>Klinik yang Ditampilkan</span>
              </div>
              
              <v-select
                label="Pilih Klinik"
                :items="masterStore.klinikList"
                v-model="formData.klinik"
                item-title="nama"
                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"
              >
                <template v-slot:chip="{ props, item }">
                  <v-chip
                    v-bind="props"
                    closable
                    size="small"
                    class="chip-secondary"
                  >
                    {{ item.raw.nama }}
                  </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.nama }}</v-list-item-title>
                  </v-list-item>
                </template>
              </v-select>
              
              <!-- Selected Preview -->
              <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>

              <!-- Grid Preview -->
              <div v-if="formData.klinik.length > 0" class="klinik-grid mt-4">
                <div class="grid-label">Preview Tampilan:</div>
                <div class="klinik-preview-grid">
                  <v-chip
                    v-for="kode in formData.klinik"
                    :key="kode"
                    size="small"
                    class="ma-1 chip-secondary-outline"
                  >
                    {{ masterStore.getKlinikNameByKode(kode) }}
                  </v-chip>
                </div>
              </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</v-icon>
            <span class="headline-4">Preview Screen: {{ previewItem?.namaScreen || '' }}</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>

    <!-- Snackbar -->
    <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>
</template>

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

const masterStore = useMasterStore();
const screenStore = useScreenStore();
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: "80px" },
  { title: "Nama Screen", value: "namaScreen", sortable: true },
  { title: "Nomor Screen", value: "nomorScreen", sortable: true },
  { 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 screenItems = computed(() => screenStore.screenItems);

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

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

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

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

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

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

  if (isEdit.value) {
    // Update screen
    const result = screenStore.updateScreen(formData.value);
    snackbar.value = {
      show: true,
      message: result.message,
      color: result.success ? 'success' : 'error'
    };
  } else {
    // Add new screen
    const result = screenStore.addScreen(formData.value);
    snackbar.value = {
      show: true,
      message: result.message,
      color: result.success ? 'success' : 'error'
    };
  }

  closeDialog();
};

const handleDelete = (item) => {
  if (confirm(`Hapus screen ${item.namaScreen}?`)) {
    const result = screenStore.deleteScreen(item.id);
    snackbar.value = {
      show: true,
      message: result.message,
      color: result.success ? 'success' : 'error'
    };
  }
};

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

const closePreviewDialog = () => {
  previewDialog.value = false;
  previewItem.value = null;
  previewUrl.value = '';
};
</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;

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

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

$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
// ============================================
.page-header {
  background: linear-gradient(135deg, $secondary-600 0%, $secondary-700 100%);
  border-radius: 16px 16px 0 0;
  box-shadow: 0 4px 16px rgba(6, 113, 224, 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;
}

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

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

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

.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: $secondary-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
// ============================================
.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;
}

.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;
}

// ============================================
// FORM ELEMENTS
// ============================================
.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;
  display: flex;
  align-items: center;
  gap: 6px;
}

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

.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;
}

.divider-section {
  border-color: $neutral-400 !important;
}

// ============================================
// CHIPS
// ============================================
.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
// ============================================
.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;
}

.klinik-grid {
  background: $neutral-300;
  padding: 16px;
  border-radius: 8px;
  border: 1px solid $neutral-400;
}

.grid-label {
  font-size: 12px;
  line-height: 16px;
  font-weight: $font-weight-semibold;
  color: $neutral-700;
  margin-bottom: 12px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

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

// ============================================
// BUTTONS
// ============================================
.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, $secondary-600 0%, $secondary-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>