import { useCallback, useEffect, useState } from "react"
import { Link } from "react-router-dom"
import { Card, Col, InputNumber, Row, Select, Space, Statistic, Table, Tag, Typography, message } from "antd"
import type { TableColumnsType } from "antd"
import { DollarOutlined, ShoppingCartOutlined } from "@ant-design/icons"
import { listAgentSettlements } from "../api/agent"
import { formatYuan } from "../../utils/format"

const { Text, Title } = Typography

const TYPE_MAP: Record<string, { label: string; color: string }> = {
  agent_profit: { label: "代理收益", color: "green" },
  agent_subsidy: { label: "代理补贴", color: "red" },
  member_commission: { label: "会员推广奖励", color: "blue" },
}
const STATUS_MAP: Record<string, { label: string; color: string }> = {
  pending: { label: "待结算", color: "default" },
  frozen: { label: "冻结中", color: "gold" },
  settled: { label: "已结算", color: "green" },
  reversed: { label: "已冲账", color: "red" },
}

export default function AdminAgentSettlements() {
  const [loading, setLoading] = useState(true)
  const [items, setItems] = useState<any[]>([])
  const [total, setTotal] = useState(0)
  const [filterType, setFilterType] = useState<string | undefined>()
  const [filterStatus, setFilterStatus] = useState<string | undefined>()
  const [filterUserId, setFilterUserId] = useState<number | null>(null)
  const [filterOrderId, setFilterOrderId] = useState<number | null>(null)

  const reload = useCallback(async () => {
    setLoading(true)
    try {
      const res = await listAgentSettlements({
        settlement_type: filterType,
        status: filterStatus,
        user_id: filterUserId ?? undefined,
        order_id: filterOrderId ?? undefined,
        limit: 50,
      })
      setItems(res.data?.items ?? [])
      setTotal(res.data?.total ?? 0)
    } catch { message.error("加载失败") }
    finally { setLoading(false) }
  }, [filterOrderId, filterStatus, filterType, filterUserId])

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

  const columns: TableColumnsType<any> = [
    { title: "订单号", dataIndex: "order_no", width: 220, render: (v: string) => <Link to={`/admin/tickets`}><Text style={{ fontSize: 12 }}>{v}</Text></Link> },
    { title: "类型", dataIndex: "settlement_type", width: 130, render: (v: string) => { const m = TYPE_MAP[v] || { label: v, color: "default" }; return <Tag color={m.color}>{m.label}</Tag> } },
    { title: "用户ID", dataIndex: "user_id", width: 80 },
    { title: "客户ID", dataIndex: "customer_user_id", width: 80, render: (v: number | null) => v ? <Link to={`/admin/users/${v}`}>{v}</Link> : "-" },
    { title: "订单金额", dataIndex: "standard_amount", width: 100, align: "right", render: (v: number) => formatYuan(v) },
    { title: "实付金额", dataIndex: "customer_pay_amount", width: 100, align: "right", render: (v: number) => formatYuan(v) },
    { title: "成本/比例", width: 110, align: "right", render: (_, row) => row.agent_cost_amount != null ? formatYuan(row.agent_cost_amount) : row.commission_rate ? `${(row.commission_rate / 100).toFixed(1)}%` : "-" },
    { title: "金额/积分", dataIndex: "delta_amount", width: 130, align: "right", render: (v: number, row) => (
      <Space orientation="vertical" size={0} style={{ alignItems: "flex-end" }}>
        <Text type={v > 0 ? "success" : v < 0 ? "danger" : "secondary"} strong>{v > 0 ? "+" : ""}{formatYuan(v)}</Text>
        {row.points_amount > 0 && <Text type="secondary" style={{ fontSize: 10 }}>≈{row.points_amount} 积分</Text>}
      </Space>
    )},
    { title: "状态", dataIndex: "status", width: 80, render: (v: string) => { const m = STATUS_MAP[v] || { label: v, color: "default" }; return <Tag color={m.color}>{m.label}</Tag> } },
    { title: "时间", dataIndex: "created_at", width: 160, render: (v: string) => v ? new Date(v).toLocaleString() : "-" },
  ]

  const stats = {
    totalProfit: items.filter(i => i.settlement_type === "agent_profit").reduce((s: number, i: any) => s + (i.delta_amount > 0 ? i.delta_amount : 0), 0),
    totalSubsidy: items.filter(i => i.settlement_type === "agent_subsidy").reduce((s: number, i: any) => s + Math.abs(i.delta_amount), 0),
    memberCommission: items.filter(i => i.settlement_type === "member_commission").reduce((s: number, i: any) => s + (i.delta_amount > 0 ? i.delta_amount : 0), 0),
    frozen: items.filter(i => i.status === "frozen").length,
  }

  return (
    <Space orientation="vertical" size={20} style={{ width: "100%" }}>
      <Row justify="space-between" align="bottom">
        <Col>
          <Title level={3}>代理结算流水</Title>
        </Col>
      </Row>
      <Row gutter={[16, 16]}>
        <Col xs={24} md={6}><Card variant="outlined"><Statistic title="代理收益" value={formatYuan(stats.totalProfit)} prefix={<DollarOutlined />} styles={{ content: { color: "#52c41a" } }} /></Card></Col>
        <Col xs={24} md={6}><Card variant="outlined"><Statistic title="代理补贴" value={formatYuan(stats.totalSubsidy)} prefix={<ShoppingCartOutlined />} styles={{ content: { color: "#ff4d4f" } }} /></Card></Col>
        <Col xs={24} md={6}><Card variant="outlined"><Statistic title="会员推广奖励" value={formatYuan(stats.memberCommission)} /></Card></Col>
        <Col xs={24} md={6}><Card variant="outlined"><Statistic title="冻结中" value={stats.frozen} suffix="笔" /></Card></Col>
      </Row>
      <Card variant="outlined" title={<Space wrap>
        <Select placeholder="类型筛选" allowClear style={{ width: 160 }} onChange={v => setFilterType(v)}
          options={Object.entries(TYPE_MAP).map(([k, v]) => ({ label: v.label, value: k }))} />
        <Select placeholder="状态筛选" allowClear style={{ width: 140 }} onChange={v => setFilterStatus(v)}
          options={Object.entries(STATUS_MAP).map(([k, v]) => ({ label: v.label, value: k }))} />
        <InputNumber min={1} precision={0} placeholder="用户 ID" value={filterUserId} onChange={v => setFilterUserId(typeof v === "number" ? v : null)} />
        <InputNumber min={1} precision={0} placeholder="订单 ID" value={filterOrderId} onChange={v => setFilterOrderId(typeof v === "number" ? v : null)} />
      </Space>}>
        <Table rowKey="id" loading={loading} columns={columns} dataSource={items}
          pagination={{ pageSize: 20, showSizeChanger: false, total }} size="middle" scroll={{ x: 1200 }} />
      </Card>
    </Space>
  )
}
