<script setup>
import { ref, reactive, computed } from "vue";
import { m, q, useAsyncData } from "#imports";
import { useQuasar } from "quasar";
import { useI18n } from "vue-i18n";
const $q = useQuasar();
const { t } = useI18n();
const { app } = await q({ app: { languages: true } });
const splitterModel = ref(62);
const filter = ref("");
const { data: all, refresh } = await useAsyncData("translate", () => {
  return q({ allTranslate: true }).then((res) => res.allTranslate);
});
const filteredRows = computed(() => {
  if (!filter.value || !all.value) return all.value;
  const searchTerm = filter.value.toLowerCase();
  return all.value.filter((row) => {
    if (row.name?.toLowerCase().includes(searchTerm)) return true;
    for (const language of app.languages) {
      if (row[language.value]?.toLowerCase().includes(searchTerm)) return true;
    }
    return false;
  });
});
const obj = reactive({
  name: "",
  _originalName: ""
  // 用於追蹤原始名稱（編輯模式）
});
const isEditMode = computed(() => !!obj._originalName);
const onSelectRow = (row) => {
  obj.name = row.name;
  obj._originalName = row.name;
  for (const language of app.languages) {
    obj[language.value] = row[language.value] || "";
  }
};
const onClearForm = () => {
  obj.name = "";
  obj._originalName = "";
  for (const language of app.languages) {
    obj[language.value] = "";
  }
};
const onSave = async () => {
  if (isEditMode.value) {
    for (const language of app.languages) {
      await m("updateTranslate", {
        name: obj._originalName,
        language: language.value,
        value: obj[language.value] || ""
      });
    }
    $q.notify({
      message: t("Update success"),
      color: "positive",
      icon: "check"
    });
  } else {
    await m("addTranslate", {
      data: {
        name: obj.name,
        values: app.languages.map((language) => {
          return {
            language: language.value,
            value: obj[language.value] || ""
          };
        })
      }
    });
    $q.notify({
      message: t("Save success"),
      color: "positive",
      icon: "check"
    });
  }
  onClearForm();
  await refresh();
};
const columns = [
  {
    label: "",
    name: "_delete"
  },
  {
    label: t("Name"),
    name: "name",
    field: "name",
    align: "left",
    sortable: true
  }
];
for (const language of app.languages) {
  columns.push({
    label: language.name,
    name: language.value,
    align: "left"
  });
}
const onDelete = async (name) => {
  $q.dialog({
    title: t("Confirm"),
    message: t("Are you sure you want to delete this item?"),
    cancel: true,
    persistent: true
  }).onOk(async () => {
    if (await m("deleteTranslate", { name })) {
      $q.notify({
        message: t("Delete success"),
        color: "positive",
        icon: "check"
      });
      if (obj._originalName === name) {
        onClearForm();
      }
      await refresh();
    }
  });
};
</script>

<template>
    <l-page>
        <l-card>
            <q-splitter v-model="splitterModel" style="height:680px">
                <template #before>
                    <q-table 
                        :rows="filteredRows" 
                        flat 
                        :rows-per-page-options="[0]" 
                        :columns="columns" 
                        dense 
                        separator="cell"
                        :bordered="false"
                    >
                        <template #top>
                            <q-input 
                                v-model="filter" 
                                dense 
                                outlined
                                :placeholder="t('Search...')"
                                clearable
                                class="full-width"
                            >
                                <template #prepend>
                                    <q-icon name="sym_o_search" />
                                </template>
                            </q-input>
                        </template>
                        <template #body="props">
                            <q-tr 
                                :props="props" 
                                :class="{ 'bg-blue-1': obj._originalName === props.row.name }"
                                class="cursor-pointer"
                                @click="onSelectRow(props.row)"
                            >
                                <q-td key="_delete" auto-width @click.stop>
                                    <q-btn dense flat round icon="sym_o_delete" color="negative"
                                        @click="onDelete(props.row.name)">
                                        <q-tooltip>{{ t("Delete") }}</q-tooltip>
                                    </q-btn>
                                </q-td>
                                <q-td key="name" style="max-width: 200px;">
                                    <div class="text-weight-medium ellipsis">
                                        {{ props.row.name }}
                                        <q-tooltip v-if="props.row.name?.length > 25" anchor="top middle" self="bottom middle">
                                            {{ props.row.name }}
                                        </q-tooltip>
                                    </div>
                                </q-td>
                                <q-td :key="language.value" v-for="language in app.languages" :props="props" style="max-width: 250px;">
                                    <div class="text-grey-8 ellipsis-2-lines">
                                        {{ props.row[language.value] || '-' }}
                                        <q-tooltip v-if="props.row[language.value]?.length > 50" anchor="top middle" self="bottom middle" max-width="400px">
                                            <div class="text-pre-wrap">{{ props.row[language.value] }}</div>
                                        </q-tooltip>
                                    </div>
                                </q-td>
                            </q-tr>
                        </template>
                    </q-table>
                </template>
                <template #after>
                    <div class="q-pa-md">
                        <div class="row items-center q-mb-md">
                            <div class="text-h6">
                                {{ isEditMode ? t("Edit Translation") : t("Add Translation") }}
                            </div>
                            <q-space />
                            <q-btn 
                                v-if="isEditMode" 
                                flat 
                                dense 
                                icon="sym_o_add" 
                                :label="t('New')" 
                                color="primary"
                                @click="onClearForm"
                            >
                                <q-tooltip>{{ t("Clear form and add new") }}</q-tooltip>
                            </q-btn>
                        </div>
                        <l-form :bordered="false" @submit="onSave">
                            <l-input 
                                label="Name" 
                                required 
                                v-model.trim="obj.name" 
                                clearable
                                :disable="isEditMode"
                                :hint="isEditMode ? t('Name cannot be changed in edit mode') : ''"
                            />
                            <l-input 
                                v-for="language in app.languages" 
                                :key="language.value"
                                :label="language.name" 
                                v-model="obj[language.value]"
                                type="textarea"
                            />
                            <template #buttons>
                                <q-btn 
                                    v-if="isEditMode"
                                    flat 
                                    :label="t('Cancel')" 
                                    @click="onClearForm"
                                    class="q-mr-sm"
                                />
                                <l-save-btn :label="isEditMode ? t('Update') : t('Save')" />
                            </template>
                        </l-form>
                    </div>
                </template>
            </q-splitter>
        </l-card>
    </l-page>
</template>

<style scoped>
.ellipsis{white-space:nowrap}.ellipsis,.ellipsis-2-lines{overflow:hidden;text-overflow:ellipsis}.ellipsis-2-lines{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;word-break:break-word}
</style>
