import { Alert, Button, Card, Space, Table, Tag, Typography, Modal } from "antd"
import type { ColumnsType } from "antd/es/table"
import { GiftOutlined } from "@ant-design/icons"
import { claimServerPoints, type PointReward, type ServerDetail } from "../../api/servers"
import { toast } from "../../utils/toast"
import { formatDate, formatMoney } from "./helpers"

const { Text, Paragraph } = Typography

const SOURCE_LABEL: Record<string, string> = {
  server_purchase: "购买云服务器",
  server_renewal: "云服务器续费",
  package_upgrade: "套餐升级",
  disk_create: "添加弹性云盘",
  disk_resize: "磁盘扩容",
  disk_renewal: "磁盘续费",
}

const STATUS_COLOR: Record<string, string> = {
  pending: "processing",
  claimable: "success",
  claimed: "blue",
  cancelled: "default",
  reversed: "error",
}

interface Props {
  server: ServerDetail
  onClaimed: () => void
}

export default function PointsTab({ server, onClaimed }: Props) {
  const rewards = server.point_rewards ?? []
  const claimableCount = rewards.filter((item) => item.status === "claimable").length
  const claimablePoints = rewards
    .filter((item) => item.status === "claimable")
    .reduce((sum, item) => sum + item.points, 0)

  const claim = () => {
    Modal.confirm({
      title: "领取服务器积分？",
      content: "领取后相关订单将不再支持用户端退款；如后续发生特殊退款，系统会自动扣回已领取积分。",
      okText: "确认领取",
      cancelText: "取消",
      onOk: async () => {
        try {
          const res = await claimServerPoints(server.id)
          toast.success(`已领取 ${res.data.data?.claimed_points ?? claimablePoints} 积分`)
          onClaimed()
        } catch (error: unknown) {
          const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
          toast.error(detail || "领取失败")
        }
      },
    })
  }

  return (
    <Space direction="vertical" size={16} style={{ width: "100%" }}>
      <Alert
        type="info"
        showIcon
        message="服务器积分"
        description="服务器开通或增值服务成功后，消费返积分会进入可领取状态。领取后积分转为可用，同时该订单不再支持用户端退款。"
      />

      <Card
        variant="outlined"
        title={<Space><GiftOutlined />待领取积分</Space>}
        extra={
          <Button type="primary" onClick={claim} disabled={claimableCount === 0}>
            领取{claimableCount > 0 ? ` ${claimablePoints} 积分` : ""}
          </Button>
        }
      >
        <Table<PointReward>
          rowKey="id"
          size="small"
          pagination={false}
          columns={columns()}
          dataSource={rewards}
        />
        {claimableCount === 0 && (
          <Paragraph type="secondary" style={{ marginTop: 12, marginBottom: 0 }}>
            当前积分仍在待开通状态，服务确认成功后即可领取。
          </Paragraph>
        )}
      </Card>
    </Space>
  )
}

function columns(): ColumnsType<PointReward> {
  return [
    {
      title: "来源",
      dataIndex: "source_type",
      render: (value: string) => SOURCE_LABEL[value] ?? value,
    },
    {
      title: "订单",
      dataIndex: "ref_no",
      render: (value: string | null) => value || "-",
    },
    {
      title: "消费金额",
      dataIndex: "amount_cents",
      align: "right",
      render: (value: number) => formatMoney(value),
    },
    {
      title: "比例",
      dataIndex: "reward_rate",
      align: "right",
      width: 90,
      render: (value: number) => `${(value / 100).toFixed(1)}%`,
    },
    {
      title: "积分",
      dataIndex: "points",
      align: "right",
      width: 120,
      render: (value: number) => <Text strong>{value}</Text>,
    },
    {
      title: "状态",
      dataIndex: "status",
      width: 100,
      render: (value: string, row) => <Tag color={STATUS_COLOR[value] ?? "default"}>{row.status_label || value}</Tag>,
    },
    {
      title: "生成时间",
      dataIndex: "created_at",
      width: 170,
      render: (value: string | null) => formatDate(value),
    },
  ]
}
