import { useCallback, useEffect, useMemo, useState } from "react"
import { Link } from "react-router-dom"
import { Card, Col, Row, Space, Statistic, Table, Tag, Typography, message } from "antd"
import type { TableColumnsType } from "antd"
import { BarChartOutlined, LinkOutlined, ShoppingCartOutlined, UserAddOutlined } from "@ant-design/icons"
import { getAffiliateReport, type AffiliateChannelItem, type AffiliateClickItem, type AffiliateReport } from "../api/agent"
import { formatYuan } from "../../utils/format"

const { Text, Title } = Typography

function pct(bps: number) {
  return `${(Number(bps || 0) / 100).toFixed(2)}%`
}

function dateText(value?: string | null) {
  return value ? new Date(value).toLocaleString() : "-"
}

export default function AdminAffiliate() {
  const [loading, setLoading] = useState(true)
  const [report, setReport] = useState<AffiliateReport | null>(null)

  const reload = useCallback(async () => {
    setLoading(true)
    try {
      const res = await getAffiliateReport({ recent_limit: 80, max_rows: 10000 })
      setReport(res.data ?? null)
    } catch {
      message.error("AFF 报表加载失败")
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => { reload() }, [reload])

  const channelColumns = useMemo<TableColumnsType<AffiliateChannelItem>>(() => [
    {
      title: "AFF",
      dataIndex: "aff_code",
      width: 120,
      render: (value: string) => <Tag color="blue">{value || "-"}</Tag>,
    },
    {
      title: "UTM",
      width: 260,
      render: (_, record) => (
        <Space wrap size={[4, 4]}>
          <Tag>{record.utm_source || "source:-"}</Tag>
          <Tag>{record.utm_medium || "medium:-"}</Tag>
          <Tag>{record.utm_campaign || "campaign:-"}</Tag>
        </Space>
      ),
    },
    { title: "点击", dataIndex: "clicks", width: 90, align: "right" },
    { title: "注册", dataIndex: "registrations", width: 90, align: "right" },
    { title: "下单", dataIndex: "orders", width: 90, align: "right" },
    { title: "注册率", dataIndex: "register_rate_bps", width: 100, align: "right", render: pct },
    { title: "下单率", dataIndex: "order_rate_bps", width: 100, align: "right", render: pct },
    { title: "收入", dataIndex: "revenue", width: 120, align: "right", render: formatYuan },
    { title: "最近点击", dataIndex: "latest_click_at", width: 170, render: dateText },
  ], [])

  const clickColumns = useMemo<TableColumnsType<AffiliateClickItem>>(() => [
    { title: "时间", dataIndex: "created_at", width: 170, render: dateText },
    { title: "AFF", dataIndex: "aff_code", width: 120, render: (value: string) => <Tag color="blue">{value}</Tag> },
    {
      title: "代理",
      dataIndex: "agent_id",
      width: 90,
      render: (value: number | null) => value ? <Link to={`/admin/users/${value}`}>{value}</Link> : "-",
    },
    {
      title: "UTM",
      width: 260,
      render: (_, record) => (
        <Space wrap size={[4, 4]}>
          <Tag>{record.utm_source || "source:-"}</Tag>
          <Tag>{record.utm_medium || "medium:-"}</Tag>
          <Tag>{record.utm_campaign || "campaign:-"}</Tag>
        </Space>
      ),
    },
    {
      title: "注册用户",
      dataIndex: "registered_user_id",
      width: 110,
      render: (value: number | null) => value ? <Link to={`/admin/users/${value}`}>{value}</Link> : "-",
    },
    { title: "转化时间", dataIndex: "converted_at", width: 170, render: dateText },
    { title: "IP", dataIndex: "ip", width: 130, render: (value: string | null) => value || "-" },
    {
      title: "落地页",
      dataIndex: "landing_url",
      ellipsis: true,
      render: (value: string | null) => value ? <Text copyable style={{ maxWidth: 260 }}>{value}</Text> : "-",
    },
  ], [])

  const summary = report?.summary

  return (
    <Space orientation="vertical" size={20} style={{ width: "100%" }}>
      <Row justify="space-between" align="bottom">
        <Col>
          <Title level={3}>AFF 渠道</Title>
          <Text type="secondary">统计推广点击、注册归因、下单转化和渠道收入。</Text>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col xs={24} md={6}>
          <Card variant="outlined">
            <Statistic title="点击" value={summary?.clicks ?? 0} prefix={<LinkOutlined />} />
          </Card>
        </Col>
        <Col xs={24} md={6}>
          <Card variant="outlined">
            <Statistic title="注册转化" value={summary?.registrations ?? 0} suffix={pct(summary?.register_rate_bps ?? 0)} prefix={<UserAddOutlined />} />
          </Card>
        </Col>
        <Col xs={24} md={6}>
          <Card variant="outlined">
            <Statistic title="支付订单" value={summary?.paid_orders ?? 0} suffix={pct(summary?.order_rate_bps ?? 0)} prefix={<ShoppingCartOutlined />} />
          </Card>
        </Col>
        <Col xs={24} md={6}>
          <Card variant="outlined">
            <Statistic title="归因收入" value={formatYuan(summary?.revenue ?? 0)} prefix={<BarChartOutlined />} />
          </Card>
        </Col>
      </Row>

      <Card variant="outlined" title="渠道转化">
        <Table<AffiliateChannelItem>
          rowKey={(record) => `${record.aff_code}:${record.utm_source || ""}:${record.utm_medium || ""}:${record.utm_campaign || ""}`}
          loading={loading}
          columns={channelColumns}
          dataSource={report?.channels ?? []}
          pagination={{ pageSize: 20 }}
          size="middle"
          scroll={{ x: 1200 }}
        />
      </Card>

      <Card variant="outlined" title="最近点击">
        <Table<AffiliateClickItem>
          rowKey="id"
          loading={loading}
          columns={clickColumns}
          dataSource={report?.recent_clicks ?? []}
          pagination={{ pageSize: 20 }}
          size="middle"
          scroll={{ x: 1300 }}
        />
      </Card>
    </Space>
  )
}
