<script setup lang="ts">
import { readError } from '@/shared/utils/error'
import { ElMessage } from 'element-plus'
import { ref, watch } from 'vue'

import { uploadAdminFile } from '@/shared/api/files'
import {
  defaultHomeBanners,
  mergeHomeConfig,
  type HomeBannerSlide,
} from '@/features/listings/api/homeConfig'
import { updateSystemConfig, type SystemConfig } from '@/features/admin/api/systemConfigs'
import { safeParseJSON } from '@/shared/utils/json'

const props = defineProps<{
  modelValue: boolean
  config: SystemConfig
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', val: boolean): void
  (e: 'saved'): void
}>()

const submitting = ref(false)
const description = ref('')
const homeBannersDraft = ref<HomeBannerSlide[]>([])
const uploadingBannerIndex = ref<number | null>(null)

watch(
  () => props.modelValue,
  val => {
    if (val) {
      homeBannersDraft.value = parseHomeBanners(props.config.value)
      description.value = props.config.description || ''
    }
  },
  { immediate: true }
)

function parseHomeBanners(raw: string) {
  const parsed = safeParseJSON(raw, defaultHomeBanners)
  return cloneHomeBanners(mergeHomeConfig({ banners: Array.isArray(parsed) ? parsed : [] }).banners)
}

function cloneHomeBanners(banners: HomeBannerSlide[]) {
  return JSON.parse(JSON.stringify(banners)) as HomeBannerSlide[]
}

function addHomeBanner() {
  homeBannersDraft.value.push({
    eyebrow: '首页推荐',
    title: '',
    badge: 'NEW',
    pill: '',
    tone: 'blue',
    image_url: '',
  })
}

function removeHomeBanner(index: number) {
  homeBannersDraft.value.splice(index, 1)
}

function resetHomeBanners() {
  homeBannersDraft.value = cloneHomeBanners(defaultHomeBanners)
}

async function handleHomeBannerUpload(event: Event, index: number) {
  const input = event.target as HTMLInputElement
  const file = input.files?.[0]
  input.value = ''
  if (!file) return
  uploadingBannerIndex.value = index
  try {
    const uploaded = await uploadAdminFile(file, 'home-banner')
    const banner = homeBannersDraft.value[index]
    if (banner) {
      banner.image_url = uploaded.url
      if (!banner.title) {
        banner.title = banner.eyebrow || '首页轮播图'
      }
    }
    ElMessage.success('图片已上传')
  } catch (error) {
    ElMessage.error(readError(error, '图片上传失败'))
  } finally {
    uploadingBannerIndex.value = null
  }
}

async function handleSave() {
  submitting.value = true
  try {
    const value = JSON.stringify(
      homeBannersDraft.value.filter(item => item.title.trim() || item.image_url?.trim()),
      null,
      2
    )
    await updateSystemConfig(props.config.key, {
      value,
      description: description.value,
    })
    ElMessage.success('配置已更新')
    emit('saved')
    emit('update:modelValue', false)
  } catch (error) {
    ElMessage.error(readError(error, '保存失败'))
  } finally {
    submitting.value = false
  }
}

</script>

<template>
  <el-dialog
    :model-value="modelValue"
    title="编辑首页轮播图"
    width="920px"
    @update:model-value="emit('update:modelValue', $event)"
  >
    <div class="dialog-body">
      <p class="config-key-label">
        <strong>{{ config.key }}</strong>
      </p>

      <div class="home-config-editor">
        <div class="editor-toolbar">
          <span>首页轮播图</span>
          <div class="panel-actions">
            <el-button size="small" @click="resetHomeBanners">恢复默认轮播</el-button>
            <el-button size="small" type="primary" @click="addHomeBanner">添加轮播</el-button>
          </div>
        </div>
        <el-table :data="homeBannersDraft" size="small" border>
          <el-table-column label="图片" min-width="240">
            <template #default="{ row, $index }">
              <div class="banner-image-editor">
                <el-input v-model="row.image_url" placeholder="图片 URL，留空使用文字卡片" />
                <div class="banner-image-tools">
                  <img v-if="row.image_url" :src="row.image_url" alt="轮播图预览" />
                  <div v-else class="empty-image">无图</div>
                  <label class="upload-trigger">
                    <input
                      type="file"
                      accept="image/jpeg,image/png,image/webp"
                      @change="handleHomeBannerUpload($event, $index)"
                    />
                    {{ uploadingBannerIndex === $index ? '上传中' : '上传图片' }}
                  </label>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="眉标" min-width="160">
            <template #default="{ row }"
              ><el-input v-model="row.eyebrow" placeholder="如 三角洲行动账号专区"
            /></template>
          </el-table-column>
          <el-table-column label="主标题" min-width="220">
            <template #default="{ row }"
              ><el-input v-model="row.title" placeholder="轮播主文案"
            /></template>
          </el-table-column>
          <el-table-column label="角标" width="110">
            <template #default="{ row }"
              ><el-input v-model="row.badge" placeholder="HOT"
            /></template>
          </el-table-column>
          <el-table-column label="胶囊文案" min-width="220">
            <template #default="{ row }"
              ><el-input v-model="row.pill" placeholder="底部补充文案"
            /></template>
          </el-table-column>
          <el-table-column label="色调" width="130">
            <template #default="{ row }">
              <el-select v-model="row.tone" placeholder="色调">
                <el-option label="蓝色" value="blue" />
                <el-option label="绿色" value="green" />
                <el-option label="橙色" value="orange" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="90">
            <template #default="{ $index }">
              <el-button size="small" type="danger" plain @click="removeHomeBanner($index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-form-item label="配置说明" class="desc-item">
        <el-input v-model="description" type="textarea" :rows="3" placeholder="配置说明" />
      </el-form-item>
    </div>
    <template #footer>
      <el-button @click="emit('update:modelValue', false)">取消</el-button>
      <el-button type="primary" :loading="submitting" @click="handleSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-body {
  display: grid;
  gap: 16px;
  max-height: 65vh;
  overflow-y: auto;
  padding-right: 8px;
}

.config-key-label {
  margin: 0;
  color: #374151;
}

.home-config-editor {
  display: grid;
  gap: 14px;
}

.editor-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.editor-toolbar span {
  color: #30343a;
  font-weight: 700;
}

.panel-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.banner-image-editor {
  display: grid;
  gap: 8px;
}

.banner-image-tools {
  display: flex;
  align-items: center;
  gap: 8px;
}

.banner-image-tools img,
.empty-image {
  width: 68px;
  height: 38px;
  border-radius: 6px;
  background: #f3f4f6;
  object-fit: cover;
}

.empty-image {
  display: grid;
  place-items: center;
  color: #9ca3af;
  font-size: 12px;
}

.upload-trigger {
  position: relative;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 28px;
  padding: 0 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: #fff;
  color: #606266;
  cursor: pointer;
  font-size: 12px;
}

.upload-trigger input {
  position: absolute;
  inset: 0;
  opacity: 0;
  cursor: pointer;
}

.desc-item {
  margin-top: 14px;
  margin-bottom: 0;
}
</style>
