<template>
  <div class="voice-selector">
    <!-- 空状态 -->
    <div v-if="userVoiceCards.length === 0" class="empty-voices">
      <div class="empty-icon">
        <Icon icon="lucide:mic-off" class="size-10 text-muted-foreground/40" />
      </div>
      <p class="text-muted-foreground mb-4">还没有配音</p>
      <Button @click="$router.push('/voice-copy')">
        去创建配音
      </Button>
    </div>

    <div v-else class="voice-selector-wrapper">
      <!-- 标题栏 -->
      <div class="selector-header">
        <div class="header-left">
          <span class="header-title">选择音色</span>
          <span class="voice-count">{{ userVoiceCards.length }} 个配音</span>
        </div>
        <Button
          v-if="selectedVoiceId"
          class="synthesize-btn"
          :disabled="isPlayerInitializing"
          :loading="previewLoadingVoiceId === selectedVoiceId"
          @click="handleSynthesize"
        >
          <Icon icon="lucide:volume-2" class="size-4" />
          合成试听
        </Button>
      </div>

      <!-- 卡片网格 -->
      <div class="voice-grid" :class="{ 'has-many': userVoiceCards.length > 4 }">
        <button
          v-for="voice in userVoiceCards"
          :key="voice.id"
          class="voice-card"
          :class="{ 'selected': selectedVoiceId === voice.id }"
          @click="handleVoiceSelect(voice)"
        >
          <!-- 头像区域 -->
          <div class="card-avatar">
            <div class="avatar-ring"></div>
            <div class="avatar-icon">
              <Icon icon="lucide:audio-waveform" class="size-6" />
            </div>
            <!-- 选中指示器 -->
            <div v-if="selectedVoiceId === voice.id" class="selected-indicator">
              <Icon icon="lucide:check" class="size-3" />
            </div>
          </div>

          <!-- 信息区域 -->
          <div class="card-info">
            <div class="voice-name">{{ voice.name }}</div>
            <div class="voice-desc">{{ voice.description || '我的配音' }}</div>
          </div>
        </button>
      </div>

      <!-- 播放器区域 -->
      <transition name="slide-fade">
        <div v-if="audioUrl" class="player-section">
          <div class="player-header">
            <div class="player-info">
              <div class="player-icon">
                <Icon icon="lucide:play-circle" class="size-8" />
              </div>
              <div class="player-meta">
                <div class="player-title">{{ currentVoiceName }}</div>
                <div class="player-label">合成预览</div>
              </div>
            </div>
            <Button variant="ghost" size="sm" @click="downloadAudio" class="download-btn">
              <Icon icon="lucide:download" class="size-4" />
              下载
            </Button>
          </div>
          <div ref="playerContainer" class="aplayer-container"></div>
        </div>
      </transition>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, nextTick, watch } from 'vue'
import { toast } from 'vue-sonner'
import { Icon } from '@iconify/vue'
import { useVoiceCopyStore } from '@/stores/voiceCopy'
import { useTTS, TTS_PROVIDERS } from '@/composables/useTTS'
import APlayer from 'aplayer'

import { Button } from '@/components/ui/button'

const props = defineProps({
  synthText: {
    type: String,
    default: '',
  },
  speechRate: {
    type: Number,
    default: 1.0,
  },
})

const voiceStore = useVoiceCopyStore()

const emit = defineEmits(['select', 'audioGenerated'])

let player = null
const playerContainer = ref(null)
const audioUrl = ref('')
const currentVoiceName = ref('')
const isPlayerInitializing = ref(false)

// 默认封面图片（音频波形图标）
const defaultCover = `data:image/svg+xml;base64,${btoa(`
<svg width="100" height="100" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
  <rect width="100" height="100" fill="#1f2937" rx="8"/>
  <g fill="#60a5fa">
    <rect x="20" y="35" width="4" height="30" rx="2">
      <animate attributeName="height" values="30;20;30" dur="0.8s" repeatCount="indefinite"/>
      <animate attributeName="y" values="35;40;35" dur="0.8s" repeatCount="indefinite"/>
    </rect>
    <rect x="30" y="30" width="4" height="40" rx="2">
      <animate attributeName="height" values="40;25;40" dur="0.6s" repeatCount="indefinite"/>
      <animate attributeName="y" values="30;37.5;30" dur="0.6s" repeatCount="indefinite"/>
    </rect>
    <rect x="40" y="25" width="4" height="50" rx="2">
      <animate attributeName="height" values="50;30;50" dur="0.7s" repeatCount="indefinite"/>
      <animate attributeName="y" values="25;35;25" dur="0.7s" repeatCount="indefinite"/>
    </rect>
    <rect x="50" y="28" width="4" height="44" rx="2">
      <animate attributeName="height" values="44;28;44" dur="0.9s" repeatCount="indefinite"/>
      <animate attributeName="y" values="28;36;28" dur="0.9s" repeatCount="indefinite"/>
    </rect>
    <rect x="60" y="32" width="4" height="36" rx="2">
      <animate attributeName="height" values="36;22;36" dur="0.5s" repeatCount="indefinite"/>
      <animate attributeName="y" values="32;39;32" dur="0.5s" repeatCount="indefinite"/>
    </rect>
    <rect x="70" y="38" width="4" height="24" rx="2">
      <animate attributeName="height" values="24;15;24" dur="0.7s" repeatCount="indefinite"/>
      <animate attributeName="y" values="38;42.5;38" dur="0.7s" repeatCount="indefinite"/>
    </rect>
  </g>
  <circle cx="50" cy="50" r="18" fill="none" stroke="#60a5fa" stroke-width="2" opacity="0.3"/>
  <path d="M44 44 L44 56 L56 50 Z" fill="#60a5fa" opacity="0.5"/>
