<script setup>
import { useLight, model, q } from "#imports";
import { useQuasar } from "quasar";
import { ref, watch, onMounted } from "vue";
import { useDragAndDrop } from "@formkit/drag-and-drop/vue";
import { animations } from "@formkit/drag-and-drop";
const light = useLight();
const $q = useQuasar();
const { my } = await q({
  my: {
    myFavorites: {
      my_favorite_id: true,
      label: true,
      path: true,
      icon: true,
      sequence: true
    }
  }
});
const [parent, rows] = useDragAndDrop(my.myFavorites, {
  plugins: [animations()],
  dragHandle: ".drag-handle"
});
const isUpdating = ref(false);
const hasChanges = ref(false);
watch(rows, (newRows) => {
  let hasChanged = false;
  for (let i = 0; i < newRows.length; i++) {
    if (newRows[i].sequence !== i + 1) {
      hasChanged = true;
      break;
    }
  }
  hasChanges.value = hasChanged;
}, { deep: true });
const updateSequence = async () => {
  if (isUpdating.value || !hasChanges.value) return;
  isUpdating.value = true;
  try {
    for (let i = 0; i < rows.value.length; i++) {
      const item = rows.value[i];
      await model("MyFavorite").update(item.my_favorite_id, {
        sequence: i + 1
      });
      item.sequence = i + 1;
    }
    await light.reloadMyFavorites();
    hasChanges.value = false;
    $q.notify({
      message: "Order updated",
      color: "positive",
      icon: "check"
    });
  } catch (error) {
    $q.notify({
      message: "Update failed: " + error.message,
      color: "negative",
      icon: "error"
    });
  } finally {
    isUpdating.value = false;
  }
};
const onSave = async (id, data) => {
  await model("MyFavorite").update(id, data);
  $q.notify({
    message: "Updated successfully",
    color: "positive",
    icon: "check"
  });
  const index = rows.value.findIndex((item) => item.my_favorite_id === id);
  if (index !== -1) {
    Object.assign(rows.value[index], data);
  }
  await light.reloadMyFavorites();
};
const onRemove = async (id) => {
  await model("MyFavorite").delete(id);
  const index = rows.value.findIndex((item) => item.my_favorite_id === id);
  if (index !== -1) {
    rows.value.splice(index, 1);
  }
  await light.reloadMyFavorites();
};
const columns = [
  { name: "handler", label: "", field: "handler", align: "center" },
  { name: "label", label: "Label", field: "label", align: "left" },
  { name: "path", label: "Path", field: "path", align: "left" },
  { name: "icon", label: "Icon", field: "icon", align: "center" },
  { name: "actions", label: "Actions", field: "actions", align: "center" }
];
onMounted(() => {
  parent.value = document.querySelector("#myfav-table .q-table__middle.scroll > table > tbody");
});
</script>

<template>
    <div>
        <q-table id="myfav-table" :rows="rows" :columns="columns" row-key="my_favorite_id" flat :bordered="false"
            :rows-per-page-options="[0]">

            <template #body-cell-label="props">
                <q-td :props="props">
                    {{ props.row.label }}
                    <q-popup-edit v-model="props.row.label" v-slot="scope" buttons
                        @save="onSave(props.row.my_favorite_id, { 'label': $event })">
                        <q-input v-model="scope.value" dense autofocus counter @keyup.enter="scope.set" />
                    </q-popup-edit>
                </q-td>
            </template>

            <template #body-cell-icon="props">
                <q-td :props="props" class="text-center" style="width: 80px;">
                    <!-- Icon -->
                    <l-icon-picker v-model="props.row.icon" flat round size="sm"
                        @update:model-value="onSave(props.row.my_favorite_id, { 'icon': $event })" />
                </q-td>

            </template>

            <template #body-cell-handler="props">
                <q-td :props="props" class="drag-handle" style="cursor: move; width: 40px; text-align: center;">
                    <q-icon name="drag_handle" />
                </q-td>
            </template>
            <!-- 操作列 -->
            <template #body-cell-actions="props">
                <q-td :props="props">
                    <q-btn icon="sym_o_delete" color="negative" flat dense @click="onRemove(props.row.my_favorite_id)"
                        :disable="saving">
                        <q-tooltip>Delete item</q-tooltip>
                    </q-btn>
                </q-td>
            </template>

            <template #no-data>
                <div class="text-center q-pa-md">
                    <l-icon name="sym_o_favorite_border" size="48px" class="text-grey-5" />
                    <div class="text-h6 q-mt-sm">No favorites added yet</div>
                    <div class="text-subtitle2 text-grey-6 q-mt-xs">
                        You can add frequently used features here for quick access.
                    </div>
                </div>
            </template>
        </q-table>

        <!-- 更新按鈕 -->
        <div v-if="hasChanges" class="q-mt-md text-center">
            <q-btn color="primary" icon="save" label="Update Order" @click="updateSequence" :loading="isUpdating"
                :disable="isUpdating" />
        </div>

        <!-- 狀態提示 -->
        <div v-if="isUpdating" class="q-mt-md">
            <q-linear-progress indeterminate color="primary" />
            <div class="text-center q-mt-sm text-grey-6">Updating order...</div>
        </div>
    </div>
</template>

<style scoped>
.drag-list{border-radius:8px;overflow:hidden}.drag-item{transition:all .2s}.drag-item:hover{background-color:rgba(0,0,0,.02)}.drag-handle{cursor:move;min-width:40px;padding:0 8px}.drag-handle:hover .q-icon{color:var(--q-primary)!important}:deep(.formkit-dnd-is-dragging){background-color:rgba(25,118,210,.05);box-shadow:0 4px 12px rgba(0,0,0,.15);opacity:.7;transform:scale(1.02)}:deep(.formkit-dnd-placeholder){align-items:center;background-color:rgba(25,118,210,.1);border:2px dashed var(--q-primary);border-radius:4px;display:flex;height:72px;justify-content:center;margin:2px 0}:deep(.formkit-dnd-placeholder:before){color:var(--q-primary);content:"Drop here";font-size:14px;font-weight:500}
</style>
