<template>
  <div
    class="rounded-xl p-4 flex items-center gap-4 min-w-72 max-w-md cursor-pointer transition-all duration-200 hover:opacity-90"
    :class="audioContainerClasses"
    @click="togglePlay"
  >
    <!-- 播放状态指示器 -->
    <div class="flex-shrink-0 w-10 h-10 flex items-center justify-center rounded-full"
         :class="playIconBgClasses">
      <component
        :is="isPlaying ? PauseOutlined : CaretRightOutlined"
        class="text-white"
        style="font-size: 16px; transform: translateX(1px)"
      />
    </div>

    <div class="flex-1 overflow-hidden">
      <!-- 高级音波动画 -->
      <div class="flex items-end gap-1 h-8 mb-2">
        <div
          v-for="i in 20"
          :key="i"
          class="rounded-full transition-all duration-300 ease-out"
          :class="waveBarClasses"
          :style="{
            width: '3px',
            height: isPlaying ? `${getWaveHeight(i)}px` : '4px',
            animationDelay: `${i * 40}ms`
          }"
        ></div>
      </div>

      <!-- 进度条和时间显示 -->
      <div class="flex items-center gap-2 w-full">
        <!-- 当前时间 -->
        <div class="text-xs font-medium flex-shrink-0" :class="timeTextClasses">
          {{ formatDuration(currentTime) }}
        </div>

        <!-- 进度条 -->
        <div class="flex-1 rounded-full h-1.5 overflow-hidden" :class="progressTrackClasses">
          <div
            class="h-full rounded-full transition-all duration-300 ease-out"
            :class="progressBarClasses"
            :style="{ width: `${progress}%` }"
          ></div>
        </div>

        <!-- 剩余时间 -->
        <div class="text-xs font-medium flex-shrink-0" :class="timeTextClasses">
          -{{ formatDuration(remainingTime) }}
        </div>
      </div>
    </div>

    <!-- 总时长显示 -->
    <div class="text-sm font-medium flex-shrink-0 min-w-12 text-right" :class="durationTextClasses">
      {{ formatDuration(audioDuration) }}
    </div>
  </div>
</template>

<script setup>
import {ref, onUnmounted, computed, watch} from 'vue';
import {CaretRightOutlined, PauseOutlined} from '@ant-design/icons-vue';

const props = defineProps({
  message: {
    type: Object,
    required: true
  },
  isSent: {
    type: Boolean,
    default: false
  }
});

const isPlaying = ref(false);
const progress = ref(0);
const audio = ref(null);
const audioDuration = ref(0);
const currentTime = ref(0);
const remainingTime = computed(() => Math.max(0, audioDuration.value - currentTime.value));

// 直接获取音频时长
const getAudioDuration = () => {
  // 如果消息对象中已经包含时长，直接使用
  if (props.message.duration && props.message.duration > 0) {
    audioDuration.value = props.message.duration;
    return;
  }

  // 否则创建临时音频获取元数据
  const audioUrl = props.message.message_content || props.message.content || '';
  const tempAudio = new Audio(audioUrl);
  tempAudio.addEventListener('loadedmetadata', () => {
    if (tempAudio.duration && tempAudio.duration > 0) {
      audioDuration.value = Math.round(tempAudio.duration);
    }
  });

  // 设置超时以防无法获取元数据
  setTimeout(() => {
    if (audioDuration.value === 0 && tempAudio.duration > 0) {
      audioDuration.value = Math.round(tempAudio.duration);
    }
  }, 500);
};

// 初始化时获取音频时长
getAudioDuration();

// 样式计算属性
const audioContainerClasses = computed(() => {
  if (props.isSent) {
    return 'bg-gradient-to-r from-blue-500 to-indigo-600 text-white shadow-lg';
  } else {
    return 'bg-gray-50 dark:bg-gray-700 border border-gray-100 dark:border-gray-600 shadow';
  }
});

const playIconBgClasses = computed(() => {
  if (props.isSent) {
    return 'bg-white/20';
  } else {
    return 'bg-blue-500';
  }
});

const waveBarClasses = computed(() => {
  if (props.isSent) {
    return ['bg-white/80', {'animate-wave': isPlaying.value}];
  } else {
    return ['bg-blue-500', {'animate-wave': isPlaying.value}];
  }
});

const progressTrackClasses = computed(() => {
  if (props.isSent) {
    return 'bg-white/30';
  } else {
    return 'bg-gray-200 dark:bg-gray-600';
  }
});

const progressBarClasses = computed(() => {
  if (props.isSent) {
    return 'bg-white';
  } else {
    return 'bg-blue-500';
  }
});

const durationTextClasses = computed(() => {
  if (props.isSent) {
    return 'text-white/90';
  } else {
    return 'text-gray-700 dark:text-gray-300';
  }
});

const timeTextClasses = computed(() => {
  if (props.isSent) {
    return 'text-white/80';
  } else {
    return 'text-gray-600 dark:text-gray-400';
  }
});

// 生成高级波形高度
const getWaveHeight = (index) => {
  const baseHeight = 4;
  const maxHeight = 20;
  // 使用更平滑的正弦波叠加
  const wavePattern =
    Math.sin((index * 0.4) + (Date.now() * 0.008)) * 0.4 +
    Math.cos((index * 0.7) + (Date.now() * 0.01)) * 0.3;
  const normalized = Math.max(0, wavePattern * 0.5 + 0.5);
  return baseHeight + (maxHeight - baseHeight) * normalized;
};

const togglePlay = () => {
  if (!audio.value) {
    const audioUrl = props.message.message_content || props.message.content || '';
    audio.value = new Audio(audioUrl);

    // 确保获取音频时长
    audio.value.addEventListener('loadedmetadata', () => {
      if (audio.value.duration && audio.value.duration > 0) {
        audioDuration.value = Math.round(audio.value.duration);
      }
    });

    audio.value.addEventListener('timeupdate', () => {
      if (audio.value.duration) {
        currentTime.value = Math.round(audio.value.currentTime);
        progress.value = (currentTime.value / audioDuration.value) * 100;
      }
    });

    audio.value.addEventListener('ended', () => {
      isPlaying.value = false;
      progress.value = 0;
      currentTime.value = 0;
    });
  }

  if (isPlaying.value) {
    audio.value.pause();
    isPlaying.value = false;
  } else {
    audio.value.play();
    isPlaying.value = true;
  }
};

const formatDuration = (seconds) => {
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${mins}:${secs.toString().padStart(2, '0')}`;
};

onUnmounted(() => {
  if (audio.value) {
    audio.value.pause();
    audio.value = null;
  }
});
</script>

<style scoped>
@keyframes wave {
  0%, 100% {
    transform: scaleY(0.7);
    opacity: 0.7;
  }
  25% {
    transform: scaleY(1.2);
    opacity: 1;
  }
  50% {
    transform: scaleY(0.8);
    opacity: 0.8;
  }
  75% {
    transform: scaleY(1.1);
    opacity: 0.9;
  }
}

.animate-wave {
  animation: wave 1.2s ease-in-out infinite;
  transform-origin: center bottom;
}
</style>
