<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useBookmarkStore } from '@/stores/bookmark'
import { useTagStore } from '@/stores/tag'
import { useDeviceStore } from '@/stores/device'
import { VisibilityType } from '@/types'
import type { Bookmark, CreateBookmarkRequest, UpdateBookmarkRequest } from '@/types'

const props = defineProps<{
  visible: boolean
  bookmark: Bookmark | null
}>()

const emit = defineEmits<{
  'update:visible': [value: boolean]
  close: []
}>()

const bookmarkStore = useBookmarkStore()
const tagStore = useTagStore()
const deviceStore = useDeviceStore()

const loading = ref(false)
const formRef = ref()

const form = reactive({
  title: '',
  url: '',
  description: '',
  tags: [] as string[],
  visibility: VisibilityType.Public,
  allowedDevices: [] as string[]
})

const isEdit = computed(() => !!props.bookmark)
const title = computed(() => isEdit.value ? '编辑书签' : '添加书签')
const allTags = computed(() => tagStore.tagNames)
const devices = computed(() => deviceStore.devices)

const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  url: [
    { required: true, message: '请输入URL', trigger: 'blur' },
    { type: 'url', message: '请输入正确的URL格式', trigger: 'blur' }
  ]
}

watch(() => props.visible, async (val) => {
  if (val) {
    await deviceStore.fetchDevices()
    if (props.bookmark) {
      form.title = props.bookmark.title
      form.url = props.bookmark.url
      form.description = props.bookmark.description || ''
      form.tags = [...props.bookmark.tags]
      form.visibility = props.bookmark.visibility
      form.allowedDevices = props.bookmark.allowedDevices || []
    } else {
      resetForm()
    }
  }
})

function resetForm() {
  form.title = ''
  form.url = ''
  form.description = ''
  form.tags = []
  form.visibility = VisibilityType.Public
  form.allowedDevices = []
}

function handleClose() {
  emit('update:visible', false)
  emit('close')
  resetForm()
}

async function handleSubmit() {
  try {
    await formRef.value.validate()
  } catch {
    return
  }

  loading.value = true
  try {
    if (isEdit.value && props.bookmark) {
      const data: UpdateBookmarkRequest = {
        title: form.title,
        url: form.url,
        description: form.description || undefined,
        tags: form.tags,
        visibility: form.visibility,
        allowedDevices: form.visibility === VisibilityType.Specified ? form.allowedDevices : undefined
      }
      const response = await bookmarkStore.updateBookmark(props.bookmark.id, data)
      if (response.success) {
        ElMessage.success('更新成功')
        handleClose()
      } else {
        ElMessage.error(response.message || '更新失败')
      }
    } else {
      const data: CreateBookmarkRequest = {
        title: form.title,
        url: form.url,
        description: form.description || undefined,
        tags: form.tags,
        visibility: form.visibility,
        allowedDevices: form.visibility === VisibilityType.Specified ? form.allowedDevices : undefined
      }
      const response = await bookmarkStore.createBookmark(data)
      if (response.success) {
        ElMessage.success('添加成功')
        await tagStore.fetchTags()
        handleClose()
      } else {
        ElMessage.error(response.message || '添加失败')
      }
    }
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '操作失败')
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <el-dialog
    :model-value="visible"
    :title="title"
    width="560px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入书签标题" />
      </el-form-item>

      <el-form-item label="URL" prop="url">
        <el-input v-model="form.url" placeholder="请输入网址" />
      </el-form-item>

      <el-form-item label="描述">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入描述（可选）"
        />
      </el-form-item>

      <el-form-item label="标签">
        <el-select
          v-model="form.tags"
          multiple
          filterable
          allow-create
          default-first-option
          placeholder="选择或创建标签"
          style="width: 100%"
        >
          <el-option
            v-for="tag in allTags"
            :key="tag"
            :label="tag"
            :value="tag"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="可见性">
        <el-radio-group v-model="form.visibility">
          <el-radio :value="VisibilityType.Public">公开（所有设备可见）</el-radio>
          <el-radio :value="VisibilityType.Private">私密（仅管理员设备可见）</el-radio>
          <el-radio :value="VisibilityType.Specified">指定设备</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item v-if="form.visibility === VisibilityType.Specified" label="允许设备">
        <el-select
          v-model="form.allowedDevices"
          multiple
          placeholder="选择允许查看的设备"
          style="width: 100%"
        >
          <el-option
            v-for="device in devices"
            :key="device.id"
            :label="device.deviceName"
            :value="device.id"
          >
            <span>{{ device.deviceName }}</span>
            <el-tag v-if="device.isAdmin" size="small" type="warning" class="ml-sm">
              管理员
            </el-tag>
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">
        {{ isEdit ? '保存' : '添加' }}
      </el-button>
    </template>
  </el-dialog>
</template>

