<!-- pages/MasterPenunjang.vue -->
<template>
  <div>
    <!-- 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-pulse</v-icon>
          </div>
          <div class="header-text">
            <h2 class="page-title">Master Penunjang</h2>
            <p class="page-subtitle">Rabu, 13 Agustus 2025 - Manajemen Layanan Penunjang</p>
          </div>
        </div>
        <v-btn 
          color="primary-600"
          variant="flat"
          elevation="0"
          class="action-btn"
          @click="openTambahDialog"
        >
          <v-icon left size="20">mdi-plus-circle</v-icon>
          Tambah Penunjang
        </v-btn>
      </div>
    </div>

    <v-container>
      <v-card>
        <!-- Table -->
        <v-card-text>
        <!-- Filter Row -->
        <div class="d-flex flex-wrap align-center justify-space-between mb-4">
          <div class="d-flex align-center">
            <span class="mr-2 body-3">Show</span>
            <v-select
              v-model="itemsPerPage"
              :items="[10, 25, 50, 100]"
              variant="outlined"
              density="compact"
              hide-details
              style="max-width: 80px;"
              rounded
              class="mr-2"
            ></v-select>
            <span class="body-3">entries</span>
          </div>
          <div class="d-flex align-center">
            <v-text-field
              v-model="search"
              prepend-inner-icon="mdi-magnify"
              label="Search"
              variant="outlined"
              density="compact"
              hide-details
              rounded
              clearable
              style="min-width: 250px;"
            ></v-text-field>
          </div>
        </div>

        <v-data-table
          v-model:page="page"
          :headers="headers"
          :items="masterStore.penunjangData"
          :items-per-page="itemsPerPage"
          :search="search"
          item-value="id"
          class="elevation-0 data-table"
          hover
          @update:itemsLength="filteredTotal = $event"
        >
          <template #item.jenis="{ item }">
            <v-chip 
              size="small" 
              :class="item.jenis === 'Medis' ? 'chip-medis' : 'chip-non-medis'"
            >
              {{ item.jenis }}
            </v-chip>
          </template>
          
          <template #item.shift="{ item }">
            <v-chip size="small" class="chip-secondary">
              {{ item.shift }}
            </v-chip>
          </template>
          
          <template #item.totalQuota="{ item }">
            <span class="body-2 text-semibold">{{ item.totalQuota }}</span>
          </template>

          <template #item.status="{ item }">
            <v-chip 
              size="small" 
              :class="item.status === 'Aktif' ? 'chip-active' : 'chip-inactive'"
            >
              {{ item.status }}
            </v-chip>
          </template>
          
          <template #item.aksi="{ item }">
            <v-btn
              size="small"
              color="warning-600"
              class="btn-edit mr-2"
              variant="flat"
              @click="openEditDialog(item)"
            >
              <v-icon size="16" left>mdi-pencil</v-icon>
              Edit
            </v-btn>
            <v-btn
              size="small"
              color="error-600"
              class="btn-delete"
              variant="flat"
              @click="handleDelete(item)"
            >
              <v-icon size="16" left>mdi-delete</v-icon>
              Delete
            </v-btn>
          </template>

          <template #bottom>
            <v-row class="ma-2" align="center">
              <v-col cols="12" sm="6" class="d-flex align-center justify-start body-3 text-grey">
                {{ showingEntriesText }}
              </v-col>
              <v-col cols="12" sm="6" class="d-flex align-center justify-end">
                <v-pagination
                  v-model="page"
                  :length="pageCount"
                  total-visible="5"
                  rounded="circle"
                  size="small"
                ></v-pagination>
              </v-col>
            </v-row>
          </template>
        </v-data-table>
      </v-card-text>
    </v-card>

    <!-- Dialog Tambah/Edit - COMPACT VERSION -->
    <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 Penunjang' : 'Tambah Penunjang' }}</span>
          <v-btn icon variant="text" size="small" class="btn-close" @click="closeDialog">
            <v-icon>mdi-close</v-icon>
          </v-btn>
        </v-card-title>

        <v-divider/>

        <v-card-text class="dialog-content-compact">
          <v-form ref="formRef">
            <!-- Informasi Dasar -->
            <div class="form-section">
              <div class="section-title">
                <v-icon size="18" class="mr-2">mdi-information-outline</v-icon>
                <span class="text-semibold">Informasi Dasar</span>
              </div>
              
              <v-text-field
                v-model="formData.kode"
                label="Kode Penunjang"
                variant="outlined"
                density="compact"
                :rules="[v => !!v || 'Kode harus diisi']"
                hide-details="auto"
                placeholder="LAB"
                class="form-field"
              />

              <v-text-field
                v-model="formData.nama"
                label="Nama Penunjang"
                variant="outlined"
                density="compact"
                :rules="[v => !!v || 'Nama harus diisi']"
                hide-details="auto"
                placeholder="Laboratorium"
                class="form-field"
              />

              <v-row dense>
                <v-col cols="6">
                  <v-select
                    v-model="formData.jenis"
                    label="Jenis Penunjang"
                    :items="jenisPenunjangList"
                    variant="outlined"
                    density="compact"
                    :rules="[v => !!v || 'Jenis harus dipilih']"
                    hide-details="auto"
                    class="form-field"
                  />
                </v-col>
                <v-col cols="6">
                  <v-select
                    v-model="formData.status"
                    label="Status"
                    :items="statusList"
                    variant="outlined"
                    density="compact"
                    hide-details="auto"
                    class="form-field"
                  />
                </v-col>
              </v-row>
            </div>

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

            <!-- Konfigurasi Shift -->
            <div class="form-section">
              <div class="section-title">
                <v-icon size="18" class="mr-2">mdi-clock-outline</v-icon>
                <span class="text-semibold">Konfigurasi Shift & Kuota</span>
              </div>

              <v-row dense>
                <v-col cols="6">
                  <v-text-field
                    v-model.number="formData.shift"
                    label="Jumlah Shift"
                    type="number"
                    variant="outlined"
                    density="compact"
                    :rules="[v => !!v || 'Shift harus diisi', v => v > 0 || 'Minimal 1']"
                    hide-details="auto"
                    class="form-field"
                    @update:model-value="updateShiftCount"
                  />
                </v-col>
              </v-row>
