<template>
  <div>
    <!-- Header -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <div class="header-icon">
            <v-icon size="28" color="white">mdi-ticket-account</v-icon>
          </div>
          <div class="header-text">
            <h2 class="page-title">Screen Antrean Masuk</h2>
            <p class="page-subtitle">Rabu, 13 Agustus 2025 - Konfigurasi Layar Antrean Masuk</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 Screen
        </v-btn>
      </div>

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

          <template v-slot:item.loket="{ item }">
            <div class="loket-tags">
              <v-chip
                v-for="(loketId, idx) in item.loket.slice(0, 3)"
                :key="idx"
                size="small"
                class="ma-1 chip-primary-outline"
              >
                {{ getLoketNameById(loketId) }}
              </v-chip>
              <v-chip
                v-if="item.loket.length > 3"
                size="small"
                class="ma-1 chip-neutral"
              >
                +{{ item.loket.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>
              Konfigurasi
            </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>

    <!-- 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 Antrean Masuk 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="AM-001"
              ></v-text-field>
              <small class="caption-2">Nomor identifikasi unik untuk screen</small>
            </div>

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

            <!-- Loket Selection -->
            <div class="field-group">
              <div class="group-label">
                <v-icon size="18" class="icon-label">mdi-view-dashboard</v-icon>
                <span>Loket yang Ditampilkan</span>
              </div>
              
              <v-select
                label="Pilih Loket"
                :items="loketOptions"
                v-model="formData.loket"
                item-title="nama"
                item-value="id"
                variant="outlined"
                density="compact"
                multiple
                chips
                closable-chips
                :rules="[v => v.length > 0 || 'Pilih minimal 1 loket']"
                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.nama }}</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.loket.length > 0" class="selected-preview">
                <v-icon size="14" class="icon-success">mdi-check-circle</v-icon>
                <small class="caption-2">{{ formData.loket.length }} loket dipilih</small>
              </div>

              <!-- Grid Preview -->
              <div v-if="formData.loket.length > 0" class="loket-grid mt-4">
                <div class="grid-label">Preview Tampilan:</div>
                <div class="loket-preview-grid">
                  <v-chip
                    v-for="loketId in formData.loket"
                    :key="loketId"
                    size="small"
                    class="ma-1 chip-primary-outline"
                  >
                    {{ getLoketNameById(loketId) }}
                  </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-ticket-account</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>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useAntreanMasukScreenStore } from '@/stores/antreanMasukScreenStore';
import { useLoketStore } from '@/stores/loketStore';

const antreanMasukScreenStore = useAntreanMasukScreenStore();
const loketStore = useLoketStore();
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: "Loket Ditampilkan", value: "loket", sortable: false },
  { title: "Layar Informasi", value: "layarInformasi", sortable: false, width: "150px" },
  { title: "Actions", value: "actions", sortable: false, width: "auto" },
]);

const antreanMasukScreenItems = computed(() => antreanMasukScreenStore.antreanMasukScreenItems);

// Get loket options for select dropdown
const loketOptions = computed(() => {
  // Directly access loketStore.loketData.value since it's a ref
  // This is the most reliable way to get all lokets
  const loketsArray = loketStore.loketData?.value || loketStore.loketData || [];
  
  // Ensure it's an array
  if (!Array.isArray(loketsArray)) {
    console.warn('loketData is not an array:', loketsArray);
    return [];
  }
  
  // Debug: log jumlah loket yang ditemukan
  if (loketsArray.length > 0) {
    console.log(`[ScreenAntreanMasuk] Found ${loketsArray.length} lokets:`, loketsArray.map(l => l.namaLoket || l.nama));
  } else {
    console.warn('[ScreenAntreanMasuk] No lokets found in loketStore');
  }
  
  // Map ALL lokets to options format - return everything, no filtering or limiting
  return loketsArray.map(loket => ({
    id: loket.id,
    nama: loket.namaLoket || `Loket ${loket.no || loket.id}`
  }));
});

// Helper to get loket name by ID
const getLoketNameById = (loketId) => {
  // Get loket directly from loketStore
  const loketsArray = loketStore.loketData?.value || loketStore.loketData || [];
  const loket = loketsArray.find(l => l.id === loketId);
  return loket ? loket.namaLoket : `Loket ${loketId}`;
};

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

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,
    loket: [...item.loket],
  };
  dialog.value = true;
};

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

const resetForm = () => {
  formData.value = {
    id: null,
    namaScreen: '',
    nomorScreen: '',
    loket: [],
  };
  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 = antreanMasukScreenStore.updateAntreanMasukScreen(formData.value);
    snackbar.value = {
      show: true,
      message: result.message,
      color: result.success ? 'success' : 'error'
    };
  } else {
    // Add new screen
    const result = antreanMasukScreenStore.addAntreanMasukScreen(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 = antreanMasukScreenStore.deleteAntreanMasukScreen(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
  // Note: Preview akan menampilkan halaman antrean masuk dengan ID screen
  previewUrl.value = `/anjungan/antreanmasuk/${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;

$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 & 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, $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;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.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
// ============================================
.data-table {
  font-family: $font-family-base;
}

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

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

// ============================================
// 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: $primary-600 !important;
  color: $neutral-100 !important;
  font-weight: $font-weight-medium;
}

.chip-secondary-small {
  background-color: $primary-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;
}

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

.loket-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, $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>
