<template>
  <v-card class="pa-5 dialog-card">
    <p class="text-center font-weight-bold mb-4 text-white" style="font-size: 20px;">
      หน้าจัดแต่งการเก็บ
    </p>

    <v-table dense class="product-table">
      <thead>
        <tr>
          <th>ลำดับความสำคัญ</th>
          <th>ชื่อ</th>
          <th>ชนิด</th>
          <th>แบรนด์</th>
          <th>จำนวนที่ต้องการเก็บ</th>
          <th>หน่วย</th>
        </tr>
      </thead>
      <transition-group tag="tbody" name="list">
        <tr 
          v-for="config in stockConfigStore.stockConfigs" 
          :key="config.StockConfigID"
          draggable="true"
          @dragstart="() => handleDragStart(config)"
          @dragover="handleDragOver"
          @drop="() => handleDrop(config)"
        >
          <td class="drag-handle">☰</td>
          <td>{{ config.itemName }}</td>
          <td>{{ config.itemType }}</td>
          <td>{{ config.itemDetail?.brand ?? '-' }}</td>
          <td>{{ (config.targetStockLevel ?? 0).toLocaleString() }}</td>
          <td>{{ config.itemDetail?.unit ?? '-' }}</td>
        </tr>

      </transition-group>
    </v-table>

    <!-- Toggle & Action Buttons -->
    <div class="action-section">
      <v-switch
        color="primary"
        v-model="isProductionSpare"
        label="ไม่ทำการผลิตเผื่อ"
        class="switch-toggle"
      />
    </div>
  </v-card>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useStockConfigStore } from '@/stores/stockConfig';
import { usePageContextStore } from '@/stores/pageContext'; 

const stockConfigStore = useStockConfigStore();
const pageContextStore = usePageContextStore();

// ดึงข้อมูล StockConfig จาก backend เมื่อ component mount
onMounted(() => {
  const pageId = pageContextStore.currentPage;
  if (pageId != null) {
    console.log('📄 Current Page ID:', pageId);
    stockConfigStore.fetchStockConfigs(pageId).then(() => {
      console.log('✅ ดึงได้:', stockConfigStore.stockConfigs);
    });
  }
});

// สำหรับ drag & drop
const draggedConfig = ref(null);

function handleDragStart(config) {
  draggedConfig.value = config;
}

function handleDragOver(event) {
  event.preventDefault();
}

async function handleDrop(targetConfig) {
  if (!draggedConfig.value || draggedConfig.value.StockConfigID === targetConfig.StockConfigID)
    return;

  const configs = stockConfigStore.stockConfigs;
  const draggedIndex = configs.findIndex(
    (c) => c.StockConfigID === draggedConfig.value.StockConfigID
  );
  const targetIndex = configs.findIndex(
    (c) => c.StockConfigID === targetConfig.StockConfigID
  );

  const [removed] = configs.splice(draggedIndex, 1);
  configs.splice(targetIndex, 0, removed);  

  // ✅ หลัง reorder ใน frontend แล้วส่งอัปเดตไป backend
  const pageID = pageContextStore.currentPage;
  const payload = {
    pages: [
      {
        PageID: pageID,
        configs: configs.map((config, index) => ({
          id: config.StockConfigID,
          priorityLevel: index + 1,
          targetStockLevel: config.targetStockLevel,
          status: config.status,
        })),
      },
    ],
  };

  await stockConfigStore.batchUpdateStockConfigs(payload);
  draggedConfig.value = null;
}



// Toggle สำหรับ "ไม่ทำการผลิตเผื่อ"
const isProductionSpare = ref(false);
</script>

<style scoped>
.dialog-card {
  background-color: #2b2e3f;
  border-radius: 15px;
  color: white;
}

.product-table {
  width: 100%;
  background-color: #333647;
  border-radius: 10px;
}

.product-table th,
.product-table td {
  padding: 10px;
  text-align: center;
  color: white;
}

.product-table tr {
  background-color: #333647;
}

.product-table tr:hover {
  background-color: #3e4258;
}

.drag-handle {
  cursor: grab;
  font-size: 18px;
  text-align: center;
}

/* Animation สำหรับ Transition Group */
.list-move {
  transition: transform 0.3s ease, opacity 0.3s ease;
}

.list-enter-active,
.list-leave-active {
  transition: opacity 0.3s, transform 0.3s;
}

.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

.switch-toggle {
  color: white;
}

.action-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

</style>