<script setup lang="ts">
import type { CategoryNode } from './CategoryTreeNode.vue'
import type { CardDetail } from './CardDetailModal.vue'
import { request } from '~/utils/http/factory'

const CARD_TYPES = [
  { value: 'image-text', label: '图文', icon: 'lucide:image-plus' },
  { value: 'image', label: '图片', icon: 'lucide:image' },
  { value: 'text', label: '纯文本', icon: 'lucide:text' },
  { value: 'portfolio', label: '图集', icon: 'lucide:layout-grid' },
  { value: 'project', label: '项目', icon: 'lucide:folder-kanban' },
] as const

const ASPECT_PRESETS = [
  { label: '竖图 3:4', value: 0.75 },
  { label: '方形 1:1', value: 1.0 },
  { label: '横图 4:3', value: 1.33 },
  { label: '宽屏 16:9', value: 1.78 },
]

const props = defineProps<{
  mode: 'create' | 'edit'
  card: CardDetail | null   // null for create, prefilled for edit
  categories: CategoryNode[]
  visible: boolean
}>()

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

// ── Tag fetching ──

interface TagItem { id: number; name: string; slug: string }
const allTags = ref<TagItem[]>([])
const tagsLoaded = ref(false)

async function loadTags() {
  if (tagsLoaded.value) return
  try {
    const raw = await request<{ code: number; data: { list: TagItem[] } }>('/api/tags')
    allTags.value = raw.data.list
    tagsLoaded.value = true
  } catch { /* ignore */ }
}

// ── Form state ──

const formType = ref<string>('image-text')
const title = ref('')
const description = ref('')
const aspectRatio = ref<number | null>(0.75)
const categoryId = ref<string | null>(null)
const imageUrl = ref('')
const imageUrls = ref<string[]>([''])
const selectedTagIds = ref<number[]>([])

const saving = ref(false)
const error = ref('')

// ── Computed ──

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

const titleText = computed(() => isEdit.value ? '编辑卡片' : '新增卡片')

const needsImage = computed(() =>
  formType.value === 'image' || formType.value === 'image-text' || formType.value === 'project'
)

const needsMultiImage = computed(() => formType.value === 'portfolio')

const needsTags = computed(() => formType.value === 'project')

const needsDescription = computed(() =>
  formType.value === 'text' || formType.value === 'image-text' || formType.value === 'portfolio' || formType.value === 'project'
)

// Flatten category tree for select
interface FlatCat { id: string; name: string; depth: number }
const flatCategories = computed<FlatCat[]>(() => {
  const result: FlatCat[] = [{ id: '', name: '（无分类）', depth: 0 }]
  function walk(nodes: CategoryNode[], depth: number) {
    for (const n of nodes) {
      if (n.id === '__uncategorized__') continue
      result.push({ id: n.id, name: n.name, depth })
      if (n.children) walk(n.children, depth + 1)
    }
  }
  walk(props.categories, 1)
  return result
})

const availableTags = computed(() =>
  allTags.value.filter(t => !selectedTagIds.value.includes(t.id))
)

// ── Init ──

watch(() => props.visible, (v) => {
  if (!v) return
  error.value = ''
  saving.value = false

  if (props.mode === 'edit' && props.card) {
    formType.value = props.card.type
    title.value = props.card.title
    description.value = props.card.description ?? ''
    aspectRatio.value = props.card.aspectRatio
    categoryId.value = props.card.categoryId ?? null
    imageUrl.value = props.card.image ?? ''
    imageUrls.value = props.card.images && props.card.images.length > 0
      ? [...props.card.images]
      : ['']
    selectedTagIds.value = []
  } else {
    formType.value = 'image-text'
    title.value = ''
    description.value = ''
    aspectRatio.value = 0.75
    categoryId.value = null
    imageUrl.value = ''
    imageUrls.value = ['']
    selectedTagIds.value = []
  }

  loadTags()
})

// ── File upload ──

async function onFileUpload(e: Event) {
  const file = (e.target as HTMLInputElement).files?.[0]
  if (!file) return
  const form = new FormData()
  form.append('file', file)
  try {
    const raw = await $fetch<{ code: number; data: { url: string } }>('/api/file/upload', {
      method: 'POST',
      body: form,
    })
    imageUrl.value = raw.data.url
  } catch {
    error.value = '图片上传失败'
  }
}

