import { useEffect, useMemo, useState } from "react"
import { Link } from "react-router-dom"
import { Card, Col, Empty, Progress, Row, Space, Spin, Statistic, Table, Tag, Typography } from "antd"
import type { ColumnsType } from "antd/es/table"
import { CrownOutlined, GiftOutlined, RiseOutlined, WalletOutlined } from "@ant-design/icons"
import { getMyMembership, getPointLogs, type PointLog, type UserMembership } from "../api/membership"
import { formatPoints, formatYuan } from "../utils/format"

const { Text, Title, Paragraph } = Typography

const POINT_CHANGE_TYPE_MAP: Record<string, { label: string; color: string }> = {
  order_reward: { label: "消费返积分", color: "success" },
  order_refund: { label: "退款扣回", color: "error" },
  points_use: { label: "积分抵扣", color: "warning" },
  points_refund: { label: "积分返还", color: "processing" },
  admin_adjust: { label: "系统调整", color: "default" },
  activity_gift: { label: "活动赠送", color: "purple" },
  agent_profit: { label: "代理收益积分", color: "green" },
  agent_subsidy: { label: "代理补贴扣回", color: "red" },
  referral_reward: { label: "推广奖励积分", color: "blue" },
}

type MembershipRule = {
  level: number
  name: string
  thresholdCents: number
  multiplier: number
  canApplyPartner: boolean
  selfCashbackRate: number
}

const MEMBER_LEVEL_RULES: MembershipRule[] = [
  { level: 0, name: "注册会员", thresholdCents: 0, multiplier: 1.0, canApplyPartner: false, selfCashbackRate: 0 },
  { level: 1, name: "初级会员", thresholdCents: 1, multiplier: 1.0, canApplyPartner: false, selfCashbackRate: 5 },
  { level: 2, name: "成长会员", thresholdCents: 5000, multiplier: 1.1, canApplyPartner: false, selfCashbackRate: 8 },
  { level: 3, name: "专业会员", thresholdCents: 20000, multiplier: 1.3, canApplyPartner: true, selfCashbackRate: 10 },
  { level: 4, name: "商务会员", thresholdCents: 50000, multiplier: 1.5, canApplyPartner: true, selfCashbackRate: 15 },
  { level: 5, name: "旗舰会员", thresholdCents: 100000, multiplier: 2.0, canApplyPartner: true, selfCashbackRate: 20 },
]

