<script setup>
import { computed, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { storeToRefs } from 'pinia'

import { useLinksStore } from '@/stores/links'

const linksStore = useLinksStore()
const { allTags } = storeToRefs(linksStore)

// 确保 store 已加载
linksStore.ensureLoaded()

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({}),
  },
  mode: {
    type: String,
    default: 'create',
  },
})

const emit = defineEmits(['submit', 'cancel'])

const formRef = ref()

const form = reactive({
  title: '',
  url: '',
  description: '',
  icon: '',
  tags: [],
  projectIds: [],
  order: 0,
})

const isEdit = computed(() => props.mode === 'edit')

function populateForm(value) {
  form.title = value.title ?? ''
  form.url = value.url ?? ''
  form.description = value.description ?? ''
  form.icon = value.icon ?? ''
  form.tags = Array.isArray(value.tags) ? [...value.tags] : []
  form.projectIds = Array.isArray(value.projectIds) ? [...value.projectIds] : []
  form.order = value.order ?? 0
}

watch(
  () => props.modelValue,
  (value) => {
    populateForm(value ?? {})
  },
  { immediate: true, deep: true }
)

const rules = {
  title: [
    {
      required: true,
      message: '请输入标题',
      trigger: 'blur',
    },
  ],
  url: [
    {
      required: true,
      message: '请输入合法的链接地址',
      trigger: 'blur',
    },
    {
      validator: (_, value, callback) => {
        if (!value) return callback()
        try {
          new URL(value)
          callback()
        } catch {
          callback(new Error('链接格式不合法'))
        }
      },
      trigger: 'blur',
    },
  ],
}

async function handleSubmit() {
  try {
    await formRef.value.validate()
    emit('submit', {
      ...form,
      tags: form.tags.filter(Boolean),
      projectIds: form.projectIds.filter(Boolean),
    })
  } catch (error) {
    if (error) {
      ElMessage.error('保存前请先修复校验错误')
    }
  }
}
</script>

<template>
  <el-form ref="formRef" :model="form" :rules="rules" label-position="top">
    <el-form-item label="标题" prop="title">
      <el-input v-model="form.title" placeholder="输入标题" />
    </el-form-item>

    <el-form-item label="链接地址" prop="url">
      <el-input v-model="form.url" placeholder="https://example.com" />
    </el-form-item>

    <el-form-item label="描述" prop="description">
      <el-input
        v-model="form.description"
        type="textarea"
        placeholder="这个链接有什么用？"
        :rows="3"
      />
    </el-form-item>

    <el-form-item label="标签">
      <el-select
        v-model="form.tags"
        multiple
        :reserve-keyword="false"
        filterable
        allow-create
        default-first-option
        placeholder="添加标签"
      >
        <el-option v-for="tag in allTags" :key="tag" :label="tag" :value="tag" />
      </el-select>
    </el-form-item>

    <el-form-item label="自定义图标地址">
      <el-input v-model="form.icon" placeholder="可选的 favicon 链接" />
    </el-form-item>

    <el-form-item label="排序号">
      <el-input-number
        v-model="form.order"
        :min="0"
        :step="1"
        placeholder="数字越小越靠前"
        style="width: 100%"
      />
      <div class="form-hint">
        数字越小，排序越靠前。默认为 0。
      </div>
    </el-form-item>

    <div class="form-actions">
      <el-button @click="emit('cancel')">取消</el-button>
      <el-button type="primary" @click="handleSubmit">{{ isEdit ? '保存修改' : '新增书签' }}</el-button>
    </div>
  </el-form>
</template>

<style scoped>
.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

.form-hint {
  font-size: 12px;
  color: var(--color-text-muted);
  margin-top: 4px;
}
</style>

