import { useCallback, useEffect, useMemo, useState } from "react"
import {
  Badge,
  Button,
  Card,
  Col,
  Empty,
  Form,
  Input,
  InputNumber,
  Modal,
  Row,
  Select,
  Space,
  Statistic,
  Switch,
  Table,
  Tag,
  Typography,
  message,
} from "antd"
import type { TableColumnsType } from "antd"
import { CheckCircleOutlined, CloseCircleOutlined, CrownOutlined, DeleteOutlined, EditOutlined, PlusOutlined, ReloadOutlined } from "@ant-design/icons"
import { createAgentTier, deleteAgentTier, listAgentTiers, updateAgentTier, type AdminAgentTier } from "../api/agent"

const { Text, Title, Paragraph } = Typography

const AGENT_TIER_PRESETS = [
  { label: "云启伙伴", value: "云启伙伴" },
  { label: "云享伙伴", value: "云享伙伴" },
  { label: "云策伙伴", value: "云策伙伴" },
  { label: "云领伙伴", value: "云领伙伴" },
  { label: "云尊伙伴", value: "云尊伙伴" },
  { label: "云冠伙伴", value: "云冠伙伴" },
]

const AGENT_TIER_CODE_PRESETS = [
  { label: "yunqi", value: "yunqi" },
  { label: "yunxiang", value: "yunxiang" },
  { label: "yunce", value: "yunce" },
  { label: "yunling", value: "yunling" },
  { label: "yunzun", value: "yunzun" },
  { label: "yunguan", value: "yunguan" },
]

function yuan(cents: number | null | undefined) {
  return `¥${((cents ?? 0) / 100).toFixed(2)}`
}

function rate(bps: number | null | undefined) {
  return `${((bps ?? 0) / 100).toFixed(1)}%`
}

