import { useCallback, useEffect, useMemo, useState } from "react"
import {
  ReloadOutlined,
  SaveOutlined,
  SettingOutlined,
  UploadOutlined,
} from "@ant-design/icons"
import {
  Alert,
  Button,
  Card,
  Col,
  Empty,
  Form,
  Input,
  InputNumber,
  Row,
  Space,
  Statistic,
  Switch,
  Typography,
  Upload,
  type UploadProps,
} from "antd"
import { toast } from "../../utils/toast"
import {
  getBusinessRules,
  updateBusinessRules,
  uploadBrandLogo,
  type BusinessSetting,
  type BusinessSettingValue,
} from "../api/settings"

const { Title, Paragraph, Text } = Typography

const GROUP_LABEL: Record<string, string> = {
  platform: "平台信息",
  refund: "退订规则",
  lifecycle: "到期生命周期",
  upstream: "上游任务同步",
  finance: "充值与财务",
  verification: "实名认证",
  promotion: "推广与结算",
  points: "积分中心",
}

function groupSettings(items: BusinessSetting[]) {
  const groups: Record<string, BusinessSetting[]> = {}
  items.forEach((item) => {
    groups[item.group] = groups[item.group] || []
    groups[item.group].push(item)
  })
  return groups
}

function settingsToValues(list: BusinessSetting[]) {
  return Object.fromEntries(list.map((item) => [item.key, item.value])) as Record<string, BusinessSettingValue>
}

