import { useCallback, useEffect, useMemo, useState } from "react"
import {
  CheckCircleOutlined,
  ReloadOutlined,
  SettingOutlined,
  SyncOutlined,
} from "@ant-design/icons"
import {
  Alert,
  Button,
  Card,
  Col,
  Flex,
  Row,
  Space,
  Statistic,
  Switch,
  Table,
  Tag,
  Typography,
  type TableColumnsType,
} from "antd"
import { toast } from "../../utils/toast"
import {
  listSpendEventTypes,
  recalculateSpend,
  updateSpendEventType,
  type SpendEventTypeConfig,
} from "../api/membership"

const { Paragraph, Text, Title } = Typography

function fmtDate(value: string | null | undefined) {
  if (!value) return "-"
  return new Date(value).toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    hour12: false,
  })
}

export default function AdminMembership() {
  const [configs, setConfigs] = useState<SpendEventTypeConfig[]>([])
  const [loading, setLoading] = useState(true)
  const [updatingCode, setUpdatingCode] = useState<string | null>(null)
  const [recalculating, setRecalculating] = useState(false)

  const loadConfigs = useCallback(async () => {
    setLoading(true)
    try {
      const res = await listSpendEventTypes()
      setConfigs(res.data ?? [])
    } catch (e: unknown) {
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "加载消费口径失败")
    } finally {
      setLoading(false)
    }
  }, [])

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

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

  const handleToggle = useCallback(async (record: SpendEventTypeConfig, enabled: boolean) => {
    setUpdatingCode(record.code)
    try {
      const res = await updateSpendEventType(record.code, enabled)
      const next = res.data?.config
      if (next) {
        setConfigs((items) => items.map((item) => item.code === next.code ? next : item))
      }
      toast.success(`已${enabled ? "计入" : "排除"}「${record.label}」`)
    } catch (e: unknown) {
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "更新消费口径失败")
    } finally {
      setUpdatingCode(null)
    }
  }, [])

  const handleRecalculate = useCallback(async () => {
    setRecalculating(true)
    try {
      const res = await recalculateSpend()
      toast.success(`已重算 ${res.data?.recalculated_users ?? 0} 个用户`)
      await loadConfigs()
    } catch (e: unknown) {
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "重算累计消费失败")
    } finally {
      setRecalculating(false)
    }
  }, [loadConfigs])

  const columns = useMemo<TableColumnsType<SpendEventTypeConfig>>(() => [
    {
      title: "消费类型",
      dataIndex: "label",
      render: (value: string, record) => (
        <Space orientation="vertical" size={0}>
          <Text strong>{value}</Text>
          <Text type="secondary">{record.code}</Text>
        </Space>
      ),
    },
    {
      title: "说明",
      dataIndex: "description",
      render: (value: string | null) => value || "-",
    },
    {
      title: "状态",
      dataIndex: "enabled",
      width: 120,
      render: (value: boolean) => (
        value ? <Tag color="success">计入累计</Tag> : <Tag>不计入</Tag>
      ),
    },
    {
      title: "更新时间",
      dataIndex: "updated_at",
      width: 180,
      render: fmtDate,
    },
    {
      title: "操作",
      dataIndex: "enabled",
      width: 130,
      render: (value: boolean, record) => (
        <Switch
          checked={value}
          checkedChildren="计入"
          unCheckedChildren="排除"
          loading={updatingCode === record.code}
          onChange={(checked) => void handleToggle(record, checked)}
        />
      ),
    },
  ], [handleToggle, updatingCode])

  return (
    <Flex vertical gap="large">
      <Space orientation="vertical" size={4}>
        <Title level={3}>会员与伙伴</Title>
        <Paragraph type="secondary">
          配置哪些消费事件计入用户累计有效消费，累计消费会影响会员成长和后续伙伴档位赋级。
        </Paragraph>
      </Space>

      <Row gutter={[16, 16]}>
        <Col xs={24} md={8}>
          <Card>
            <Statistic title="消费类型" value={stats.total} suffix="项" prefix={<SettingOutlined />} />
          </Card>
        </Col>
        <Col xs={24} md={8}>
          <Card>
            <Statistic title="已计入" value={stats.enabled} suffix="项" prefix={<CheckCircleOutlined />} />
          </Card>
        </Col>
        <Col xs={24} md={8}>
          <Card>
            <Statistic title="已排除" value={stats.disabled} suffix="项" />
          </Card>
        </Col>
      </Row>

      <Alert
        type="info"
        showIcon
        title="消费口径说明"
        description="关闭某个类型不会删除历史流水，只会在重算累计消费时排除该类型；重新开启后，历史流水会再次计入。"
      />

      <Card
        title="有效消费类型"
        extra={
          <Space>
            <Button icon={<ReloadOutlined />} onClick={() => void loadConfigs()}>
              刷新
            </Button>
            <Button
              type="primary"
              icon={<SyncOutlined />}
              loading={recalculating}
              onClick={() => void handleRecalculate()}
            >
              重算累计消费
            </Button>
          </Space>
        }
      >
        <Table<SpendEventTypeConfig>
          rowKey="code"
          loading={loading}
          columns={columns}
          dataSource={configs}
          pagination={false}
        />
      </Card>
    </Flex>
  )
}
