import { Alert, Descriptions, Modal, Typography } from 'antd'
import type { WebhookDelivery } from '@/types/webhook'

const { Paragraph, Text } = Typography

interface DeliveryDetailModalProps {
  open: boolean
  delivery: WebhookDelivery | null
  onClose: () => void
}

function formatPayload(payload: string) {
  try {
    return JSON.stringify(JSON.parse(payload), null, 2)
  } catch {
    return payload
  }
}

export function DeliveryDetailModal({ open, delivery, onClose }: DeliveryDetailModalProps) {
  if (!delivery) {
    return null
  }

  return (
    <Modal title="投递详情" open={open} onCancel={onClose} footer={null} width={720}>
      <Descriptions column={2} bordered size="small">
        <Descriptions.Item label="投递 ID">{delivery.id}</Descriptions.Item>
        <Descriptions.Item label="Webhook ID">{delivery.webhook_id}</Descriptions.Item>
        <Descriptions.Item label="事件类型">{delivery.event_type}</Descriptions.Item>
        <Descriptions.Item label="尝试次数">{delivery.attempt}</Descriptions.Item>
        <Descriptions.Item label="状态码">{delivery.status_code || '-'}</Descriptions.Item>
        <Descriptions.Item label="结果">
          {delivery.success ? (
            <Text type="success">成功</Text>
          ) : (
            <Text type="danger">失败</Text>
          )}
        </Descriptions.Item>
        <Descriptions.Item label="创建时间" span={2}>
          {delivery.created_at || '-'}
        </Descriptions.Item>
        <Descriptions.Item label="投递时间" span={2}>
          {delivery.delivered_at || '-'}
        </Descriptions.Item>
      </Descriptions>

      {delivery.error && (
        <Alert
          type="error"
          message="错误信息"
          description={delivery.error}
          style={{ marginTop: 16 }}
          showIcon
        />
      )}

      <div style={{ marginTop: 16 }}>
        <Text strong>请求负载</Text>
        <Paragraph
          code
          style={{
            marginTop: 8,
            maxHeight: 200,
            overflow: 'auto',
            backgroundColor: '#f5f5f5',
            padding: 12,
            borderRadius: 4,
            whiteSpace: 'pre-wrap',
          }}
        >
          {formatPayload(delivery.payload)}
        </Paragraph>
      </div>

      {delivery.response_body && (
        <div style={{ marginTop: 16 }}>
          <Text strong>响应内容</Text>
          <Paragraph
            code
            style={{
              marginTop: 8,
              maxHeight: 200,
              overflow: 'auto',
              backgroundColor: '#f5f5f5',
              padding: 12,
              borderRadius: 4,
              whiteSpace: 'pre-wrap',
            }}
          >
            {formatPayload(delivery.response_body)}
          </Paragraph>
        </div>
      )}
    </Modal>
  )
}