<!--               
                  <div class="total-display">
                    <span class="caption-text">Total Kuota</span>
                    <v-chip size="small" color="success" variant="flat">
                      <v-icon size="14" start>mdi-sigma</v-icon>
                      {{ calculateTotalQuota() }}
                    </v-chip>
                  </div> -->
              

              <v-checkbox
                v-model="formData.autoShift"
                label="Auto Shift"
                hide-details
                color="primary"
                density="compact"
                class="form-field-checkbox"
              />

              <!-- Shift List -->
              <div class="shift-list">
                <div v-for="(shift, index) in formData.jamShiftList" :key="index" class="shift-row">
                  <div class="shift-label">Shift {{ index + 1 }}</div>
                  <v-row dense>
                    <v-col cols="4">
                      <v-text-field
                        v-model="shift.dari"
                        label="Mulai"
                        type="time"
                        variant="outlined"
                        density="compact"
                        hide-details
                        class="form-field-inline"
                      />
                    </v-col>
                    <v-col cols="4">
                      <v-text-field
                        v-model="shift.sampai"
                        label="Selesai"
                        type="time"
                        variant="outlined"
                        density="compact"
                        hide-details
                        class="form-field-inline"
                      />
                    </v-col>
                    <v-col cols="3">
                      <v-text-field
                        v-model.number="shift.kuota"
                        label="Kuota"
                        type="number"
                        variant="outlined"
                        density="compact"
                        hide-details
                        placeholder="0"
                        class="form-field-inline"
                      />
                    </v-col>
                    <v-col cols="1" class="d-flex align-center">
                      <v-btn
                        v-if="formData.jamShiftList.length > 1"
                        icon
                        size="x-small"
                        variant="text"
                        color="error"
                        @click="removeShift(index)"
                      >
                        <v-icon size="18">mdi-close</v-icon>
                      </v-btn>
                    </v-col>
                  </v-row>
                </div>
              </div>
            </div>

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

            <!-- Jadwal Operasional -->
            <div class="form-section">
              <div class="section-title">
                <v-icon size="18" class="mr-2">mdi-calendar-check</v-icon>
                <span class="text-semibold">Jadwal Operasional</span>
              </div>
              
              <v-select
                v-model="formData.jadwalOperasional"
                :items="hariList.map(h => h.hari)"
                label="Pilih Hari Operasional"
                variant="outlined"
                density="compact"
                multiple
                chips
                hide-details
                class="form-field"
              >
                <template #chip="{ item, props }">
                  <v-chip
                    v-bind="props"
                    size="small"
                    closable
                  >
                    {{ item.title }}
                  </v-chip>
                </template>
              </v-select>
            </div>

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

            <!-- Keterangan -->
            <div class="form-section">
              <div class="section-title">
                <v-icon size="18" class="mr-2">mdi-note-text-outline</v-icon>
                <span class="text-semibold">Keterangan</span>
              </div>
              
              <v-textarea
                v-model="formData.keterangan"
                label="Keterangan Layanan"
                variant="outlined"
                density="compact"
                hide-details
                rows="3"
                placeholder="Informasi tambahan tentang layanan penunjang..."
                class="form-field"
              />
            </div>
          </v-form>
        </v-card-text>

        <v-divider/>

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

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

