<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import PageCard from '@/components/PageCard.vue'
import { useToolsStore } from '@/stores/tools'
import { TOOL_ICONS } from '@/constants'

const route = useRoute()
const router = useRouter()
const toolsStore = useToolsStore()
const formRef = ref<FormInstance>()

const isEdit = computed(() => route.params.id != null)
const editingTool = computed(() =>
  isEdit.value ? toolsStore.getTool(route.params.id as string) : undefined,
)

const form = reactive({
  id: '',
  name: '',
  description: '',
  url: '',
  icon: 'fa-cog',
})

const rules: FormRules = {
  name: [
    { required: true, message: '请输入工具名称', trigger: 'blur' },
    { max: 30, message: '不超过 30 字符', trigger: 'blur' },
  ],
  url: [{ required: true, message: '请输入跳转地址', trigger: 'blur' }],
}

function handleSubmit() {
  if (!formRef.value) return
  formRef.value.validate((valid) => {
    if (!valid) return
    if (isEdit.value) {
      toolsStore.updateTool(form.id, { ...form })
      ElMessage.success('更新成功')
    } else {
      toolsStore.addTool({ ...form, id: 'custom_' + Date.now() })
      ElMessage.success('添加成功')
    }
    router.push('/tools')
  })
}

function handleCancel() {
  router.back()
}

onMounted(() => {
  if (editingTool.value) {
    Object.assign(form, editingTool.value)
  }
})
</script>

<template>
  <PageCard :title="isEdit ? '编辑自定义工具' : '添加自定义工具'">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      style="max-width: 600px"
    >
      <el-form-item label="工具名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入工具名称" maxlength="30" show-word-limit />
      </el-form-item>

      <el-form-item label="工具描述">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="2"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="跳转地址" prop="url">
        <el-input v-model="form.url" placeholder="相对路径或完整 URL" />
      </el-form-item>

      <el-form-item label="图标">
        <div class="icon-grid">
          <div
            v-for="icon in TOOL_ICONS"
            :key="icon"
            class="icon-option"
            :class="{ selected: form.icon === icon }"
            @click="form.icon = icon"
          >
            <i class="fa" :class="icon" />
          </div>
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSubmit">{{ isEdit ? '保存' : '添加' }}</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </PageCard>
</template>

<style scoped lang="scss">
.icon-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(44px, 1fr));
  gap: 8px;
  max-width: 500px;
}

.icon-option {
  width: 44px;
  height: 44px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 16px;
  color: #606266;

  &:hover {
    border-color: #1890ff;
    color: #1890ff;
  }

  &.selected {
    border-color: #1890ff;
    background: rgba(24, 144, 255, 0.1);
    color: #1890ff;
  }
}
</style>