function errorMessage(error: unknown, fallback: string) {
  return (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail || fallback
}

export default function AdminSettings() {
  const [form] = Form.useForm<Record<string, BusinessSettingValue>>()
  const [settings, setSettings] = useState<BusinessSetting[]>([])
  const [loading, setLoading] = useState(false)
  const [saving, setSaving] = useState(false)
  const [uploadingLogo, setUploadingLogo] = useState(false)

  const grouped = useMemo(() => groupSettings(settings), [settings])
  const values = Form.useWatch([], form) || {}

  const loadSettings = useCallback(async () => {
    setLoading(true)
    try {
      const res = await getBusinessRules()
      const list = res.data ?? []
      setSettings(list)
      form.setFieldsValue(settingsToValues(list))
    } catch (error) {
      toast.error(errorMessage(error, "加载系统设置失败"))
    } finally {
      setLoading(false)
    }
  }, [form])

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

  const handleSave = async () => {
    let payload: Record<string, BusinessSettingValue>
    try {
      payload = await form.validateFields()
    } catch {
      return
    }

    const suspendDays = Number(payload["lifecycle.expire_suspend_after_days"] ?? 0)
    const deleteDays = Number(payload["lifecycle.expire_delete_after_days"] ?? 0)
    if (deleteDays < suspendDays) {
      toast.error("到期删除天数不能小于到期暂停天数")
      return
    }
    const minRecharge = Number(payload["finance.recharge_min_cents"] ?? 0)
    const maxRecharge = Number(payload["finance.recharge_max_cents"] ?? 0)
    if (maxRecharge < minRecharge) {
      toast.error("最高充值金额不能小于最低充值金额")
      return
    }
    const checkinMin = Number(payload["points.checkin_min_points"] ?? 0)
    const checkinMax = Number(payload["points.checkin_max_points"] ?? 0)
    if (checkinMax < checkinMin) {
      toast.error("每日签到最高积分不能小于最低积分")
      return
    }
    const verificationFreeQuota = Number(payload["verification.free_quota_per_user"] ?? 0)
    const verificationPrice = Number(payload["verification.quota_price_cents"] ?? 0)
    if (verificationFreeQuota < 0 || verificationPrice < 0) {
      toast.error("实名认证免费次数和单价不能小于 0")
      return
    }

    setSaving(true)
    try {
      const res = await updateBusinessRules(payload)
      const list = res.data ?? []
      setSettings(list)
      form.setFieldsValue(settingsToValues(list))
      toast.success("系统设置已保存")
    } catch (error) {
      toast.error(errorMessage(error, "保存系统设置失败"))
    } finally {
      setSaving(false)
    }
  }

  const uploadLogo: UploadProps["beforeUpload"] = async (file) => {
    if (!/image\/(png|jpeg|webp|svg\+xml)/.test(file.type) || file.size > 2 * 1024 * 1024) {
      toast.error("请选择 2MB 以内的 PNG、JPG、WebP 或 SVG 图片")
      return Upload.LIST_IGNORE
    }
    setUploadingLogo(true)
    try {
      await uploadBrandLogo(file)
      toast.success("站点 Logo 已更新")
    } catch (error) {
      toast.error(errorMessage(error, "Logo 上传失败"))
    } finally {
      setUploadingLogo(false)
    }
    return Upload.LIST_IGNORE
  }

  const renderSettingControl = (item: BusinessSetting) => {
    if (item.value_type === "boolean") {
      return <Switch checkedChildren="启用" unCheckedChildren="关闭" />
    }
    if (item.value_type === "text" || item.value_type === "url" || item.value_type === "email") {
      return <Input maxLength={item.max_value ?? undefined} placeholder={`请输入${item.label}`} />
    }
    return (
      <InputNumber
        min={item.min_value ?? undefined}
        max={item.max_value ?? undefined}
        precision={0}
        addonAfter={item.unit}
        style={{ width: "100%" }}
      />
    )
  }

  const settingRules = (item: BusinessSetting) => {
    if (item.value_type === "boolean") return []
    return [
      { required: true, message: `请输入${item.label}` },
      {
        validator: (_: unknown, value: unknown) => {
          if (item.value_type === "integer") {
            const n = Number(value)
            if (!Number.isFinite(n)) return Promise.reject(new Error("请输入有效数字"))
            if (item.min_value !== null && n < item.min_value) return Promise.reject(new Error(`不能小于 ${item.min_value}${item.unit}`))
            if (item.max_value !== null && n > item.max_value) return Promise.reject(new Error(`不能大于 ${item.max_value}${item.unit}`))
          }
          if (typeof value === "string") {
            const text = value.trim()
            if (item.min_value !== null && text.length < item.min_value) return Promise.reject(new Error(`至少 ${item.min_value} 个字符`))
            if (item.value_type === "url" && !/^https?:\/\//.test(text)) return Promise.reject(new Error("请输入 http:// 或 https:// 开头的地址"))
          }
          return Promise.resolve()
        },
      },
    ]
  }

  const siteName = String(values["platform.site_name"] ?? "网站")
  const registrationEnabled = Boolean(values["platform.registration_enabled"] ?? true)
  const rechargeEnabled = Boolean(values["finance.recharge_enabled"] ?? true)
  const rechargeMin = Number(values["finance.recharge_min_cents"] ?? 0)
  const rechargeMax = Number(values["finance.recharge_max_cents"] ?? 0)
  const verificationFreeQuota = Number(values["verification.free_quota_per_user"] ?? 0)
  const verificationPrice = Number(values["verification.quota_price_cents"] ?? 0)
  const verificationPurchaseEnabled = Boolean(values["verification.quota_purchase_enabled"] ?? true)

  return (
    <Space orientation="vertical" size={20} style={{ width: "100%" }}>
      <Row gutter={[16, 16]} align="bottom" justify="space-between">
        <Col>
          <Title level={3} style={{ margin: 0 }}>系统设置</Title>
          <Paragraph type="secondary" style={{ marginTop: 8, marginBottom: 0 }}>
            管理平台信息、注册充值入口、退订规则、资源生命周期、推广结算和积分规则。
          </Paragraph>
        </Col>
        <Col>
          <Space>
            <Button icon={<ReloadOutlined />} loading={loading} onClick={loadSettings}>
              刷新
            </Button>
            <Button type="primary" icon={<SaveOutlined />} loading={saving} onClick={handleSave}>
              保存
            </Button>
          </Space>
        </Col>
      </Row>

      <Row gutter={[16, 16]}>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined"><Statistic title="站点名称" value={siteName} prefix={<SettingOutlined />} /></Card>
        </Col>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined"><Statistic title="新用户注册" value={registrationEnabled ? "开放" : "关闭"} /></Card>
        </Col>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined">
            <Statistic title="余额充值" value={rechargeEnabled ? `￥${(rechargeMin / 100).toFixed(2)} - ￥${(rechargeMax / 100).toFixed(2)}` : "已关闭"} />
          </Card>
        </Col>
        <Col xs={24} sm={12} xl={6}>
          <Card variant="outlined">
            <Statistic
              title="实名认证"
              value={verificationPurchaseEnabled ? `${verificationFreeQuota} 次免费 / ￥${(verificationPrice / 100).toFixed(2)}` : `${verificationFreeQuota} 次免费`}
            />
          </Card>
        </Col>
      </Row>

      <Card variant="outlined" title="站点品牌">
        <Space orientation="vertical" size={8}>
          <Text type="secondary">Logo 推荐使用透明背景 PNG，横版 480 x 120 像素；方形图标建议 256 x 256 像素。支持 PNG、JPG、WebP、SVG，最大 2MB。</Text>
          <Upload accept="image/png,image/jpeg,image/webp,image/svg+xml" showUploadList={false} beforeUpload={uploadLogo}>
            <Button icon={<UploadOutlined />} loading={uploadingLogo}>上传 Logo</Button>
          </Upload>
        </Space>
      </Card>

      <Alert
        type="info"
        showIcon
        title="配置保存后立即生效"
        description="邮件和短信插件已移到“通知插件”页面管理；这里仅保留业务规则配置。"
      />

      <Form form={form} layout="vertical">
        <Space orientation="vertical" size={16} style={{ width: "100%" }}>
          {settings.length === 0 && !loading ? (
            <Card variant="outlined">
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无可配置规则" />
            </Card>
          ) : null}

          {Object.entries(grouped).map(([group, items]) => (
            <Card key={group} title={GROUP_LABEL[group] ?? group} variant="outlined" loading={loading}>
              <Row gutter={[16, 12]}>
                {items.map((item) => (
                  <Col xs={24} md={12} xl={8} key={item.key}>
                    <Form.Item
                      name={item.key}
                      label={item.label}
                      extra={item.description}
                      valuePropName={item.value_type === "boolean" ? "checked" : "value"}
                      rules={settingRules(item)}
                    >
                      {renderSettingControl(item)}
                    </Form.Item>
                  </Col>
                ))}
              </Row>
            </Card>
          ))}

          <Card variant="outlined">
            <Space orientation="vertical" size={8}>
              <Text strong>当前生效范围</Text>
              <Text type="secondary">
                注册、充值、退订、生命周期、推广结算和积分规则保存后立即生效；通知通道请前往“通知插件”页面管理。
              </Text>
            </Space>
          </Card>
        </Space>
      </Form>
    </Space>
  )
}
