<template>
  <n-modal v-model:show="showModal" preset="card" title="添加解析" class="w-600px" :bordered="false">
    <div class="analysis-container h-600px flex flex-col">
      <div class="flex items-center justify-between p-4 border-b border-gray-200">
        <span class="text-18px font-bold text-[#303133]">添加解析</span>
        <n-button v-if="![1, 2, 3].includes(type ?? -1)" type="primary" @click="addCustomOption">
          <template #icon>
            <icon-mdi-plus />
          </template>
          添加自定义选项
        </n-button>
      </div>

      <n-scrollbar class="flex-1 p-4">
        <!-- Types 1, 2, 3: Single, Multiple, True/False -->
        <template v-if="[1, 2, 3].includes(type ?? -1)">
          <div v-for="(item, index) in customOptions" :key="index" class="mb-4">
            <n-card size="small">
              <n-form-item :label="`${item.key}：`" :show-feedback="false">
                <n-input
                  v-model:value="item.value"
                  type="textarea"
                  :placeholder="`请输入${item.key}对应的解析内容`"
                  :rows="3"
                />
              </n-form-item>
            </n-card>
          </div>
        </template>

        <!-- Other types -->
        <template v-else>
          <div class="dynamic-options">
            <div v-for="(item, index) in customOptions" :key="index" class="mb-4 p-2">
              <n-card size="small">
                <n-form ref="formRefs" :model="item" :rules="formRule">
                  <n-form-item path="key" class="w-full mb-4">
                    <div class="flex gap-4 items-center w-full">
                      <n-input v-model:value="item.key" placeholder="请输入选项" />
                      <n-button type="error" ghost @click="removeOption(index)">
                        <template #icon>
                          <icon-mdi-delete />
                        </template>
                      </n-button>
                    </div>
                  </n-form-item>

                  <n-form-item path="value">
                    <n-input
                      v-model:value="item.value"
                      type="textarea"
                      :rows="3"
                      placeholder="请输入解析内容"
                    />
                  </n-form-item>
                </n-form>
              </n-card>
            </div>
          </div>
        </template>
      </n-scrollbar>

      <div class="flex gap-2 justify-end p-4 border-t border-gray-200">
        <n-button @click="hide">取消</n-button>
        <n-button type="primary" :loading="affirmLoading" @click="handleAffirm">确定</n-button>
      </div>
    </div>
  </n-modal>
</template>

<script setup lang="ts">
import { ref, useTemplateRef } from 'vue';
import { useMessage, useDialog } from 'naive-ui';
import type { FormInst, FormRules } from 'naive-ui';
import { type QuestionFromInfo, updateKeywordAnalysisAxios } from '@/service/api/book';
import { myStrToJson } from '@/utils/data';

// Icons need to be handled. Assuming unplugin-icons is set up or I should use a generic one.
// I'll use icon-mdi-plus and icon-mdi-delete assuming standard icon sets.

const message = useMessage();
const dialog = useDialog();

const showModal = ref(false);
const formRefs = useTemplateRef<FormInst[]>('formRefs'); // Note: naive-ui doesn't support array refs automatically in template like element-plus might, but vue 3.5 does.
// However, in loop, we might need to handle validation differently or collect refs manually.
// Actually, for "Other types", we have multiple forms.
// A simpler way is to validate manually or use one form with dynamic fields.
// Let's stick to the structure but handle validation carefully.

const affirmLoading = ref(false);
const questionFromInfo = ref<QuestionFromInfo | undefined>(undefined);
const type = ref<number | undefined>(undefined);

const options = ref<string[]>([]);
const customOptions = ref<{ key: string; value: string }[]>([]);

const formRule: FormRules = {
  key: [{ required: true, message: '选项不能为空', trigger: 'blur' }],
  value: [{ required: true, message: '解析内容不能为空', trigger: 'blur' }],
};

async function handleAffirm() {
  try {
    affirmLoading.value = true;

    if (![1, 2, 3].includes(type.value ?? -1)) {
      // Validate all dynamic forms
      // Since formRefs might not work as array directly in some setups, let's assume we can get them.
      // Or better, just check the data manually since it's simple.
      let valid = true;
      if (Array.isArray(formRefs.value)) {
        for (const form of formRefs.value) {
           await form.validate((errors) => {
             if (errors) valid = false;
           });
        }
      } else if (formRefs.value) {
         // Single form instance? Unlikely with v-for.
         // Vue 3 v-for ref behavior:
         // In Vue 3.2.25+, ref in v-for should work as array if bound to a variable.
      }

      // Fallback manual validation if refs are tricky
      for (const item of customOptions.value) {
        if (!item.key || !item.value) {
           message.error('请填写完整信息');
           affirmLoading.value = false;
           return;
        }
      }
    }

    await updateKeywordAnalysisAxios({
      id: questionFromInfo.value!.id!,
      keywordAnalysis: JSON.stringify(customOptions.value),
    });
    hide();
    message.success('操作成功');
  } catch (error: any) {
    console.error('error====', error);
    message.error(error.msg || '操作失败');
  } finally {
    affirmLoading.value = false;
  }
}

function addCustomOption() {
  customOptions.value.push({
    key: '',
    value: '',
  });
}

function removeOption(index: number) {
  dialog.warning({
    title: '温馨提示',
    content: '删除后不可恢复，您确定删除吗？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      customOptions.value.splice(index, 1);
    },
  });
}

function show(_data: { questionFromInfo?: QuestionFromInfo }) {
  type.value = _data.questionFromInfo?.type ?? undefined;
  options.value = myStrToJson<string[]>(_data.questionFromInfo?.options || '[]') || [];
  questionFromInfo.value = _data.questionFromInfo ?? undefined;

  const savedAnalysis = myStrToJson<{ key: string; value: string }[]>(_data.questionFromInfo?.keywordAnalysis || '[]') || [];
  if (savedAnalysis.length > 0) {
    customOptions.value = savedAnalysis;
  } else {
    if ([1, 2, 3].includes(type.value ?? -1)) {
      customOptions.value = options.value.map((option) => ({ key: option, value: '' }));
    } else {
      customOptions.value = [];
    }
  }

  showModal.value = true;
}

function hide() {
  showModal.value = false;
}

defineExpose({
  show,
  hide,
});
</script>

<style scoped>
.analysis-container {
  /* Using UnoCSS classes in template */
}
</style>