export default function AdminAgentTiers() {
  const [loading, setLoading] = useState(true)
  const [items, setItems] = useState<AdminAgentTier[]>([])
  const [modalOpen, setModalOpen] = useState(false)
  const [editing, setEditing] = useState<AdminAgentTier | null>(null)
  const [saving, setSaving] = useState(false)
  const [form] = Form.useForm()

  const reload = useCallback(async () => {
    setLoading(true)
    try {
      const res = await listAgentTiers()
      setItems(res.data ?? [])
    } catch {
      message.error("加载失败")
    } finally {
      setLoading(false)
    }
  }, [])

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

  const defaultValues = {
    enabled: true,
    auto_downgrade_enabled: true,
    sort_order: 0,
    min_member_level: 3,
    min_total_spend: 0,
    cost_rate: 7800,
    monthly_sales_required: 0,
    monthly_active_customers_required: 0,
    max_refund_rate_bps: 5000,
    max_monthly_subsidy_cents: 10000,
    min_balance_for_subsidy_cents: 12800,
    observe_days: 7,
    freeze_days: 7,
    max_coupon_discount_rate: 5000,
    max_monthly_coupon_count: 10,
  }

  const openCreate = () => {
    setEditing(null)
    form.resetFields()
    form.setFieldsValue(defaultValues)
    setModalOpen(true)
  }

  const openEdit = (tier: AdminAgentTier) => {
    setEditing(tier)
    form.setFieldsValue({ ...defaultValues, ...tier })
    setModalOpen(true)
  }

  const handleDelete = async (id: number) => {
    try {
      await deleteAgentTier(id)
      message.success("已删除")
      void reload()
    } catch (e: unknown) {
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      message.error(detail || "删除失败")
    }
  }

  const handleSave = async () => {
    try {
      const values = await form.validateFields()
      setSaving(true)
      if (editing) {
        await updateAgentTier(editing.id, values)
        message.success("已更新")
      } else {
        await createAgentTier(values)
        message.success("已创建")
      }
      setModalOpen(false)
      void reload()
    } catch (e: unknown) {
      if (e && typeof e === "object" && "errorFields" in e) return
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      message.error(detail || "保存失败")
    } finally {
      setSaving(false)
    }
  }

  const columns: TableColumnsType<AdminAgentTier> = [
    {
      title: "档位",
      key: "name",
      width: 200,
      render: (_v, r) => (
        <Space>
          <CrownOutlined style={{ fontSize: 20, color: r.enabled ? "#1677ff" : "#d9d9d9" }} />
          <Space orientation="vertical" size={0}>
            <Text strong>{r.name}</Text>
            <Text type="secondary" style={{ fontSize: 12 }}>标识：{r.code}</Text>
          </Space>
        </Space>
      ),
    },
    { title: "成本折扣", dataIndex: "cost_rate", width: 100, align: "center", render: rate },
    { title: "最低会员", dataIndex: "min_member_level", width: 100, align: "center", render: (v: number) => <Tag>LV{v}</Tag> },
    { title: "申请消费", dataIndex: "min_total_spend", width: 120, align: "right", render: yuan },
    {
      title: "30天保级",
      key: "lifecycle",
      width: 180,
      render: (_v, r) => (
        <Space orientation="vertical" size={0}>
          <Text style={{ fontSize: 12 }}>净销售 {yuan(r.monthly_sales_required)}</Text>
          <Text style={{ fontSize: 12 }}>有效客户 {r.monthly_active_customers_required}</Text>
        </Space>
      ),
    },
    {
      title: "风控",
      key: "risk",
      width: 170,
      render: (_v, r) => (
        <Space orientation="vertical" size={0}>
          <Text style={{ fontSize: 12 }}>退款率 {rate(r.max_refund_rate_bps)}</Text>
          <Text style={{ fontSize: 12 }}>补贴 {yuan(r.max_monthly_subsidy_cents)}</Text>
        </Space>
      ),
    },
    { title: "观察期", dataIndex: "observe_days", width: 90, align: "center", render: (v: number) => `${v}天` },
    { title: "排序", dataIndex: "sort_order", width: 70, align: "center" },
    { title: "状态", dataIndex: "enabled", width: 80, align: "center", render: (v: boolean) => <Badge status={v ? "success" : "default"} text={v ? "启用" : "禁用"} /> },
    { title: "说明", dataIndex: "description", width: 200, ellipsis: true },
    {
      title: "操作",
      key: "action",
      width: 120,
      align: "right",
      render: (_v, r) => (
        <Space size={4}>
          <Button size="small" icon={<EditOutlined />} onClick={() => openEdit(r)} />
          <Button
            size="small"
            danger
            icon={<DeleteOutlined />}
            onClick={() => Modal.confirm({ title: `删除 ${r.name}？`, onOk: () => handleDelete(r.id) })}
          />
        </Space>
      ),
    },
  ]

  const stats = useMemo(() => {
    const enabled = items.filter((item) => item.enabled).length
    return { total: items.length, enabled }
  }, [items])

  return (
    <Space orientation="vertical" size={20} style={{ width: "100%" }}>
      <Row justify="space-between" align="bottom">
        <Col>
          <Title level={3}>代理档位配置</Title>
          <Paragraph type="secondary">配置代理档位、成本折扣、准入条件、保级规则和风控阈值。</Paragraph>
        </Col>
        <Col>
          <Space>
            <Button icon={<ReloadOutlined />} loading={loading} onClick={reload}>刷新</Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>添加档位</Button>
          </Space>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col xs={24} sm={8}><Card variant="outlined"><Statistic title="档位总数" value={stats.total} prefix={<CrownOutlined />} /></Card></Col>
        <Col xs={24} sm={8}><Card variant="outlined"><Statistic title="已启用" value={stats.enabled} prefix={<CheckCircleOutlined />} styles={{ content: { color: "#52c41a" } }} /></Card></Col>
        <Col xs={24} sm={8}><Card variant="outlined"><Statistic title="已禁用" value={stats.total - stats.enabled} prefix={<CloseCircleOutlined />} styles={{ content: { color: "#ff4d4f" } }} /></Card></Col>
      </Row>

      <Card variant="outlined" title="代理档位列表">
        <Table
          rowKey="id"
          loading={loading}
          columns={columns}
          dataSource={items}
          pagination={false}
          size="middle"
          scroll={{ x: 1280 }}
          locale={{ emptyText: <Empty description="暂无档位"><Button type="primary" onClick={openCreate}>添加第一个档位</Button></Empty> }}
        />
      </Card>

      <Modal
        title={editing ? "编辑档位" : "新建档位"}
        open={modalOpen}
        onOk={handleSave}
        onCancel={() => setModalOpen(false)}
        confirmLoading={saving}
        destroyOnHidden
        width={720}
      >
        <Form form={form} layout="vertical" style={{ marginTop: 16 }}>
          <Row gutter={16}>
            <Col xs={24} md={12}>
              <Form.Item name="name" label="档位名称" rules={[{ required: true, message: "请输入名称" }]}>
                <Select options={AGENT_TIER_PRESETS} />
              </Form.Item>
            </Col>
            <Col xs={24} md={12}>
              <Form.Item name="code" label="档位标识" rules={[{ required: true, message: "请输入标识" }]}>
                <Select options={AGENT_TIER_CODE_PRESETS} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col xs={24} md={12}><Form.Item name="cost_rate" label="成本折扣（万分比，7800=78%）" rules={[{ required: true }]}><InputNumber min={1} max={10000} style={{ width: "100%" }} /></Form.Item></Col>
            <Col xs={24} md={12}><Form.Item name="min_member_level" label="申请最低会员等级"><InputNumber min={0} max={99} precision={0} style={{ width: "100%" }} /></Form.Item></Col>
            <Col xs={24} md={12}><Form.Item name="min_total_spend" label="申请最低累计消费（分）"><InputNumber min={0} precision={0} style={{ width: "100%" }} /></Form.Item></Col>
            <Col xs={24} md={12}><Form.Item name="sort_order" label="排序"><InputNumber min={0} precision={0} style={{ width: "100%" }} /></Form.Item></Col>
          </Row>
          <Row gutter={16}>
            <Col xs={24} md={12}><Form.Item name="monthly_sales_required" label="30天保级净销售额（分）"><InputNumber min={0} precision={0} style={{ width: "100%" }} /></Form.Item></Col>
            <Col xs={24} md={12}><Form.Item name="monthly_active_customers_required" label="30天保级有效客户数"><InputNumber min={0} precision={0} style={{ width: "100%" }} /></Form.Item></Col>
            <Col xs={24} md={12}><Form.Item name="observe_days" label="观察期天数"><InputNumber min={1} max={90} precision={0} style={{ width: "100%" }} /></Form.Item></Col>
            <Col xs={24} md={12}><Form.Item name="auto_downgrade_enabled" label="自动降级" valuePropName="checked"><Switch /></Form.Item></Col>
          </Row>
          <Row gutter={16}>
            <Col xs={24} md={12}><Form.Item name="max_refund_rate_bps" label="风控退款率阈值（万分比，5000=50%）"><InputNumber min={0} max={10000} precision={0} style={{ width: "100%" }} /></Form.Item></Col>
            <Col xs={24} md={12}><Form.Item name="max_monthly_subsidy_cents" label="30天补贴亏损阈值（分）"><InputNumber min={0} precision={0} style={{ width: "100%" }} /></Form.Item></Col>
            <Col xs={24} md={12}><Form.Item name="min_balance_for_subsidy_cents" label="补贴风控余额阈值（分）"><InputNumber min={0} precision={0} style={{ width: "100%" }} /></Form.Item></Col>
            <Col xs={24} md={12}><Form.Item name="freeze_days" label="冻结期参考天数"><InputNumber min={1} max={90} precision={0} style={{ width: "100%" }} /></Form.Item></Col>
          </Row>
          <Row gutter={16}>
            <Col xs={24} md={12}><Form.Item name="max_coupon_discount_rate" label="最大优惠券折扣力度（万分比）"><InputNumber min={0} max={10000} precision={0} style={{ width: "100%" }} /></Form.Item></Col>
            <Col xs={24} md={12}><Form.Item name="max_monthly_coupon_count" label="每月最大发券数"><InputNumber min={0} precision={0} style={{ width: "100%" }} /></Form.Item></Col>
          </Row>
          <Form.Item name="enabled" label="启用" valuePropName="checked"><Switch /></Form.Item>
          <Form.Item name="description" label="说明"><Input.TextArea rows={2} placeholder="输入说明文字" /></Form.Item>
        </Form>
      </Modal>
    </Space>
  )
}