// ── Image URLs helpers ──

function addImageUrl() {
  imageUrls.value.push('')
}

function removeImageUrl(idx: number) {
  if (imageUrls.value.length <= 1) return
  imageUrls.value.splice(idx, 1)
}

// ── Tag toggle ──

function toggleTag(tagId: number) {
  const idx = selectedTagIds.value.indexOf(tagId)
  if (idx >= 0) {
    selectedTagIds.value.splice(idx, 1)
  } else {
    selectedTagIds.value.push(tagId)
  }
}

// ── Submit ──

async function onSubmit() {
  error.value = ''

  if (!title.value.trim()) { error.value = '请输入标题'; return }
  if (needsImage.value && !imageUrl.value.trim()) { error.value = '请输入图片 URL'; return }
  if (needsMultiImage.value) {
    const validUrls = imageUrls.value.filter(u => u.trim())
    if (validUrls.length === 0) { error.value = '请至少添加一张图片'; return }
  }

  saving.value = true

  const body: Record<string, unknown> = {
    type: formType.value,
    title: title.value.trim(),
    description: needsDescription.value ? (description.value.trim() || null) : null,
    aspectRatio: aspectRatio.value,
    categoryId: categoryId.value || null,
  }

  // Images
  if (needsMultiImage.value) {
    const validUrls = imageUrls.value.filter(u => u.trim())
    body.images = validUrls.map((url, i) => ({ url: url.trim(), sortOrder: i }))
  } else if (needsImage.value) {
    body.images = [{ url: imageUrl.value.trim(), sortOrder: 0 }]
  }

  // Tags
  if (needsTags.value) {
    body.tagIds = [...selectedTagIds.value]
  }

  try {
    if (isEdit.value && props.card) {
      await request(`/api/cards/${props.card.id}`, { method: 'PUT', body })
    } else {
      await request('/api/cards', { method: 'POST', body })
    }
    emit('saved')
    emit('update:visible', false)
  } catch (err: any) {
    error.value = err?.data?.message ?? err?.message ?? '保存失败'
  } finally {
    saving.value = false
  }
}
</script>

