<template>
  <div class="generate-button-container" :class="{ 'is-loading': isLoading, 'is-disabled': isDisabled }">
    <button
      ref="buttonRef"
      :disabled="isDisabled || isLoading"
      :class="[
        'generate-button',
        { 'btn-large': size === 'large' },
        { 'btn-small': size === 'small' },
        { 'is-loading': isLoading },
        { 'is-disabled': isDisabled }
      ]"
      @click="handleClick"
      :title="buttonTitle"
    >
      <template v-if="isLoading">
        <LoadingOutlined :spin="true" />
        <span>{{ loadingText || t('common.generate') }}</span>
      </template>
      <template v-else>
        <template v-if="icon">
          <component :is="icon" />
        </template>
        <template v-else>
          <PlayCircleOutlined />
        </template>
        <span>{{ buttonText }}</span>
      </template>
    </button>

    <!-- 智能提示气泡 -->
    <div
      v-if="showTooltip && tooltipContent"
      class="generate-button-tooltip"
      :class="{ 'tooltip-error': isError }"
      ref="tooltipRef"
    >
      <span>{{ tooltipContent }}</span>
      <div class="tooltip-arrow"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { PlayCircleOutlined, LoadingOutlined } from '@ant-design/icons-vue'
import { useI18n } from 'vue-i18n'
import { message } from 'ant-design-vue'

const props = defineProps({
  // 生成类型：text-to-video, image-to-video, storyboard-video
  type: {
    type: String,
    default: 'text-to-video'
  },
  // 按钮大小：default, large, small
  size: {
    type: String,
    default: 'default'
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false
  },
  // 是否正在加载
  loading: {
    type: Boolean,
    default: false
  },
  // 按钮文本
  text: {
    type: String,
    default: ''
  },
  // 加载状态文本
  loadingText: {
    type: String,
    default: ''
  },
  // 图标组件
  icon: {
    type: Object,
    default: null
  },
  // 工具提示内容
  tooltip: {
    type: String,
    default: ''
  },
  // 是否显示错误状态
  error: {
    type: Boolean,
    default: false
  },
  // 生成参数
  generateParams: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['generate', 'click', 'loading', 'error'])

const { t } = useI18n()
const buttonRef = ref(null)
const tooltipRef = ref(null)
const showTooltip = ref(false)

// 响应式状态
const isLoading = ref(props.loading)
const isDisabled = ref(props.disabled)
const isError = ref(props.error)
const tooltipContent = ref(props.tooltip)

// 计算属性
const buttonText = computed(() => {
  if (props.text) return props.text
  
  const typeMap = {
    'text-to-video': t('common.generateVideo'),
    'image-to-video': t('common.generateVideo'),
    'storyboard-video': t('common.generateVideo'),
    'storyboard-image': t('common.generateImage')
  }
  
  return typeMap[props.type] || t('common.generate')
})

const buttonTitle = computed(() => {
  if (tooltipContent.value) return tooltipContent.value
  return buttonText.value
})

// 处理按钮点击
const handleClick = async () => {
  if (isLoading.value || isDisabled.value) return
  
  emit('click')
  
  try {
    isLoading.value = true
    emit('loading', true)
    
    // 触发生成事件
    const result = await emit('generate', props.generateParams)
    
    // 如果结果是Promise，等待其完成
    if (result && typeof result.then === 'function') {
      await result
    }
    
  } catch (error) {
    console.error('生成失败:', error)
    isError.value = true
    tooltipContent.value = error.message || t('common.generateFailed')
    showTooltip.value = true
    emit('error', error)
    message.error(error.message || t('common.generateFailed'))
  } finally {
    isLoading.value = false
    emit('loading', false)
  }
}

// 监听属性变化
watch(
  () => props.loading,
  (newVal) => {
    isLoading.value = newVal
  }
)

watch(
  () => props.disabled,
  (newVal) => {
    isDisabled.value = newVal
  }
)

watch(
  () => props.error,
  (newVal) => {
    isError.value = newVal
  }
)

watch(
  () => props.tooltip,
  (newVal) => {
    tooltipContent.value = newVal
  }
)

onMounted(() => {
  // 初始化工具提示位置
  updateTooltipPosition()
})

// 更新工具提示位置
const updateTooltipPosition = () => {
  nextTick(() => {
    if (!tooltipRef.value || !buttonRef.value) return
    
    const buttonRect = buttonRef.value.getBoundingClientRect()
    const tooltipRect = tooltipRef.value.getBoundingClientRect()
    
    tooltipRef.value.style.left = `${buttonRect.left + (buttonRect.width - tooltipRect.width) / 2}px`
    tooltipRef.value.style.top = `${buttonRect.bottom + 8}px`
  })
}

// 暴露方法
const showLoading = (text) => {
  isLoading.value = true
  if (text) {
    loadingText.value = text
  }
}

const hideLoading = () => {
  isLoading.value = false
}

const showError = (message) => {
  isError.value = true
  tooltipContent.value = message
  showTooltip.value = true
}

const hideError = () => {
  isError.value = false
  tooltipContent.value = ''
  showTooltip.value = false
}

defineExpose({
  showLoading,
  hideLoading,
  showError,
  hideError,
  updateTooltipPosition
})
</script>

<style scoped>
.generate-button-container {
  position: relative;
  display: inline-block;
}

.generate-button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 4px 14px 0 rgba(102, 126, 234, 0.39);
  width: 100%;
}

.generate-button:hover:not(.is-disabled):not(.is-loading) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
  background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
}

.generate-button:active:not(.is-disabled):not(.is-loading) {
  transform: translateY(0);
  box-shadow: 0 4px 14px 0 rgba(102, 126, 234, 0.39);
}

.generate-button.is-disabled {
  background: #f5f5f5;
  color: #999;
  cursor: not-allowed;
  box-shadow: none;
}

.generate-button.is-loading {
  cursor: not-allowed;
  opacity: 0.8;
}

.generate-button.btn-large {
  padding: 16px 32px;
  font-size: 18px;
  border-radius: 10px;
}

.generate-button.btn-small {
  padding: 8px 16px;
  font-size: 14px;
  border-radius: 6px;
}

.generate-button-tooltip {
  position: absolute;
  bottom: calc(100% + 12px);
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  z-index: 1000;
  animation: tooltipFadeIn 0.3s ease;
}

.generate-button-tooltip.tooltip-error {
  background: rgba(255, 87, 34, 0.9);
}

.tooltip-arrow {
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  width: 0;
  height: 0;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 5px solid rgba(0, 0, 0, 0.8);
}

.generate-button-tooltip.tooltip-error .tooltip-arrow {
  border-top-color: rgba(255, 87, 34, 0.9);
}

@keyframes tooltipFadeIn {
  from {
    opacity: 0;
    transform: translateX(-50%) translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .generate-button {
    padding: 10px 20px;
    font-size: 14px;
  }
  
  .generate-button.btn-large {
    padding: 14px 28px;
    font-size: 16px;
  }
  
  .generate-button.btn-small {
    padding: 6px 14px;
    font-size: 12px;
  }
}

@media (max-width: 480px) {
  .generate-button {
    padding: 8px 16px;
    font-size: 13px;
  }
  
  .generate-button.btn-large {
    padding: 12px 24px;
    font-size: 14px;
  }
}
</style>