import { useCallback, useEffect, useMemo, useState } from "react"
import { Link } from "react-router-dom"
import {
  Button,
  Card,
  Col,
  Input,
  Row,
  Space,
  Spin,
  Statistic,
  Tag,
  Typography,
  message,
} from "antd"
import {
  CheckCircleOutlined,
  QqOutlined,
  YoutubeOutlined,
  CalendarOutlined,
  WalletOutlined,
  ShoppingCartOutlined,
  ShareAltOutlined,
  TeamOutlined,
} from "@ant-design/icons"
import {
  completeBilibiliTask,
  completeQQTask,
  dailyCheckin,
  getPointCenterOverview,
  withdrawPoints,
  type PointCenterOverview,
} from "../api/points"
import { formatPoints, formatYuan } from "../utils/format"

const { Text, Title } = Typography

function feeRateLabel(rateTenThousand: number) {
  return `${(rateTenThousand / 100).toFixed(0)}%`
}

export default function PointsCenter() {
  const [loading, setLoading] = useState(true)
  const [data, setData] = useState<PointCenterOverview | null>(null)
  const [withdrawPointsValue, setWithdrawPointsValue] = useState<string>("")
  const [withdrawing, setWithdrawing] = useState(false)
  const [qqAnswer, setQqAnswer] = useState("")
  const [bilibiliAnswer, setBilibiliAnswer] = useState("")
  const [taskLoading, setTaskLoading] = useState<"qq" | "bilibili" | "checkin" | null>(null)

  const loadData = useCallback(async () => {
    setLoading(true)
    try {
      const ov = await getPointCenterOverview()
      setData(ov)
    } catch (error) {
      const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      message.error(detail || "加载积分中心失败")
    } finally {
      setLoading(false)
    }
  }, [])

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

  const withdrawPreview = useMemo(() => {
    const points = parseInt(withdrawPointsValue || "0", 10)
    if (!points || points <= 0 || !data) return null
    const feePoints = Math.ceil(points * data.settings.withdraw_fee_rate / 10000)
    const netPoints = points - feePoints
    const creditedCents = Math.floor(netPoints / 1000) * 100
    return { points, feePoints, netPoints, creditedCents }
  }, [withdrawPointsValue, data])

  const handleWithdraw = async () => {
    const points = parseInt(withdrawPointsValue, 10)
    if (!points || points <= 0) {
      message.error("请输入有效的积分数量")
      return
    }
    setWithdrawing(true)
    try {
      const res = await withdrawPoints(points)
      message.success(`提现成功，到账 ${formatYuan(res.credited_cents)}`)
      setWithdrawPointsValue("")
      setData((prev) =>
        prev
          ? {
              ...prev,
              available_points: res.available_points,
              balance_cents: res.balance_cents,
              recent_withdrawals: [
                {
                  id: Date.now(),
                  points_amount: res.points_amount,
                  fee_points: res.fee_points,
                  credited_cents: res.credited_cents,
                  status: "completed",
                  created_at: new Date().toISOString(),
                },
                ...prev.recent_withdrawals,
              ].slice(0, 10),
            }
          : prev
      )
    } catch (error) {
      const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      message.error(detail || "提现失败")
    } finally {
      setWithdrawing(false)
    }
  }

  const handleQQ = async () => {
    if (!qqAnswer.trim()) {
      message.error("请输入群主QQ号")
      return
    }
    setTaskLoading("qq")
    try {
      const res = await completeQQTask(qqAnswer.trim())
      message.success(`QQ群任务完成，获得 ${res.reward_points} 积分`)
      setQqAnswer("")
      setData((prev) => (prev ? { ...prev, available_points: res.available_points, qq_rewarded: true } : prev))
    } catch (error) {
      const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      message.error(detail || "任务提交失败")
    } finally {
      setTaskLoading(null)
    }
  }

  const handleBilibili = async () => {
    if (!bilibiliAnswer.trim()) {
      message.error("请输入B站用户名")
      return
    }
    setTaskLoading("bilibili")
    try {
      const res = await completeBilibiliTask(bilibiliAnswer.trim())
      message.success(`B站关注任务完成，获得 ${res.reward_points} 积分`)
      setBilibiliAnswer("")
      setData((prev) => (prev ? { ...prev, available_points: res.available_points, bilibili_rewarded: true } : prev))
    } catch (error) {
      const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      message.error(detail || "任务提交失败")
    } finally {
      setTaskLoading(null)
    }
  }

  const handleCheckin = async () => {
    setTaskLoading("checkin")
    try {
      const { verifyCaptcha } = await import("../utils/geetest")
      const captcha = await verifyCaptcha()
      const res = await dailyCheckin(captcha)
      message.success(`签到成功，获得 ${res.reward_points} 积分`)
      setData((prev) => (prev ? { ...prev, available_points: res.available_points, today_checkin: res.reward_points } : prev))
    } catch (error) {
      const msg = (error as Error)?.message || "签到失败"
      if (msg === "已取消人机验证") return
      const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      message.error(detail || msg)
    } finally {
      setTaskLoading(null)
    }
  }

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

  const taskItems = [
    {
      key: "qq",
      icon: <QqOutlined style={{ fontSize: 28, color: "#1677ff" }} />,
      title: "加入QQ社区",
      desc: "加入官方QQ群，点击已加入并填写群主QQ号验证。",
      reward: data.settings.qq_reward,
      done: data.qq_rewarded,
      action: (
        <Space orientation="vertical" size={8} style={{ width: "100%" }}>
          <Input
            placeholder="填写群主QQ号"
            value={qqAnswer}
            onChange={(e) => setQqAnswer(e.target.value)}
            disabled={data.qq_rewarded}
          />
          <Button
            type="primary"
            block
            loading={taskLoading === "qq"}
            disabled={data.qq_rewarded}
            onClick={handleQQ}
          >
            {data.qq_rewarded ? "已完成" : `提交答案领 ${formatPoints(data.settings.qq_reward)}`}
          </Button>
        </Space>
      ),
    },
    {
      key: "bilibili",
      icon: <YoutubeOutlined style={{ fontSize: 28, color: "#ff4d4f" }} />,
      title: "关注B站",
      desc: "关注官方B站账号，点击已关注并填写B站用户名验证。",
      reward: data.settings.bilibili_reward,
      done: data.bilibili_rewarded,
      action: (
        <Space orientation="vertical" size={8} style={{ width: "100%" }}>
          <Input
            placeholder="填写B站用户名"
            value={bilibiliAnswer}
            onChange={(e) => setBilibiliAnswer(e.target.value)}
            disabled={data.bilibili_rewarded}
          />
          <Button
            type="primary"
            block
            loading={taskLoading === "bilibili"}
            disabled={data.bilibili_rewarded}
            onClick={handleBilibili}
          >
            {data.bilibili_rewarded ? "已完成" : `提交答案领 ${formatPoints(data.settings.bilibili_reward)}`}
          </Button>
        </Space>
      ),
    },
    {
      key: "checkin",
      icon: <CalendarOutlined style={{ fontSize: 28, color: "#52c41a" }} />,
      title: "每日签到",
      desc: `完成人机验证即可签到，随机获得 ${data.settings.checkin_min_points}~${data.settings.checkin_max_points} 积分。`,
      reward: null,
      done: data.today_checkin !== null,
      action: (
        <Button
          type="primary"
          block
          loading={taskLoading === "checkin"}
          disabled={data.today_checkin !== null}
          onClick={handleCheckin}
        >
          {data.today_checkin !== null ? `今日已签到 +${data.today_checkin}` : "立即签到"}
        </Button>
      ),
    },
    {
      key: "self_purchase",
      icon: <ShoppingCartOutlined style={{ fontSize: 28, color: "#faad14" }} />,
      title: "消费返现",
      desc: "购买或续费服务器后，按会员等级获得自购返现积分。",
      reward: null,
      done: false,
      action: (
        <Space orientation="vertical" size={8} style={{ width: "100%" }}>
          {data.self_purchase.count > 0 && (
            <Tag color="orange">
              待领取 {formatPoints(data.self_purchase.points)} 积分（{data.self_purchase.count} 笔）
            </Tag>
          )}
          <Link to="/orders">
            <Button block>{data.self_purchase.count > 0 ? "去领取" : "去消费"}</Button>
          </Link>
        </Space>
      ),
    },
    {
      key: "referral",
      icon: <ShareAltOutlined style={{ fontSize: 28, color: "#1677ff" }} />,
      title: "推广返现",
      desc: "邀请好友注册并下单，获得普通会员推广奖励积分。",
      reward: null,
      done: false,
      action: (
        <Space orientation="vertical" size={8} style={{ width: "100%" }}>
          {data.member_commission.count > 0 && (
            <Tag color="blue">
              待结算 {formatPoints(data.member_commission.points)} 积分（{data.member_commission.count} 笔）
            </Tag>
          )}
          <Link to="/promotion">
            <Button block>去推广中心</Button>
          </Link>
        </Space>
      ),
    },
    {
      key: "agent_profit",
      icon: <TeamOutlined style={{ fontSize: 28, color: "#722ed1" }} />,
      title: "代理收益",
      desc: "成为代理后，下级客户消费可获得代理收益积分。",
      reward: null,
      done: false,
      action: (
        <Space orientation="vertical" size={8} style={{ width: "100%" }}>
          {data.agent_profit.count > 0 && (
            <Tag color="purple">
              待结算 {formatPoints(data.agent_profit.points)} 积分（{data.agent_profit.count} 笔）
            </Tag>
          )}
          <Link to="/agent">
            <Button block>去代理中心</Button>
          </Link>
        </Space>
      ),
    },
  ]

  return (
    <Space orientation="vertical" size={20} style={{ width: "100%" }}>
      <div>
        <Title level={3} style={{ marginBottom: 4 }}>积分中心</Title>
        <Text type="secondary">做任务赚积分，或将积分提现到余额。</Text>
      </div>

      <Row gutter={[16, 16]} align="stretch">
        <Col xs={24} lg={8}>
          <Card variant="outlined" style={{ height: "100%" }}>
            <Space orientation="vertical" size={20} style={{ width: "100%" }}>
              <Statistic
                title="可用积分"
                value={formatPoints(data.available_points)}
                prefix={<WalletOutlined />}
              />
              <Statistic
                title="账户余额"
                value={formatYuan(data.balance_cents)}
                prefix={<WalletOutlined />}
              />

              <div>
                <Text strong>积分提现</Text>
                <Space orientation="vertical" size={8} style={{ width: "100%", marginTop: 8 }}>
                  <Input
                    type="number"
                    min={data.settings.withdraw_min_points}
                    placeholder={`最低 ${formatPoints(data.settings.withdraw_min_points)} 积分`}
                    value={withdrawPointsValue}
                    onChange={(e) => setWithdrawPointsValue(e.target.value)}
                    suffix="积分"
                  />
                  {withdrawPreview && (
                    <Space orientation="vertical" size={0}>
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        手续费 {feeRateLabel(data.settings.withdraw_fee_rate)}：{formatPoints(withdrawPreview.feePoints)}
                      </Text>
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        实际到账：{formatYuan(withdrawPreview.creditedCents)}
                      </Text>
                    </Space>
                  )}
                  <Button
                    type="primary"
                    block
                    loading={withdrawing}
                    onClick={handleWithdraw}
                    disabled={
                      !withdrawPreview ||
                      withdrawPreview.points < data.settings.withdraw_min_points
                    }
                  >
                    提现到余额
                  </Button>
                </Space>
              </div>

              {data.recent_withdrawals.length > 0 && (
                <div>
                  <Text strong>最近提现</Text>
                  <Space orientation="vertical" size={6} style={{ width: "100%" }}>
                    {data.recent_withdrawals.map((item) => (
                      <Text key={item.id} style={{ fontSize: 12 }}>
                        {formatPoints(item.points_amount)} 积分 → {formatYuan(item.credited_cents)}
                        （手续费 {formatPoints(item.fee_points)}）
                      </Text>
                    ))}
                  </Space>
                </div>
              )}
            </Space>
          </Card>
        </Col>

        <Col xs={24} lg={16}>
          <Card variant="outlined" title="积分获取渠道" style={{ height: "100%" }}>
            <Row gutter={[16, 16]}>
              {taskItems.map((item) => (
                <Col key={item.key} xs={24} md={12}>
                  <Card variant="outlined" style={{ height: "100%" }}>
                    <Space orientation="vertical" size={12} style={{ width: "100%" }}>
                      <Space>
                        {item.icon}
                        <Text strong>{item.title}</Text>
                        {item.done && <Tag color="success" icon={<CheckCircleOutlined />}>已完成</Tag>}
                        {item.reward !== null && !item.done && (
                          <Tag color="blue">+{formatPoints(item.reward)}</Tag>
                        )}
                      </Space>
                      <Text type="secondary" style={{ fontSize: 12 }}>{item.desc}</Text>
                      {item.action}
                    </Space>
                  </Card>
                </Col>
              ))}
            </Row>
          </Card>
        </Col>
      </Row>
    </Space>
  )
}
