import { useCallback, useEffect, useMemo, useState } from "react"
import { Link } from "react-router-dom"
import {
  Alert,
  Badge,
  Button,
  Card,
  Col,
  Empty,
  Form,
  Input,
  Modal,
  Row,
  Select,
  Space,
  Spin,
  Statistic,
  Table,
  Tag,
  Typography,
  message,
} from "antd"
import type { TableColumnsType } from "antd"
import {
  CheckCircleOutlined,
  ClockCircleOutlined,
  CloseCircleOutlined,
  CopyOutlined,
  CrownOutlined,
  DollarOutlined,
  EditOutlined,
  LinkOutlined,
  SendOutlined,
  TeamOutlined,
} from "@ant-design/icons"
import {
  applyAgent,
  getAgentCustomers,
  getAgentOverview,
  getAgentSettlements,
  listPublicAgentTiers,
  type AgentCustomerItem,
  type AgentOverview,
  type AgentSettlementItem,
  type AgentTier,
} from "../api/agent"
import { getMyMembership, type UserMembership } from "../api/membership"
import { updatePromotionInviteCode } from "../api/promotion"
import { formatPoints, formatYuan } from "../utils/format"

const { Text, Title, Paragraph } = Typography
const { TextArea } = Input

const STATUS_MAP: Record<string, { label: string; color: "success" | "processing" | "warning" | "error" | "default"; icon: React.ReactNode }> = {
  pending: { label: "待审核", color: "processing", icon: <ClockCircleOutlined /> },
  active: { label: "已激活", color: "success", icon: <CheckCircleOutlined /> },
  observing: { label: "观察期", color: "warning", icon: <ClockCircleOutlined /> },
  risk_locked: { label: "风控锁定", color: "error", icon: <CloseCircleOutlined /> },
  suspended: { label: "已暂停", color: "warning", icon: <ClockCircleOutlined /> },
  rejected: { label: "已拒绝", color: "error", icon: <CloseCircleOutlined /> },
  terminated: { label: "已清退", color: "default", icon: <CloseCircleOutlined /> },
}

const SETTLEMENT_TYPE_MAP: Record<string, { label: string; color: string }> = {
  agent_profit: { label: "代理差价收益", color: "green" },
  agent_subsidy: { label: "代理补贴", color: "red" },
  member_commission: { label: "会员推广奖励", color: "blue" },
}