<template>
  <BoDialog
    :show="visible"
    :mask-can-close="!saving"
    :style="{ width: '480px' }"
    @update:show="(v: boolean) => emit('update:visible', v)"
  >
    <div class="card-form">
      <!-- Header -->
      <div class="cf-header">
        <h2 class="cf-title">{{ titleText }}</h2>
        <button type="button" class="cf-close" :disabled="saving" @click="emit('update:visible', false)">
          <Icon name="lucide:x" />
        </button>
      </div>

      <!-- Body -->
      <div class="cf-body">
        <div v-if="error" class="cf-error">{{ error }}</div>

        <!-- Type selector -->
        <div class="cf-field">
          <label class="cf-label">类型</label>
          <div class="cf-type-grid">
            <button
              v-for="ct in CARD_TYPES"
              :key="ct.value"
              type="button"
              class="cf-type-btn"
              :class="{ active: formType === ct.value }"
              :disabled="saving"
              @click="formType = ct.value"
            >
              <Icon :name="ct.icon" class="cf-type-icon" />
              <span>{{ ct.label }}</span>
            </button>
          </div>
        </div>

        <!-- Title -->
        <div class="cf-field">
          <label class="cf-label"><span class="cf-required">*</span> 标题 <span class="cf-count">{{ title.length }}/60</span></label>
          <input
            v-model="title"
            type="text"
            class="cf-input"
            placeholder="卡片标题"
            :disabled="saving"
            maxlength="60"
            @keyup.enter="onSubmit"
          />
        </div>

        <!-- Category -->
        <div class="cf-field">
          <label class="cf-label">分类</label>
          <select v-model="categoryId" class="cf-select" :disabled="saving">
            <option
              v-for="fc in flatCategories"
              :key="fc.id"
              :value="fc.id || null"
            >
              {{ '\u00A0\u00A0'.repeat(fc.depth) }}{{ fc.name }}
            </option>
          </select>
        </div>

        <!-- Image URL (single) -->
        <div v-if="needsImage" class="cf-field">
          <label class="cf-label"><span class="cf-required">*</span> 图片</label>
          <div class="cf-image-input-row">
            <input
              v-model="imageUrl"
              type="url"
              class="cf-input"
              placeholder="粘贴图片 URL 或点击上传"
              :disabled="saving"
            />
            <label class="cf-upload-btn" :class="{ disabled: saving }">
              <Icon name="lucide:upload" />
              <input
                type="file"
                accept="image/*"
                :disabled="saving"
                hidden
                @change="onFileUpload"
              />
            </label>
          </div>
          <div v-if="imageUrl" class="cf-image-preview">
            <img :src="imageUrl" alt="预览" @error="(e) => { (e.target as HTMLImageElement).style.display = 'none' }" />
          </div>
        </div>

        <!-- Image URLs (multi, for portfolio) -->
        <div v-if="needsMultiImage" class="cf-field">
          <label class="cf-label"><span class="cf-required">*</span> 图片列表</label>
          <div class="cf-image-list">
            <div v-for="(_, idx) in imageUrls" :key="idx" class="cf-image-row">
              <input
                v-model="imageUrls[idx]"
                type="url"
                class="cf-input"
                placeholder="https://..."
                :disabled="saving"
              />
              <button
                v-if="imageUrls.length > 1"
                type="button"
                class="cf-image-remove"
                :disabled="saving"
                @click="removeImageUrl(idx)"
              >
                <Icon name="lucide:x" />
              </button>
            </div>
            <div v-if="imageUrls.some(u => u.trim())" class="cf-image-previews">
              <div
                v-for="(url, idx) in imageUrls.filter(u => u.trim())"
                :key="idx"
                class="cf-image-preview cf-image-preview--sm"
              >
                <img :src="url" alt="预览" @error="(e) => { (e.target as HTMLImageElement).style.display = 'none' }" />
              </div>
            </div>
          </div>
          <button type="button" class="cf-add-btn" :disabled="saving" @click="addImageUrl">
            <Icon name="lucide:plus" />
            <span>添加图片</span>
          </button>
        </div>

        <!-- Description -->
        <div v-if="needsDescription" class="cf-field">
          <label class="cf-label">描述 <span class="cf-count">{{ description.length }}/200</span></label>
          <textarea
            v-model="description"
            class="cf-textarea"
            rows="3"
            placeholder="描述内容..."
            :disabled="saving"
            maxlength="200"
          ></textarea>
        </div>

        <!-- Aspect Ratio -->
        <div class="cf-field">
          <label class="cf-label">宽高比</label>
          <div class="cf-ratio-row">
            <button
              v-for="r in ASPECT_PRESETS"
              :key="r.value"
              type="button"
              class="cf-ratio-btn"
              :class="{ active: aspectRatio === r.value }"
              :disabled="saving"
              @click="aspectRatio = r.value"
            >
              {{ r.label }}
            </button>
            <input
              v-model.number="aspectRatio"
              type="number"
              class="cf-input cf-input-sm"
              step="0.01"
              min="0.1"
              max="5"
              placeholder="自定义"
              :disabled="saving"
            />
          </div>
        </div>

        <!-- Tags (project) -->
        <div v-if="needsTags" class="cf-field">
          <label class="cf-label">标签</label>
          <div v-if="selectedTagIds.length > 0" class="cf-tags-selected">
            <span
              v-for="tid in selectedTagIds"
              :key="tid"
              class="cf-tag-chip"
            >
              {{ allTags.find(t => t.id === tid)?.name ?? `#${tid}` }}
              <button type="button" class="cf-tag-remove" :disabled="saving" @click="toggleTag(tid)">
                <Icon name="lucide:x" />
              </button>
            </span>
          </div>
          <div v-if="availableTags.length > 0" class="cf-tags-available">
            <span class="cf-label-sm">可选标签</span>
            <div class="cf-tags-pool">
              <button
                v-for="tag in availableTags"
                :key="tag.id"
                type="button"
                class="cf-tag-option"
                :disabled="saving"
                @click="toggleTag(tag.id)"
              >
                {{ tag.name }}
              </button>
            </div>
          </div>
          <span v-if="allTags.length === 0 && tagsLoaded" class="cf-hint">暂无可用标签，请先在标签管理中创建</span>
        </div>
      </div>

      <!-- Footer -->
      <div class="cf-footer">
        <button type="button" class="cf-btn cf-btn-cancel" :disabled="saving" @click="emit('update:visible', false)">
          取消
        </button>
        <button type="button" class="cf-btn cf-btn-primary" :disabled="saving" @click="onSubmit">
          {{ saving ? '保存中…' : (isEdit ? '保存修改' : '创建卡片') }}
        </button>
      </div>
    </div>
  </BoDialog>