</svg>
`.trim())}`

// 使用TTS Hook
const {
  previewLoadingVoiceId,
  playVoiceSample,
  setText,
  setSpeechRate,
} = useTTS({
  provider: TTS_PROVIDERS.SILICONFLOW,
})

const selectedVoiceId = ref('')

const userVoiceCards = computed(() =>
  (voiceStore.profiles || []).map((profile) => ({
    id: `user-${profile.id}`,
    rawId: profile.id,
    name: profile.name || '未命名',
    category: '',
    gender: profile.gender || 'female',
    description: profile.note || '我的配音',
    fileUrl: profile.fileUrl,
    transcription: profile.transcription || '',
    source: 'user',
    voiceId: profile.voiceId,
  })),
)

const handleVoiceSelect = (voice) => {
  selectedVoiceId.value = voice.id
  currentVoiceName.value = voice.name
  emit('select', voice)
}

const handleSynthesize = () => {
  if (!selectedVoiceId.value || isPlayerInitializing.value) return

  const voice = userVoiceCards.value.find((v) => v.id === selectedVoiceId.value)
  if (!voice) return

  currentVoiceName.value = voice.name
  handlePlayVoiceSample(voice)
}

// 监听 prop 变化，更新 TTS 参数
watch(
  () => props.synthText,
  (newText) => {
    setText(newText || '')
  },
  { immediate: true },
)

watch(
  () => props.speechRate,
  (newRate) => {
    setSpeechRate(newRate)
  },
  { immediate: true },
)

const handlePlayVoiceSample = (voice) => {
  currentVoiceName.value = voice.name
  playVoiceSample(
    voice,
    (data) => {
      const url = data.audioUrl || data.objectUrl
      if (!url) return
      initPlayer(url)
    },
    () => {
      /* 错误已在 useTTS 中处理 */
    },
    { autoPlay: false },
  )
}

/**
 * 初始化 APlayer
 */
const initPlayer = (url) => {
  // 防止并发初始化
  if (isPlayerInitializing.value) {
    return
  }

  isPlayerInitializing.value = true
  destroyPlayer()
  audioUrl.value = url

  nextTick(() => {
    try {
      // 检查容器是否存在
      if (!playerContainer.value) {
        toast.error('播放器容器未就绪')
        isPlayerInitializing.value = false
        audioUrl.value = ''
        return
      }

      player = new APlayer({
        container: playerContainer.value,
        autoplay: true,
        theme: '#3b82f6',
        volume: 0.7,
        loop: 'none',
        audio: [
          {
            name: currentVoiceName.value || '语音合成',
            artist: '合成',
            url: url,
            cover: defaultCover,
          },
        ],
      })

      player.on('ended', () => {
        player.seek(0)
      })

      player.on('error', (e) => {
        console.error('APlayer 播放错误:', e)
      })

      player.on('canplay', () => {
        isPlayerInitializing.value = false
        // 发送音频时长和 URL 给父组件
        const durationMs = Math.floor(player.audio.duration * 1000)
        if (durationMs > 0) {
          emit('audioGenerated', {
            durationMs,
            audioUrl: audioUrl.value, // 使用 URL（性能优化）
          })
        }
      })
    } catch (e) {
      console.error('APlayer 初始化失败:', e)
      toast.error('播放器初始化失败，请重试')
      isPlayerInitializing.value = false
      audioUrl.value = ''
    }
  })
}

