<template>
  <div class="error-card">
    <CloseCircleOutlined class="error-card__icon" />
    <div class="error-card__body">
      <div class="error-card__title">{{ title }}</div>
      <div v-if="detail" class="error-card__detail">{{ detail }}</div>
    </div>
    <a-button
      v-if="!hideRetry"
      class="error-card__retry"
      type="primary"
      size="small"
      :loading="isRetrying"
      @click="handleRetry"
    >
      <template #icon><RedoOutlined /></template>
      重试
    </a-button>
  </div>
</template>

<script setup lang="ts">
import { computed, onUnmounted, ref } from 'vue'
import { CloseCircleOutlined, RedoOutlined } from '@ant-design/icons-vue'

interface Props {
  title: string
  detail?: string
  hideRetry?: boolean
  loading?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  detail: '',
  hideRetry: false,
})

const emit = defineEmits<{
  retry: []
}>()

const internalRetrying = ref(false)
const isRetrying = computed(() => props.loading ?? internalRetrying.value)
let retryTimer: ReturnType<typeof setTimeout> | null = null

function handleRetry(): void {
  if (isRetrying.value) return
  if (props.loading === undefined) {
    internalRetrying.value = true
    retryTimer = setTimeout(() => {
      internalRetrying.value = false
      retryTimer = null
    }, 2000)
  }
  emit('retry')
}

onUnmounted(() => {
  if (retryTimer) {
    clearTimeout(retryTimer)
    retryTimer = null
  }
})
</script>

<style scoped>
.error-card {
  display: flex;
  gap: var(--space-3);
  padding: var(--space-3) var(--space-4);
  background: var(--color-error-light);
  border: 1px solid rgba(239, 68, 68, 0.2);
  border-radius: var(--radius-lg);
  color: var(--color-error);
  width: 100%;
}

.error-card__icon {
  font-size: var(--font-lg);
  flex-shrink: 0;
  margin-top: 1px;
}

.error-card__body {
  display: flex;
  flex-direction: column;
  gap: var(--space-1);
  min-width: 0;
  flex: 1;
}

.error-card__title {
  font-weight: var(--font-weight-medium);
  font-size: var(--font-sm);
}

.error-card__detail {
  font-size: var(--font-xs);
  opacity: 0.85;
  word-break: break-word;
}

.error-card__retry {
  flex-shrink: 0;
  align-self: flex-start;
}
</style>