export default function MembershipPage() {
  const [membership, setMembership] = useState<UserMembership | null>(null)
  const [pointLogs, setPointLogs] = useState<PointLog[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    async function load() {
      setLoading(true)
      try {
        const [member, logs] = await Promise.all([
          getMyMembership(),
          getPointLogs(20, 0),
        ])
        setMembership(member)
        setPointLogs(logs)
      } finally {
        setLoading(false)
      }
    }
    load()
  }, [])

  const currentRule = useMemo(
    () => MEMBER_LEVEL_RULES.find((rule) => rule.level === membership?.member_level?.level) ?? MEMBER_LEVEL_RULES[0],
    [membership?.member_level?.level],
  )
  const currentQuarterSpent = membership?.current_quarter_self_spent ?? membership?.current_quarter_spent ?? 0
  const nextLevel = MEMBER_LEVEL_RULES.find((rule) => rule.thresholdCents > currentQuarterSpent) ?? null
  const progressPercent = nextLevel
    ? Math.min(100, Math.round((currentQuarterSpent / nextLevel.thresholdCents) * 100))
    : 100

  if (loading) {
    return <Spin size="large" description="加载会员中心" style={{ display: "flex", justifyContent: "center", padding: 80 }} />
  }

  return (
    <Space orientation="vertical" size={20} style={{ width: "100%" }}>
      <div>
        <Title level={3} style={{ marginBottom: 4 }}>会员中心</Title>
        <Paragraph type="secondary" style={{ marginBottom: 0 }}>
          会员中心只展示会员等级、积分和自购成长。推广奖励请前往 <Link to="/promotion">推广中心</Link>，代理申请请前往 <Link to="/agent">代理中心</Link>。
        </Paragraph>
      </div>

      <Row gutter={[16, 16]}>
        <Col xs={24} md={6}>
          <Card variant="outlined">
            <Statistic title="当前等级" value={`LV${currentRule.level}`} prefix={<CrownOutlined />} />
            <Text type="secondary">{currentRule.name}</Text>
          </Card>
        </Col>
        <Col xs={24} md={6}>
          <Card variant="outlined">
            <Statistic title="当前季度自购" value={formatYuan(currentQuarterSpent)} prefix={<WalletOutlined />} />
          </Card>
        </Col>
        <Col xs={24} md={6}>
          <Card variant="outlined">
            <Statistic title="可用积分" value={formatPoints(membership?.available_points ?? 0)} prefix={<GiftOutlined />} />
          </Card>
        </Col>
        <Col xs={24} md={6}>
          <Card variant="outlined">
            <Statistic title="累计积分" value={formatPoints(membership?.total_points ?? 0)} prefix={<RiseOutlined />} />
          </Card>
        </Col>
      </Row>

      <Card variant="outlined" title="成长进度">
        <Space orientation="vertical" size={16} style={{ width: "100%" }}>
          <Text>
            {nextLevel
              ? `距离 LV${nextLevel.level} ${nextLevel.name} 还需 ${formatYuan(Math.max(0, nextLevel.thresholdCents - currentQuarterSpent))}`
              : "已达到当前最高会员等级"}
          </Text>
          <Progress percent={progressPercent} />
        </Space>
      </Card>

      <Card variant="outlined" title="会员等级">
        <Table<MembershipRule>
          rowKey="level"
          size="middle"
          pagination={false}
          dataSource={MEMBER_LEVEL_RULES}
          columns={levelColumns(currentRule.level)}
          scroll={{ x: 860 }}
        />
      </Card>

      <Card variant="outlined" title="积分流水">
        {pointLogs.length === 0 ? (
          <Empty description="暂无积分流水" />
        ) : (
          <Table<PointLog>
            rowKey={(record) => String(record.id ?? `${record.change_type}-${record.created_at}-${record.ref_no ?? ""}-${record.delta}`)}
            size="small"
            pagination={false}
            dataSource={pointLogs}
            columns={pointLogColumns()}
          />
        )}
      </Card>
    </Space>
  )
}

function levelColumns(currentLevel: number): ColumnsType<MembershipRule> {
  return [
    {
      title: "等级",
      dataIndex: "level",
      fixed: "left",
      render: (level: number, row) => (
        <Space>
          <CrownOutlined />
          <Text strong>LV{level}</Text>
          <Text>{row.name}</Text>
          {level === currentLevel && <Tag color="blue">当前</Tag>}
        </Space>
      ),
    },
    {
      title: "升级/保级条件",
      dataIndex: "thresholdCents",
      render: (value: number) => value > 0 ? formatYuan(value) : "注册即得",
    },
    {
      title: "积分获取倍率",
      dataIndex: "multiplier",
      render: (value: number) => `${value.toFixed(1)}x`,
    },
    {
      title: "伙伴申请资格",
      dataIndex: "canApplyPartner",
      render: (value: boolean) => value ? <Tag color="blue">可申请伙伴</Tag> : <Tag>无</Tag>,
    },
    {
      title: "自购积分返现",
      dataIndex: "selfCashbackRate",
      render: (value: number) => value > 0 ? `${value}%` : "无",
    },
  ]
}

function pointLogColumns(): ColumnsType<PointLog> {
  return [
    {
      title: "类型",
      dataIndex: "change_type",
      width: 160,
      render: (value: string) => {
        const meta = POINT_CHANGE_TYPE_MAP[value] || { label: value, color: "default" }
        return <Tag color={meta.color}>{meta.label}</Tag>
      },
    },
    {
      title: "备注",
      dataIndex: "remark",
      render: (value: string | null, row) => (
        <Space orientation="vertical" size={0}>
          <Text>{value || "-"}</Text>
          <Text type="secondary">{row.ref_no || "-"}</Text>
        </Space>
      ),
    },
    {
      title: "时间",
      dataIndex: "created_at",
      width: 180,
      render: (value: string) => new Date(value).toLocaleString(),
    },
    {
      title: "变动",
      dataIndex: "delta",
      align: "right",
      width: 140,
      render: (value: number) => (
        <Text type={value >= 0 ? "success" : "danger"} strong>
          {value > 0 ? "+" : ""}{formatPoints(value)}
        </Text>
      ),
    },
  ]
}