<script setup>
definePageMeta({
  middleware: ['auth', 'check-page-access']
})
import { ref, computed } from 'vue';
import { useMasterStore } from '@/stores/masterStore';

const masterStore = useMasterStore();
const page = ref(1);
const itemsPerPage = ref(10);
const search = ref('');
const filteredTotal = ref(masterStore.penunjangData.length);

import { watch } from 'vue';
watch(() => masterStore.penunjangData.length, (newLen) => {
  if (!search.value) filteredTotal.value = newLen;
}, { immediate: true });
const dialog = ref(false);
const isEdit = ref(false);
const formRef = ref(null);

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

const headers = ref([
  { title: 'No', value: 'no', sortable: true },
  { title: 'Kode', value: 'kode', sortable: true },
  { title: 'Nama Penunjang', value: 'nama', sortable: true },
  { title: 'Jenis', value: 'jenis', sortable: true },
  { title: 'Shift', value: 'shift', sortable: true },
  { title: 'Total Kuota', value: 'totalQuota', sortable: true },
  { title: 'Status', value: 'status', sortable: true },
  { title: 'Aksi', value: 'aksi', sortable: false },
]);

const pageCount = computed(() => {
  return Math.ceil(filteredTotal.value / itemsPerPage.value) || 1;
});

const showingEntriesText = computed(() => {
  if (filteredTotal.value === 0) return 'Showing 0 to 0 of 0 entries';
  const start = (page.value - 1) * itemsPerPage.value + 1;
  const end = Math.min(page.value * itemsPerPage.value, filteredTotal.value);
  return `Showing ${start} to ${end} of ${filteredTotal.value} entries${search.value ? ' (filtered)' : ''}`;
});

const jenisPenunjangList = ref([
  'Medis',
  'Non-Medis'
]);

const statusList = ref([
  'Aktif',
  'Tidak Aktif'
]);

const hariList = ref([
  { no: 1, hari: 'Senin' },
  { no: 2, hari: 'Selasa' },
  { no: 3, hari: 'Rabu' },
  { no: 4, hari: 'Kamis' },
  { no: 5, hari: 'Jum\'at' },
  { no: 6, hari: 'Sabtu' },
  { no: 7, hari: 'Minggu' },
]);

const formData = ref({
  id: null,
  kode: '',
  nama: '',
  jenis: 'Medis',
  shift: 1,
  jamShiftList: [{ dari: '07:00', sampai: '15:00', kuota: 0 }],
  autoShift: false,
  jadwalOperasional: [],
  status: 'Aktif',
  keterangan: ''
});

const calculateTotalQuota = () => {
  return formData.value.jamShiftList.reduce((total, shift) => {
    return total + (parseInt(shift.kuota) || 0);
  }, 0);
};

const updateShiftCount = (newShiftCount) => {
  const currentCount = formData.value.jamShiftList.length;
  
  if (newShiftCount > currentCount) {
    for (let i = currentCount; i < newShiftCount; i++) {
      let defaultDari = '07:00', defaultSampai = '15:00';
      
      if (i === 1) { defaultDari = '13:00'; defaultSampai = '21:00'; }
      else if (i === 2) { defaultDari = '21:00'; defaultSampai = '07:00'; }
      else if (i > 2) {
        const prevShift = formData.value.jamShiftList[i - 1];
        const [prevHour] = prevShift.sampai.split(':');
        const nextHour = (parseInt(prevHour) + 1) % 24;
        defaultDari = `${String(nextHour).padStart(2, '0')}:00`;
        defaultSampai = `${String((nextHour + 8) % 24).padStart(2, '0')}:00`;
      }
      
      formData.value.jamShiftList.push({ dari: defaultDari, sampai: defaultSampai, kuota: 0 });
    }
  } else if (newShiftCount < currentCount && newShiftCount > 0) {
    formData.value.jamShiftList = formData.value.jamShiftList.slice(0, newShiftCount);
  }
};