</template>

<style scoped>
.card-form {
  display: flex;
  flex-direction: column;
  max-height: 85vh;
  background: var(--color-canvas, #faf9f5);
  border-radius: 12px;
  overflow: hidden;
}

/* ── Header ── */

.cf-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 18px 24px 0;
}

.cf-title {
  font-family: var(--font-display);
  font-size: 18px;
  font-weight: 500;
  color: var(--color-ink);
  margin: 0;
}

.cf-close {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  background: none;
  border-radius: 8px;
  color: var(--color-muted);
  cursor: pointer;
  transition: all 0.12s ease;
}

.cf-close :deep(svg) { width: 18px; height: 18px; }
.cf-close:hover { background: var(--color-surface-soft); color: var(--color-ink); }

/* ── Body ── */

.cf-body {
  padding: 18px 24px;
  display: flex;
  flex-direction: column;
  gap: 14px;
  overflow-y: auto;
}

.cf-error {
  padding: 10px 14px;
  background: rgba(198, 69, 69, 0.08);
  color: var(--color-error, #c64545);
  border-radius: 8px;
  font-size: 13px;
}

.cf-field {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.cf-label {
  font-size: 13px;
  font-weight: 500;
  color: var(--color-body);
}

.cf-required {
  color: var(--color-error, #c64545);
  font-weight: 600;
}

.cf-count {
  font-weight: 400;
  font-size: 11px;
  color: var(--color-muted-soft);
  margin-left: auto;
}

.cf-label-sm {
  font-size: 11px;
  color: var(--color-muted);
  margin-bottom: 2px;
}

.cf-input,
.cf-select,
.cf-textarea {
  width: 100%;
  padding: 9px 13px;
  font-size: 14px;
  color: var(--color-ink);
  background: var(--color-canvas, #faf9f5);
  border: 1px solid var(--color-hairline);
  border-radius: 8px;
  outline: none;
  transition: border-color 0.15s ease, box-shadow 0.15s ease;
  font-family: var(--font-body);
}

.cf-input:focus,
.cf-select:focus,
.cf-textarea:focus {
  border-color: var(--color-primary);
  box-shadow: 0 0 0 3px rgba(204, 120, 92, 0.15);
}

.cf-input-sm {
  width: 120px;
}

.cf-select {
  cursor: pointer;
  appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%236c6a64' stroke-width='2'%3E%3Cpath d='M6 9l6 6 6-6'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 12px center;
  padding-right: 36px;
}

.cf-textarea {
  resize: vertical;
  min-height: 70px;
  padding: 10px 13px;
  line-height: 1.5;
}

.cf-hint {
  font-size: 11px;
  color: var(--color-muted-soft);
  line-height: 1.4;
}

/* ── Image upload ── */

.cf-image-input-row {
  display: flex;
  gap: 8px;
}

.cf-image-input-row .cf-input {
  flex: 1;
}

.cf-upload-btn {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed var(--color-hairline);
  border-radius: 8px;
  cursor: pointer;
  color: var(--color-muted);
  transition: all 0.15s ease;
  flex-shrink: 0;
}

.cf-upload-btn :deep(svg) { width: 18px; height: 18px; }
.cf-upload-btn:hover { border-color: var(--color-primary); color: var(--color-primary); }
.cf-upload-btn.disabled { opacity: 0.5; cursor: not-allowed; }

.cf-image-preview {
  width: 100%;
  aspect-ratio: 16 / 9;
  border-radius: 8px;
  overflow: hidden;
  background: var(--color-surface-soft);
  border: 1px solid var(--color-hairline);
}

.cf-image-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.cf-image-previews {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(60px, 1fr));
  gap: 6px;
}

.cf-image-preview--sm {
  aspect-ratio: 1;
  border-radius: 6px;
  overflow: hidden;
  background: var(--color-surface-soft);
  border: 1px solid var(--color-hairline);
}

.cf-image-preview--sm img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* ── Aspect ratio presets ── */

.cf-ratio-row {
  display: flex;
  gap: 6px;
  align-items: center;
  flex-wrap: wrap;
}

.cf-ratio-btn {
  height: 34px;
  padding: 0 12px;
  font-size: 12px;
  font-weight: 500;
  border-radius: 8px;
  border: 1px solid var(--color-hairline);
  background: var(--color-canvas);
  color: var(--color-muted);
  cursor: pointer;
  transition: all 0.12s ease;
}

.cf-ratio-btn:hover {
  border-color: var(--color-muted);
  color: var(--color-body);
}

.cf-ratio-btn.active {
  border-color: var(--color-primary);
  background: rgba(204, 120, 92, 0.08);
  color: var(--color-primary);
}

.cf-ratio-row .cf-input-sm {
  width: 80px;
  height: 34px;
}

/* ── Type grid ── */

.cf-type-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 6px;
}

.cf-type-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  padding: 10px 4px;
  border-radius: 8px;
  border: 1px solid var(--color-hairline);
  background: var(--color-canvas);
  cursor: pointer;
  font-size: 11px;
  font-weight: 500;
  color: var(--color-muted);
  transition: all 0.15s ease;
}

.cf-type-btn:hover {
  border-color: var(--color-muted);
  color: var(--color-body);
}

.cf-type-btn.active {
  border-color: var(--color-primary);
  background: rgba(204, 120, 92, 0.08);
  color: var(--color-primary);
}

.cf-type-icon {
  width: 18px;
  height: 18px;
}

/* ── Image list ── */

.cf-image-list {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.cf-image-row {
  display: flex;
  gap: 6px;
  align-items: center;
}

.cf-image-row .cf-input {
  flex: 1;
}

.cf-image-remove {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid var(--color-hairline);
  background: var(--color-canvas);
  border-radius: 6px;
  color: var(--color-muted);
  cursor: pointer;
  flex-shrink: 0;
  transition: all 0.12s ease;
}

.cf-image-remove :deep(svg) { width: 14px; height: 14px; }
.cf-image-remove:hover { border-color: var(--color-error); color: var(--color-error); }

.cf-add-btn {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  padding: 6px 12px;
  font-size: 12px;
  font-weight: 500;
  border-radius: 6px;
  border: 1px dashed var(--color-hairline);
  background: none;
  color: var(--color-muted);
  cursor: pointer;
  transition: all 0.15s ease;
}

.cf-add-btn :deep(svg) { width: 14px; height: 14px; }
.cf-add-btn:hover { border-color: var(--color-primary); color: var(--color-primary); }

/* ── Tags ── */

.cf-tags-selected {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.cf-tag-chip {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 4px 10px;
  font-size: 12px;
  font-weight: 500;
  border-radius: 9999px;
  background: var(--color-primary);
  color: var(--color-on-primary, #fff);
}

.cf-tag-remove {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 16px;
  height: 16px;
  border: none;
  background: rgba(255,255,255,0.2);
  border-radius: 50%;
  cursor: pointer;
  color: inherit;
  padding: 0;
}

.cf-tag-remove :deep(svg) { width: 10px; height: 10px; }

.cf-tags-available {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.cf-tags-pool {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.cf-tag-option {
  padding: 3px 10px;
  font-size: 12px;
  font-weight: 500;
  border-radius: 9999px;
  border: 1px solid var(--color-hairline);
  background: var(--color-canvas);
  color: var(--color-body);
  cursor: pointer;
  transition: all 0.12s ease;
}

.cf-tag-option:hover {
  border-color: var(--color-primary);
  color: var(--color-primary);
}

/* ── Footer ── */

.cf-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding: 14px 24px;
  border-top: 1px solid var(--color-hairline);
  background: var(--color-surface-soft);
}

.cf-btn {
  height: 38px;
  padding: 0 18px;
  font-size: 14px;
  font-weight: 500;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.15s ease;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.cf-btn:disabled { opacity: 0.5; cursor: not-allowed; }

.cf-btn-cancel {
  color: var(--color-body);
  background: var(--color-canvas);
  border: 1px solid var(--color-hairline);
}

.cf-btn-cancel:hover:not(:disabled) { background: var(--color-surface-soft); }

.cf-btn-primary {
  color: var(--color-on-primary, #fff);
  background: var(--color-primary);
  border: none;
}

.cf-btn-primary:hover:not(:disabled) { background: var(--color-primary-active, #b5654f); }
</style>
