import { useCallback, useEffect, useState } from 'react'
import {
  Button,
  Input,
  Popconfirm,
  Select,
  Space,
  Table,
  Tag,
  Tooltip,
  message,
  type TableColumnsType,
} from 'antd'
import {
  DeleteOutlined,
  EditOutlined,
  HistoryOutlined,
  PlusOutlined,
  ReloadOutlined,
  SearchOutlined,
} from '@ant-design/icons'
import { PageHeader } from '@/components/common'
import { PageEmpty, PageError } from '@/components/feedback'
import { PageLayout, FilterCard, TableCard } from '@/components/layout'
import { getErrorMessage } from '@/lib/errors'
import { deleteWebhook, listWebhooks, updateWebhookStatus } from '@/services/webhooks'
import {
  WebhookEventText,
  WebhookStatusColor,
  WebhookStatusText,
  type Webhook,
  type WebhookEvent,
  type WebhookStatus,
} from '@/types/webhook'
import { WebhookDeliveriesDrawer } from './WebhookDeliveriesDrawer'
import { WebhookFormModal } from './WebhookFormModal'

export function WebhooksPage() {
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [webhooks, setWebhooks] = useState<Webhook[]>([])
  const [keyword, setKeyword] = useState('')
  const [statusFilter, setStatusFilter] = useState<WebhookStatus | undefined>()
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [formVisible, setFormVisible] = useState(false)
  const [deliveriesVisible, setDeliveriesVisible] = useState(false)
  const [selectedWebhook, setSelectedWebhook] = useState<Webhook | null>(null)

  const fetchWebhooks = useCallback(async () => {
    setLoading(true)
    setError(null)

    try {
      const result = await listWebhooks({ page, page_size: pageSize })
      setWebhooks(result.data)
    } catch (err) {
      setError(getErrorMessage(err, '获取 Webhook 列表失败'))
    } finally {
      setLoading(false)
    }
  }, [page, pageSize])

  useEffect(() => {
    void fetchWebhooks()
  }, [fetchWebhooks])

  // 关键字或状态变化时重置页码
  useEffect(() => {
    setPage(1)
  }, [keyword, statusFilter])

  const filteredWebhooks = webhooks.filter((webhook) => {
    const matchesKeyword = !keyword
      || webhook.name.toLowerCase().includes(keyword.toLowerCase())
      || webhook.url.toLowerCase().includes(keyword.toLowerCase())
    const matchesStatus = statusFilter === undefined || webhook.status === statusFilter
    return matchesKeyword && matchesStatus
  })

  // 前端分页切片（前端全量过滤后再分页）
  const pagedWebhooks = filteredWebhooks.slice((page - 1) * pageSize, page * pageSize)

  const handleReset = () => {
    setKeyword('')
    setStatusFilter(undefined)
    setPage(1)
  }

  const handleDelete = async (id: number) => {
    try {
      await deleteWebhook(id)
      message.success('Webhook 已删除')
      await fetchWebhooks()
    } catch (err) {
      message.error(getErrorMessage(err, '删除 Webhook 失败'))
    }
  }

  const handleToggleStatus = async (webhook: Webhook) => {
    const nextStatus: WebhookStatus = webhook.status === 1 ? 0 : 1

    try {
      await updateWebhookStatus(webhook.id, nextStatus)
      message.success('Webhook 状态已更新')
      await fetchWebhooks()
    } catch (err) {
      message.error(getErrorMessage(err, '更新 Webhook 状态失败'))
    }
  }

  const columns: TableColumnsType<Webhook> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: 180,
      ellipsis: true,
    },
    {
      title: '目标 URL',
      dataIndex: 'url',
      key: 'url',
      width: 320,
      ellipsis: true,
      render: (value) => (
        <Tooltip title={value}>
          <span>{value}</span>
        </Tooltip>
      ),
    },
    {
      title: '订阅事件',
      dataIndex: 'events',
      key: 'events',
      width: 260,
      render: (events: WebhookEvent[]) => (
        <Space size={[0, 4]} wrap>
          {events.map((event) => (
            <Tag key={event} color="blue">
              {WebhookEventText[event] || event}
            </Tag>
          ))}
        </Space>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (value: WebhookStatus) => (
        <Tag color={WebhookStatusColor[value]}>{WebhookStatusText[value]}</Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (value) => value || '-',
    },
    {
      title: '操作',
      key: 'action',
      width: 260,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button type="link" size="small" icon={<EditOutlined />} onClick={() => {
            setSelectedWebhook(record)
            setFormVisible(true)
          }}>
            编辑
          </Button>
          <Button type="link" size="small" icon={<HistoryOutlined />} onClick={() => {
            setSelectedWebhook(record)
            setDeliveriesVisible(true)
          }}>
            记录
          </Button>
          <Popconfirm
            title={record.status === 1 ? '确定禁用该 Webhook 吗？' : '确定启用该 Webhook 吗？'}
            onConfirm={() => void handleToggleStatus(record)}
          >
            <Button type="link" size="small">
              {record.status === 1 ? '禁用' : '启用'}
            </Button>
          </Popconfirm>
          <Popconfirm
            title="确定删除该 Webhook 吗？"
            onConfirm={() => void handleDelete(record.id)}
          >
            <Button type="link" size="small" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ]

  if (error) {
    return <PageError description={error} onRetry={fetchWebhooks} />
  }

  return (
    <PageLayout>
      <PageHeader
        title="Webhook 管理"
        description="对齐真实后端 `/webhooks` 与 `/webhooks/:id/deliveries`，移除不存在的状态/测试子接口"
        actions={(
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              setSelectedWebhook(null)
              setFormVisible(true)
            }}
          >
            创建 Webhook
          </Button>
        )}
      />

      <FilterCard>
        <Space wrap size="middle">
          <Input
            placeholder="Webhook 名称或 URL"
            prefix={<SearchOutlined />}
            value={keyword}
            onChange={(event) => setKeyword(event.target.value)}
            onPressEnter={() => setPage(1)}
            style={{ width: 240 }}
            allowClear
          />
          <Select
            placeholder="状态"
            value={statusFilter}
            onChange={setStatusFilter}
            allowClear
            style={{ width: 120 }}
            options={[
              { value: 0, label: '已禁用' },
              { value: 1, label: '已启用' },
            ]}
          />
          <Button type="primary" icon={<SearchOutlined />} onClick={() => setPage(1)}>
            查询
          </Button>
          <Button onClick={handleReset}>重置</Button>
          <Button icon={<ReloadOutlined />} onClick={() => void fetchWebhooks()}>
            刷新
          </Button>
        </Space>
      </FilterCard>

      <TableCard>
        <Table
          columns={columns}
          dataSource={pagedWebhooks}
          rowKey="id"
          loading={loading}
          pagination={{
            current: page,
            pageSize,
            total: filteredWebhooks.length,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (value) => `共 ${value} 条`,
            onChange: (current, size) => {
              setPage(current)
              setPageSize(size)
            },
          }}
          scroll={{ x: 1400 }}
          locale={{ emptyText: <PageEmpty description="暂无 Webhook 数据" /> }}
        />
      </TableCard>

      <WebhookFormModal
        open={formVisible}
        webhook={selectedWebhook}
        onSuccess={() => {
          setFormVisible(false)
          void fetchWebhooks()
        }}
        onClose={() => setFormVisible(false)}
      />

      <WebhookDeliveriesDrawer
        open={deliveriesVisible}
        webhook={selectedWebhook}
        onClose={() => setDeliveriesVisible(false)}
      />
    </PageLayout>
  )
}