const removeShift = (index) => {
  if (formData.value.jamShiftList.length > 1) {
    formData.value.jamShiftList.splice(index, 1);
    formData.value.shift = formData.value.jamShiftList.length;
  }
};

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

const openEditDialog = (item) => {
  isEdit.value = true;
  formData.value = {
    id: item.id,
    kode: item.kode,
    nama: item.nama,
    jenis: item.jenis,
    shift: item.shift,
    jamShiftList: JSON.parse(JSON.stringify(item.jamShiftList)),
    autoShift: item.autoShift || false,
    jadwalOperasional: [...(item.jadwalOperasional || [])],
    status: item.status,
    keterangan: item.keterangan || ''
  };
  dialog.value = true;
};

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

const resetForm = () => {
  formData.value = {
    id: null,
    kode: '',
    nama: '',
    jenis: 'Medis',
    shift: 1,
    jamShiftList: [{ dari: '07:00', sampai: '15:00', kuota: 0 }],
    autoShift: false,
    jadwalOperasional: [],
    status: 'Aktif',
    keterangan: ''
  };
  if (formRef.value) {
    formRef.value.reset();
  }
};

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

  let result;
  if (isEdit.value) {
    result = masterStore.updatePenunjang(formData.value);
  } else {
    result = masterStore.addPenunjang(formData.value);
  }

  if (result.success) {
    snackbar.value = { show: true, message: result.message, color: 'success' };
    closeDialog();
  } else {
    snackbar.value = { show: true, message: result.message, color: 'error' };
  }
};

const handleDelete = (item) => {
  if (confirm(`Hapus penunjang ${item.nama}?`)) {
    const result = masterStore.deletePenunjang(item.id);
    snackbar.value = {
      show: true,
      message: result.message,
      color: result.success ? 'success' : 'error'
    };
  }
};
</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;

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

$danger-600: #E02B1D;

$medis-600: #10b981;
$medis-300: #d1fae5;

$non-medis-600: #f59e0b;
$non-medis-300: #fef3c7;

// 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: 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: 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: $primary-600 !important;
}

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

.chip-medis {
  background-color: $medis-300 !important;
  color: $medis-600 !important;
  font-weight: $font-weight-semibold;
}

.chip-non-medis {
  background-color: $non-medis-300 !important;
  color: $non-medis-600 !important;
  font-weight: $font-weight-semibold;
}

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

.chip-active {
  background-color: $success-300 !important;
  color: $success-600 !important;
  font-weight: $font-weight-semibold;
}

.chip-inactive {
  background-color: $neutral-400 !important;
  color: $neutral-600 !important;
  font-weight: $font-weight-semibold;
}

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

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

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

// ============================================
// DIALOG - COMPACT VERSION
// ============================================
.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-compact {
  padding: 20px 24px !important;
  background: $neutral-100;
}

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

// ============================================
// FORM SECTIONS - COMPACT
// ============================================
.form-section {
  margin-bottom: 16px;
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 13px;
  color: $primary-600;
  font-weight: $font-weight-semibold;
  margin-bottom: 12px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.section-divider {
  margin: 16px 0;
  border-color: $neutral-400 !important;
}

.form-field {
  margin-bottom: 12px;
}

.form-field-inline {
  margin-bottom: 0;
}

.form-field-checkbox {
  margin-bottom: 12px;
  margin-top: -4px;
}

// Total Display
.total-display {
  display: flex;
  flex-direction: column;
  gap: 4px;
  height: 40px;
  justify-content: center;
}

.caption-text {
  font-size: 11px;
  color: $neutral-700;
  font-weight: $font-weight-medium;
}

// Shift List
.shift-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-top: 12px;
}

.shift-row {
  background: $neutral-300;
  border-radius: 8px;
  padding: 10px 12px;
  border: 1px solid $neutral-400;
}

.shift-label {
  font-size: 11px;
  font-weight: $font-weight-semibold;
  color: $primary-600;
  margin-bottom: 6px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

// ============================================
// 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: $primary-600 !important;
  color: $neutral-100 !important;
  text-transform: none;
  font-weight: $font-weight-semibold;
  font-size: 16px;
  line-height: 24px;
  min-width: 100px;
}

.body-3 {
  font-size: 14px;
  line-height: 20px;
}
</style>