export default function AgentCenter() {
  const [loading, setLoading] = useState(true)
  const [overview, setOverview] = useState<AgentOverview | null>(null)
  const [membership, setMembership] = useState<UserMembership | null>(null)
  const [tiers, setTiers] = useState<AgentTier[]>([])
  const [customers, setCustomers] = useState<AgentCustomerItem[]>([])
  const [settlements, setSettlements] = useState<AgentSettlementItem[]>([])
  const [applyOpen, setApplyOpen] = useState(false)
  const [applying, setApplying] = useState(false)
  const [applyForm] = Form.useForm()
  const [inviteOpen, setInviteOpen] = useState(false)
  const [updatingInvite, setUpdatingInvite] = useState(false)
  const [inviteForm] = Form.useForm<{ invite_code: string }>()

  const load = useCallback(async () => {
    setLoading(true)
    try {
      const [ov, tierRes, memberRes] = await Promise.all([
        getAgentOverview(),
        listPublicAgentTiers(),
        getMyMembership(),
      ])
      setOverview(ov.data ?? null)
      setTiers(tierRes.data ?? [])
      setMembership(memberRes)

      if (["active", "observing"].includes(ov.data?.agent?.status || "")) {
        const [custRes, settleRes] = await Promise.all([
          getAgentCustomers(0, 50),
          getAgentSettlements(0, 50),
        ])
        setCustomers(custRes.data?.items ?? [])
        setSettlements(settleRes.data?.items ?? [])
      } else {
        setCustomers([])
        setSettlements([])
      }
    } catch {
      message.error("加载代理中心失败")
    } finally {
      setLoading(false)
    }
  }, [])

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

  const agent = overview?.agent
  const isAgent = agent?.status === "active" || agent?.status === "observing"
  const isPending = agent?.status === "pending"
  const isRejected = agent?.status === "rejected"
  const isRiskLocked = agent?.status === "risk_locked"
  const statusMeta = agent?.status ? STATUS_MAP[agent.status] : null
  const memberLevel = membership?.member_level?.level ?? 0
  const inviteCode = overview?.invite_code ?? ""
  const inviteChangeCount = overview?.invite_code_change_count ?? 0
  const inviteChangeLimit = overview?.invite_code_change_limit ?? 3
  const inviteChangeRemaining = overview?.invite_code_change_remaining ?? 0
  const inviteEditEnabled = Boolean(overview?.invite_code_edit_enabled)

  const eligibleTiers = useMemo(
    () => tiers.filter((tier) => memberLevel >= tier.min_member_level),
    [memberLevel, tiers],
  )

  const handleApply = async (values: { tier: string; reason: string; channels: string }) => {
    setApplying(true)
    try {
      await applyAgent(values.tier, values.reason, values.channels)
      message.success("代理申请已提交，请等待管理员审核")
      setApplyOpen(false)
      applyForm.resetFields()
      load()
    } catch (e: unknown) {
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      message.error(detail || "提交失败")
    } finally {
      setApplying(false)
    }
  }

  const openInviteEditor = () => {
    if (!inviteEditEnabled) {
      message.warning("当前暂不支持修改邀请码")
      return
    }
    if (inviteChangeRemaining <= 0) {
      message.warning("邀请码最多可修改 3 次")
      return
    }
    inviteForm.setFieldsValue({ invite_code: inviteCode })
    setInviteOpen(true)
  }

  const handleInviteUpdate = async (values: { invite_code: string }) => {
    setUpdatingInvite(true)
    try {
      const data = await updatePromotionInviteCode(values.invite_code)
      setOverview((prev) => prev ? {
        ...prev,
        invite_code: data.invite_code,
        invite_code_edit_enabled: data.invite_code_edit_enabled,
        invite_code_change_count: data.invite_code_change_count,
        invite_code_change_limit: data.invite_code_change_limit,
        invite_code_change_remaining: data.invite_code_change_remaining,
      } : prev)
      setInviteOpen(false)
      message.success("邀请码已更新，旧邀请码仍可继续使用")
    } catch (e: unknown) {
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      message.error(detail || "邀请码更新失败")
    } finally {
      setUpdatingInvite(false)
    }
  }

  const copyInviteLink = async () => {
    if (!inviteCode) return
    const url = `${window.location.origin}/register?ref=${inviteCode}`
    await navigator.clipboard?.writeText(url)
    message.success("邀请链接已复制")
  }

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

  return (
    <Space orientation="vertical" size={20} style={{ width: "100%" }}>
      <Row justify="space-between" align="middle" gutter={[16, 16]}>
        <Col>
          <Title level={3} style={{ marginBottom: 4 }}>代理中心</Title>
          <Paragraph type="secondary" style={{ marginBottom: 0 }}>
            代理伙伴按后台配置的成本价结算。普通会员推广请前往 <Link to="/promotion">推广中心</Link>。
          </Paragraph>
        </Col>
        <Col>
          {!isAgent && !isPending && (
            <Button type="primary" size="large" icon={<SendOutlined />} onClick={() => setApplyOpen(true)}>
              {isRejected ? "重新申请" : "申请成为代理"}
            </Button>
          )}
        </Col>
      </Row>

      {agent?.review_message && !isAgent && (
        <Alert
          type={isRejected ? "warning" : isAgent ? "success" : "info"}
          showIcon
          title={isRejected ? "申请未通过" : isAgent ? "审核通过" : "审核结果"}
          description={agent.review_message}
        />
      )}

      {agent?.status === "observing" && (
        <Alert
          type="warning"
          showIcon
          title="代理观察期"
          description={`当前仍按原代理档位结算。观察截止：${agent.observe_until ? new Date(agent.observe_until).toLocaleString() : "-"}`}
        />
      )}

      {isRiskLocked && (
        <Alert
          type="error"
          showIcon
          title="代理风控锁定"
          description={agent?.risk_reason || "该状态下不会产生新的代理差价结算，请联系管理员处理。"}
        />
      )}

      <Alert
        type="info"
        showIcon
        title="当前版本规则"
        description="代理收益以积分形式发放，1000积分=1元。客户实付低于代理成本的补贴订单暂不支持，后续完成代理余额/冻结余额后再开放。因部分地区有限价（如浙江宁波，禁止降低起售价），限价产品不参与代理折扣。"
      />

      <Row gutter={[16, 16]}>
        <Col xs={24} md={6}>
          <Card variant="outlined">
            <Statistic title="代理状态" value={statusMeta?.label ?? "未申请"} prefix={statusMeta?.icon ?? <CrownOutlined />} />
          </Card>
        </Col>
        <Col xs={24} md={6}>
          <Card variant="outlined">
            <Statistic title="当前档位" value={agent?.agent_tier?.name ?? "暂无"} prefix={<CrownOutlined />} />
          </Card>
        </Col>
        <Col xs={24} md={6}>
          <Card variant="outlined">
            <Statistic title="代理客户" value={overview?.customer_count ?? 0} prefix={<TeamOutlined />} />
          </Card>
        </Col>
        <Col xs={24} md={6}>
          <Card variant="outlined">
            <Statistic title="代理收益积分" value={formatPoints((overview?.total_profit ?? 0) * 10)} prefix={<DollarOutlined />} />
          </Card>
        </Col>
      </Row>

      <Card variant="outlined" title="代理档位">
        {tiers.length === 0 ? (
          <Empty description="后台尚未配置代理档位" />
        ) : (
          <Row gutter={[12, 12]}>
            {tiers.map((tier) => {
              const current = agent?.agent_tier?.id === tier.id
              const eligible = memberLevel >= tier.min_member_level
              return (
                <Col key={tier.id} xs={24} md={8}>
                  <Card size="small" style={{ borderColor: current ? "#1677ff" : undefined, background: current ? "#f0f5ff" : undefined }}>
                    <Space orientation="vertical" size={6}>
                      <Space>
                        <Text strong>{tier.name}</Text>
                        {current && <Tag color="blue">当前</Tag>}
                        {!eligible && <Tag>LV{tier.min_member_level}开放</Tag>}
                      </Space>
                      <Text type="secondary">代理成本：{(tier.cost_rate / 100).toFixed(1)}%</Text>
                      <Text type="secondary">最低会员等级：LV{tier.min_member_level}</Text>
                      <Text type="secondary">最低累计消费：{tier.min_total_spend > 0 ? formatYuan(tier.min_total_spend) : "无门槛"}</Text>
                      {tier.description && <Text type="secondary">{tier.description}</Text>}
                    </Space>
                  </Card>
                </Col>
              )
            })}
          </Row>
        )}
      </Card>

      <Card
        variant="outlined"
        title={<Space><LinkOutlined />邀请码</Space>}
        extra={
          <Button
            icon={<EditOutlined />}
            onClick={openInviteEditor}
            disabled={!inviteEditEnabled || inviteChangeRemaining <= 0}
          >
            修改
          </Button>
        }
      >
        <Space orientation="vertical" size={10} style={{ width: "100%" }}>
          <Space wrap>
            <Text type="secondary">当前邀请码</Text>
            <Text code copyable={!!inviteCode}>{inviteCode || "暂未生成"}</Text>
            <Button size="small" icon={<CopyOutlined />} disabled={!inviteCode} onClick={copyInviteLink}>
              复制邀请链接
            </Button>
          </Space>
          <Text type="secondary">
            已修改 {inviteChangeCount} / {inviteChangeLimit} 次，剩余 {inviteChangeRemaining} 次。旧邀请码会一直有效。
          </Text>
        </Space>
      </Card>

      {isAgent && (
        <>
          <Card variant="outlined" title={<Space><TeamOutlined />我的代理客户</Space>}>
            {customers.length === 0 ? (
              <Empty description="暂无代理客户" />
            ) : (
              <Table rowKey="id" size="small" columns={customerColumns()} dataSource={customers} pagination={false} />
            )}
          </Card>
          <Card variant="outlined" title={<Space><DollarOutlined />代理收益流水</Space>}>
            {settlements.length === 0 ? (
              <Empty description="暂无代理收益" />
            ) : (
              <Table rowKey="id" size="small" columns={settlementColumns()} dataSource={settlements} pagination={false} scroll={{ x: 860 }} />
            )}
          </Card>
        </>
      )}

      <Modal title="修改邀请码" open={inviteOpen} onCancel={() => setInviteOpen(false)} footer={null} width={520} destroyOnHidden>
        <Alert
          type="info"
          showIcon
          style={{ marginBottom: 16 }}
          title={`每个账号最多可修改 ${inviteChangeLimit} 次，当前剩余 ${inviteChangeRemaining} 次`}
          description="保存后旧的邀请码仍然有效，已绑定的下级不会受影响。"
        />
        <Form form={inviteForm} layout="vertical" onFinish={handleInviteUpdate}>
          <Form.Item
            name="invite_code"
            label="新邀请码"
            rules={[
              { required: true, message: "请输入新邀请码" },
              { min: 4, max: 32, message: "邀请码长度需为 4-32 个字符" },
              { pattern: /^[A-Za-z0-9_-]+$/, message: "仅支持字母、数字、下划线和短横线" },
            ]}
          >
            <Input placeholder="输入新的邀请码" maxLength={32} autoComplete="off" />
          </Form.Item>
          <Button type="primary" htmlType="submit" block loading={updatingInvite}>
            保存修改
          </Button>
        </Form>
      </Modal>

      <Modal title="代理申请" open={applyOpen} onCancel={() => setApplyOpen(false)} footer={null} width={560} destroyOnHidden>
        <Alert
          type="info"
          showIcon
          style={{ marginBottom: 16 }}
          title={`当前会员等级 LV${memberLevel}`}
          description="请选择你要申请的代理档位，并说明推广渠道。代理审核通过后，该推广关系下的客户订单将按代理差价结算，不再叠加普通推广奖励。"
        />
        <Form form={applyForm} layout="vertical" onFinish={handleApply}>
          <Form.Item name="tier" label="申请档位" rules={[{ required: true, message: "请选择代理档位" }]}>
            <Select placeholder={eligibleTiers.length ? "选择代理档位" : "当前会员等级暂不可申请"}>
              {tiers.map((tier) => (
                <Select.Option key={tier.code} value={tier.code} disabled={memberLevel < tier.min_member_level}>
                  {tier.name} · 成本 {(tier.cost_rate / 100).toFixed(1)}% · LV{tier.min_member_level}+
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="reason" label="申请理由" rules={[{ required: true, message: "请填写申请理由" }]}>
            <TextArea rows={3} placeholder="描述你的推广经验、客户来源和申请原因" maxLength={500} showCount />
          </Form.Item>
          <Form.Item name="channels" label="预计推广渠道" rules={[{ required: true, message: "请填写推广渠道" }]}>
            <TextArea rows={2} placeholder="例如：社群、网站、短视频平台、技术论坛等" maxLength={300} showCount />
          </Form.Item>
          <Button type="primary" htmlType="submit" block size="large" loading={applying} disabled={eligibleTiers.length === 0}>
            提交申请
          </Button>
        </Form>
      </Modal>
    </Space>
  )
}

function customerColumns(): TableColumnsType<AgentCustomerItem> {
  return [
    {
      title: "客户",
      key: "customer",
      render: (_value, row) => row.customer ? (
        <Space>
          <TeamOutlined />
          <Space orientation="vertical" size={0}>
            <Text strong>{row.customer.nickname || row.customer.username}</Text>
            <Text type="secondary" style={{ fontSize: 12 }}>ID {row.customer_user_id}</Text>
          </Space>
        </Space>
      ) : <Text type="secondary">用户 #{row.customer_user_id}</Text>,
    },
    { title: "绑定方式", dataIndex: "bind_source", width: 120, render: (value: string) => value === "invite_code" ? "邀请码" : value },
    { title: "绑定时间", dataIndex: "bound_at", width: 180, render: (value: string) => value ? new Date(value).toLocaleString() : "-" },
    { title: "状态", dataIndex: "status", width: 100, render: (value: string) => <Badge status={value === "active" ? "success" : "default"} text={value} /> },
  ]
}

function settlementColumns(): TableColumnsType<AgentSettlementItem> {
  return [
    { title: "订单", dataIndex: "order_no", width: 220, render: (value: string) => <Link to={`/orders/${value}`}>{value}</Link> },
    { title: "类型", dataIndex: "settlement_type", width: 130, render: (value: string) => {
      const meta = SETTLEMENT_TYPE_MAP[value] || { label: value, color: "default" }
      return <Tag color={meta.color}>{meta.label}</Tag>
    } },
    { title: "订单金额", dataIndex: "standard_amount", width: 110, align: "right", render: (value: number) => formatYuan(value) },
    { title: "客户实付", dataIndex: "customer_pay_amount", width: 110, align: "right", render: (value: number) => formatYuan(value) },
    { title: "代理成本", dataIndex: "agent_cost_amount", width: 110, align: "right", render: (value: number | null) => value == null ? "-" : formatYuan(value) },
    { title: "收益", dataIndex: "delta_amount", width: 140, align: "right", render: (value: number) => (
      <Space orientation="vertical" size={0} style={{ alignItems: "flex-end" }}>
        <Text type={value > 0 ? "success" : "secondary"} strong>{value > 0 ? "+" : ""}{formatYuan(value)}</Text>
        {value > 0 && <Text type="secondary" style={{ fontSize: 10 }}>+{formatPoints(value * 10)}积分</Text>}
      </Space>
    ) },
    { title: "状态", dataIndex: "status", width: 130, render: (value: string, row) => {
      if (value === "settled") return <Tag color="green">已结算</Tag>
      if (value === "frozen") {
        return (
          <Space orientation="vertical" size={0}>
            <Tag color="gold">冻结中</Tag>
            {row.frozen_until && <Text type="secondary" style={{ fontSize: 10 }}>{new Date(row.frozen_until).toLocaleString()}</Text>}
          </Space>
        )
      }
      if (value === "reversed") return <Tag color="red">已扣回</Tag>
      return <Tag>待开通</Tag>
    } },
    { title: "时间", dataIndex: "created_at", width: 180, render: (value: string) => value ? new Date(value).toLocaleString() : "-" },
  ]
}
