import { useCallback, useEffect, useState } from 'react'
import {
  Button,
  Descriptions,
  Drawer,
  Table,
  Tag,
  Typography,
  message,
  type TableColumnsType,
} from 'antd'
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  EyeOutlined,
  ReloadOutlined,
} from '@ant-design/icons'
import { getErrorMessage } from '@/lib/errors'
import { getWebhookDeliveries } from '@/services/webhooks'
import { WebhookStatusText, type Webhook, type WebhookDelivery } from '@/types/webhook'
import { DeliveryDetailModal } from './DeliveryDetailModal'

const { Text } = Typography

interface WebhookDeliveriesDrawerProps {
  open: boolean
  webhook: Webhook | null
  onClose: () => void
}

export function WebhookDeliveriesDrawer({ open, webhook, onClose }: WebhookDeliveriesDrawerProps) {
  const [loading, setLoading] = useState(false)
  const [deliveries, setDeliveries] = useState<WebhookDelivery[]>([])
  const [detailVisible, setDetailVisible] = useState(false)
  const [selectedDelivery, setSelectedDelivery] = useState<WebhookDelivery | null>(null)

  const fetchDeliveries = useCallback(async () => {
    if (!webhook) {
      return
    }

    setLoading(true)
    try {
      const result = await getWebhookDeliveries(webhook.id, { limit: 50 })
      setDeliveries(result)
    } catch (err) {
      message.error(getErrorMessage(err, '获取投递记录失败'))
    } finally {
      setLoading(false)
    }
  }, [webhook])

  useEffect(() => {
    if (open) {
      void fetchDeliveries()
    }
  }, [fetchDeliveries, open])

  const columns: TableColumnsType<WebhookDelivery> = [
    {
      title: '事件',
      dataIndex: 'event_type',
      key: 'event_type',
      width: 180,
      render: (value) => <Tag color="blue">{value}</Tag>,
    },
    {
      title: '尝试次数',
      dataIndex: 'attempt',
      key: 'attempt',
      width: 100,
    },
    {
      title: '状态码',
      dataIndex: 'status_code',
      key: 'status_code',
      width: 100,
      render: (value) => (
        <Tag color={value >= 200 && value < 300 ? 'success' : 'error'}>{value || '-'}</Tag>
      ),
    },
    {
      title: '结果',
      dataIndex: 'success',
      key: 'success',
      width: 100,
      render: (value) => (
        <Tag
          color={value ? 'success' : 'error'}
          icon={value ? <CheckCircleOutlined /> : <CloseCircleOutlined />}
        >
          {value ? '成功' : '失败'}
        </Tag>
      ),
    },
    {
      title: '错误信息',
      dataIndex: 'error',
      key: 'error',
      width: 220,
      ellipsis: true,
      render: (value) => value || '-',
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (value) => value || '-',
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_, record) => (
        <Button
          type="link"
          size="small"
          icon={<EyeOutlined />}
          onClick={() => {
            setSelectedDelivery(record)
            setDetailVisible(true)
          }}
        >
          详情
        </Button>
      ),
    },
  ]

  return (
    <>
      <Drawer
        title={`投递记录 - ${webhook?.name || ''}`}
        placement="right"
        width={960}
        open={open}
        onClose={onClose}
        extra={(
          <Button icon={<ReloadOutlined />} onClick={() => void fetchDeliveries()}>
            刷新
          </Button>
        )}
      >
        {webhook && (
          <Descriptions size="small" column={2} style={{ marginBottom: 16 }}>
            <Descriptions.Item label="目标 URL">
              <Text copyable ellipsis style={{ maxWidth: 420 }}>
                {webhook.url}
              </Text>
            </Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={webhook.status === 1 ? 'success' : 'default'}>
                {WebhookStatusText[webhook.status]}
              </Tag>
            </Descriptions.Item>
          </Descriptions>
        )}

        <Table
          columns={columns}
          dataSource={deliveries}
          rowKey="id"
          loading={loading}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showTotal: (value) => `共 ${value} 条`,
          }}
          scroll={{ x: 1000 }}
          size="small"
        />
      </Drawer>

      <DeliveryDetailModal
        open={detailVisible}
        delivery={selectedDelivery}
        onClose={() => setDetailVisible(false)}
      />
    </>
  )
}