const downloadAudio = () => {
  if (!audioUrl.value) return

  const link = document.createElement('a')
  link.href = audioUrl.value
  link.download = `${currentVoiceName.value || '语音合成'}.mp3`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

const destroyPlayer = () => {
  isPlayerInitializing.value = false
  if (player) {
    try {
      player.pause()
      player.destroy()
    } catch (e) {
      console.error('销毁播放器失败:', e)
    }
    player = null
  }
  if (audioUrl.value?.startsWith('blob:')) {
    URL.revokeObjectURL(audioUrl.value)
  }
  audioUrl.value = ''
}

onMounted(async () => {
  await voiceStore.refresh()
})

onBeforeUnmount(() => {
  destroyPlayer()
})
</script>

<style scoped lang="less">
.voice-selector {
  width: 100%;
}

/* 空状态 */
.empty-voices {
  padding: 40px 24px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border: 1px dashed #e2e8f0;
  border-radius: 16px;
  text-align: center;

  .empty-icon {
    margin-bottom: 12px;
  }
}

/* 主容器 */
.voice-selector-wrapper {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 标题栏 */
.selector-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 12px;
  border-bottom: 1px solid #f1f5f9;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-title {
  font-size: 15px;
  font-weight: 600;
  color: #1e293b;
}

.voice-count {
  font-size: 12px;
  color: #94a3b8;
  background: #f1f5f9;
  padding: 2px 8px;
  border-radius: 10px;
}

.synthesize-btn {
  height: 34px;
  padding: 0 14px;
  border-radius: 8px;
  border: none;
  background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
  color: white;
  font-weight: 500;
  font-size: 13px;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.25);
  transition: all 0.2s ease;

  &:hover:not(:disabled) {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(59, 130, 246, 0.35);
  }

  &:disabled {
    background: #94a3b8;
    box-shadow: none;
    cursor: not-allowed;
    transform: none;
  }
}

/* 卡片网格 */
.voice-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  gap: 12px;

  &.has-many {
    max-height: 280px;
    overflow-y: auto;
    padding-right: 4px;

    &::-webkit-scrollbar {
      width: 4px;
    }
    &::-webkit-scrollbar-track {
      background: #f1f5f9;
      border-radius: 2px;
    }
    &::-webkit-scrollbar-thumb {
      background: #cbd5e1;
      border-radius: 2px;
    }
  }
}

/* 音色卡片 */
.voice-card {
  position: relative;
  background: white;
  border: 2px solid #f1f5f9;
  border-radius: 14px;
  padding: 16px 12px;
  cursor: pointer;
  transition: all 0.25s ease;
  overflow: hidden;
  text-align: left;

  &:hover {
    border-color: #e2e8f0;
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.06);
  }

  &.selected {
    border-color: #3b82f6;
    background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
    box-shadow: 0 4px 16px rgba(59, 130, 246, 0.15);
  }
}

/* 头像区域 */
.card-avatar {
  position: relative;
  width: 48px;
  height: 48px;
  margin: 0 auto 10px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;

  .avatar-ring {
    background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%);
  }
  .avatar-icon {
    color: #3b82f6;
  }
}

.avatar-ring {
  position: absolute;
  inset: 0;
  border-radius: 50%;
}

.avatar-icon {
  position: relative;
  z-index: 1;
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.selected-indicator {
  position: absolute;
  top: -4px;
  right: -4px;
  width: 20px;
  height: 20px;
  background: #3b82f6;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 10px;
  box-shadow: 0 2px 6px rgba(59, 130, 246, 0.4);
  animation: scaleIn 0.2s ease;
}

@keyframes scaleIn {
  from {
    transform: scale(0);
  }
  to {
    transform: scale(1);
  }
}

/* 信息区域 */
.card-info {
  text-align: center;
}

.voice-name {
  font-size: 13px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.voice-desc {
  font-size: 11px;
  color: #94a3b8;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 播放器区域 */
.player-section {
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-radius: 14px;
  padding: 14px;
  border: 1px solid #e2e8f0;
}

.player-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.player-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.player-icon {
  width: 36px;
  height: 36px;
  color: #3b82f6;
  display: flex;
  align-items: center;
  justify-content: center;
}

.player-meta {
  .player-title {
    font-size: 14px;
    font-weight: 600;
    color: #1e293b;
  }
  .player-label {
    font-size: 11px;
    color: #94a3b8;
  }
}

.download-btn {
  color: #64748b;
  font-size: 12px;
  padding: 4px 10px;
  height: auto;
  border-radius: 6px;
  transition: all 0.2s ease;

  &:hover {
    color: #3b82f6;
    background: rgba(59, 130, 246, 0.08);
  }
}

.aplayer-container {
  :deep(.aplayer) {
    border-radius: 10px;
    box-shadow: none;
    border: 1px solid rgba(0, 0, 0, 0.04);

    .aplayer-body {
      border-radius: 10px;
    }
  }
}

/* 动画 */
.slide-fade-enter-active {
  transition: all 0.3s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.2s ease-in;
}

.slide-fade-enter-from {
  transform: translateY(-10px);
  opacity: 0;
}

.slide-fade-leave-to {
  transform: translateY(-10px);
  opacity: 0;
}
</style>
