<script lang="ts" setup>
import { computed, ref, watch } from 'vue';

import {
  cloneTemplateValue,
  langs,
} from './activity-template-shared';

import {
  Button,
  Input,
  Select,
  TextArea,
} from 'antdv-next';

const props = defineProps<{
  modelValue?: Array<Record<string, any>>;
  type?: string;
}>();

const emit = defineEmits<{
  'update:modelValue': [Array<Record<string, any>>];
}>();

const syncing = ref(false);
const langList = ref<Array<Record<string, any>>>([]);
const pendingLang = ref<string>('');

const availableOptions = computed(() =>
  langs
    .filter((item) => !langList.value.some((langItem) => langItem.lang === item.value))
    .map((item) => ({
      label: item.name,
      value: item.value,
    })),
);

watch(
  () => props.modelValue,
  (value) => {
    syncing.value = true;
    langList.value = cloneTemplateValue(value || []);
    Promise.resolve().then(() => {
      syncing.value = false;
    });
  },
  { deep: true, immediate: true },
);

watch(
  langList,
  (value) => {
    if (syncing.value) {
      return;
    }
    emit('update:modelValue', cloneTemplateValue(value || []));
  },
  { deep: true },
);

function addLang() {
  if (!pendingLang.value) {
    return;
  }
  const matched = langs.find((item) => item.value === pendingLang.value);
  if (!matched) {
    return;
  }
  langList.value.push({
    lang: matched.value,
    name: matched.name,
    value: '',
  });
  pendingLang.value = '';
}

function removeLang(index: number) {
  langList.value.splice(index, 1);
}
</script>

<template>
  <div class="lang-editor">
    <div v-for="(item, index) in langList" :key="`${item.lang}-${index}`" class="lang-item">
      <div class="lang-item__head">
        <span>{{ item.name || item.lang }}</span>
        <Button danger size="small" type="link" @click="removeLang(index)">
          删除
        </Button>
      </div>
      <TextArea
        v-if="type === 'textarea'"
        v-model:value="item.value"
        :rows="4"
        spellcheck="false"
      />
      <Input v-else v-model:value="item.value" />
    </div>

    <div v-if="availableOptions.length > 0" class="lang-editor__toolbar">
      <Select
        v-model:value="pendingLang"
        allow-clear
        placeholder="添加语言"
        style="width: 180px"
        :options="availableOptions"
      />
      <Button @click="addLang">添加</Button>
    </div>
  </div>
</template>

<style scoped>
.lang-editor {
  display: grid;
  gap: 12px;
}

.lang-item {
  display: grid;
  gap: 8px;
}

.lang-item__head {
  align-items: center;
  display: flex;
  justify-content: space-between;
}

.lang-editor__toolbar {
  display: flex;
  gap: 8px;
}
</style>
