import { useCallback, useEffect, useMemo, useState } from "react"
import {
  AccountBookOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  DollarOutlined,
  HistoryOutlined,
  ReloadOutlined,
  SearchOutlined,
  WalletOutlined,
} from "@ant-design/icons"
import {
  Button,
  Card,
  Col,
  Empty,
  Input,
  InputNumber,
  Row,
  Select,
  Space,
  Statistic,
  Table,
  Tabs,
  Tag,
  Typography,
  theme,
  type TableColumnsType,
} from "antd"
import { PageSkeleton, type SkeletonSpec } from "../../utils/skeleton"
import { toast } from "../../utils/toast"
import {
  getAdminRechargeStats,
  listAdminBalanceLogs,
  listAdminRechargeOrders,
  type AdminBalanceLog,
  type AdminRechargeOrder,
  type AdminRechargeStats,
} from "../api/finance"

const { Title, Paragraph, Text } = Typography

const PAGE_SKELETON: SkeletonSpec[] = [
  { type: "header", title: 160, subtitle: 260 },
  { type: "grid", cols: 4, count: 4, gap: 12, item: { type: "card", h: 90 } },
  { type: "table", rows: 8, cols: 6 },
]

const RECHARGE_STATUS_META: Record<AdminRechargeOrder["status"], { label: string; color: string }> = {
  pending: { label: "待支付", color: "warning" },
  paid: { label: "已到账", color: "success" },
  expired: { label: "已过期", color: "default" },
  closed: { label: "已关闭", color: "default" },
  refunded: { label: "已退款", color: "purple" },
}

const CHANNEL_LABEL: Record<string, string> = {
  alipay: "支付宝",
  wxpay: "微信支付",
  admin: "管理员",
}

const BALANCE_TYPE_LABEL: Record<string, string> = {
  recharge: "充值",
  order_pay: "订单支付",
  order_refund: "订单退款",
  admin_adjust: "后台调账",
}

function yuanFromCents(cents: number) {
  return `¥${(cents / 100).toFixed(2)}`
}

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 AdminFinance() {
  const { token } = theme.useToken()
  const [initialLoading, setInitialLoading] = useState(true)
  const [statsLoading, setStatsLoading] = useState(false)
  const [ordersLoading, setOrdersLoading] = useState(false)
  const [logsLoading, setLogsLoading] = useState(false)
  const [stats, setStats] = useState<AdminRechargeStats | null>(null)
  const [orders, setOrders] = useState<AdminRechargeOrder[]>([])
  const [logs, setLogs] = useState<AdminBalanceLog[]>([])
  const [activeTab, setActiveTab] = useState("recharge")

  const [keyword, setKeyword] = useState("")
  const [status, setStatus] = useState("")
  const [channel, setChannel] = useState("")
  const [logUserId, setLogUserId] = useState<number | null>(null)
  const [logType, setLogType] = useState("")

  const loadStats = useCallback(async () => {
    setStatsLoading(true)
    try {
      const res = await getAdminRechargeStats()
      setStats(res.data ?? null)
    } catch (e: unknown) {
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "加载财务统计失败")
    } finally {
      setStatsLoading(false)
    }
  }, [])

  const loadOrders = useCallback(async () => {
    setOrdersLoading(true)
    try {
      const res = await listAdminRechargeOrders({
        keyword: keyword.trim() || undefined,
        status: status || undefined,
        channel: channel || undefined,
        limit: 100,
      })
      setOrders(res.data ?? [])
    } catch (e: unknown) {
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "加载充值订单失败")
    } finally {
      setOrdersLoading(false)
    }
  }, [channel, keyword, status])

  const loadLogs = useCallback(async () => {
    setLogsLoading(true)
    try {
      const res = await listAdminBalanceLogs({
        user_id: logUserId ?? undefined,
        change_type: logType || undefined,
        limit: 100,
      })
      setLogs(res.data ?? [])
    } catch (e: unknown) {
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "加载余额流水失败")
    } finally {
      setLogsLoading(false)
    }
  }, [logType, logUserId])

  const reloadAll = useCallback(async () => {
    if (activeTab === "balance") {
      await Promise.all([loadStats(), loadLogs()])
      return
    }
    await Promise.all([loadStats(), loadOrders()])
  }, [activeTab, loadLogs, loadOrders, loadStats])

  useEffect(() => {
    void (async () => {
      setInitialLoading(true)
      await Promise.all([loadStats(), loadOrders()])
      setInitialLoading(false)
    })()
  }, [])

  const handleTabChange = useCallback((key: string) => {
    setActiveTab(key)
    if (key === "balance" && logs.length === 0) {
      void loadLogs()
    }
    if (key === "recharge" && orders.length === 0) {
      void loadOrders()
    }
  }, [loadLogs, loadOrders, logs.length, orders.length])

  const orderColumns = useMemo<TableColumnsType<AdminRechargeOrder>>(() => [
    {
      title: "订单号",
      dataIndex: "out_trade_no",
      width: 240,
      render: (value: string, record) => (
        <Space orientation="vertical" size={0}>
          <Text code style={{ fontSize: 12 }}>{value}</Text>
          {record.trade_no && <Text type="secondary" style={{ fontSize: 12 }}>{record.trade_no}</Text>}
        </Space>
      ),
    },
    {
      title: "用户",
      dataIndex: "user_id",
      width: 100,
      render: (value: number) => <Text type="secondary">#{value}</Text>,
    },
    {
      title: "渠道",
      dataIndex: "channel",
      width: 120,
      render: (value: string) => <Tag>{CHANNEL_LABEL[value] ?? value}</Tag>,
    },
    {
      title: "金额",
      dataIndex: "amount_cents",
      width: 140,
      align: "right",
      render: (value: number, record) => (
        <Space orientation="vertical" size={0} align="end">
          <Text strong>{yuanFromCents(value)}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>¥{Number(record.amount).toFixed(2)}</Text>
        </Space>
      ),
    },
    {
      title: "状态",
      dataIndex: "status",
      width: 120,
      render: (value: AdminRechargeOrder["status"]) => {
        const meta = RECHARGE_STATUS_META[value]
        return <Tag color={meta.color}>{meta.label}</Tag>
      },
    },
    {
      title: "创建时间",
      dataIndex: "created_at",
      width: 180,
      render: fmtDate,
    },
  ], [])

  const logColumns = useMemo<TableColumnsType<AdminBalanceLog>>(() => [
    {
      title: "流水 ID",
      dataIndex: "id",
      width: 110,
      render: (value: number) => <Text type="secondary">#{value}</Text>,
    },
    {
      title: "用户",
      dataIndex: "user_id",
      width: 100,
      render: (value: number) => <Text type="secondary">#{value}</Text>,
    },
    {
      title: "类型",
      dataIndex: "change_type",
      width: 140,
      render: (value: string) => <Tag>{BALANCE_TYPE_LABEL[value] ?? value}</Tag>,
    },
    {
      title: "变动",
      dataIndex: "delta",
      width: 140,
      align: "right",
      render: (value: number) => (
        <Text strong type={value >= 0 ? "success" : "danger"}>
          {value >= 0 ? "+" : "-"}{yuanFromCents(Math.abs(value))}
        </Text>
      ),
    },
    {
      title: "变动后余额",
      dataIndex: "balance_after",
      width: 150,
      align: "right",
      render: (value: number) => <Text>{yuanFromCents(value)}</Text>,
    },
    {
      title: "关联单号",
      dataIndex: "ref_no",
      ellipsis: true,
      render: (value: string | null) => value ? <Text code style={{ fontSize: 12 }}>{value}</Text> : "-",
    },
    {
      title: "备注",
      dataIndex: "remark",
      ellipsis: true,
      render: (value: string | null) => value || "-",
    },
    {
      title: "时间",
      dataIndex: "created_at",
      width: 180,
      render: fmtDate,
    },
  ], [])

  return (
    <PageSkeleton loading={initialLoading} spec={PAGE_SKELETON} gap={24}>
      <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>
            <Button
              icon={<ReloadOutlined />}
              loading={statsLoading || ordersLoading || logsLoading}
              onClick={reloadAll}
            >
              刷新
            </Button>
          </Col>
        </Row>

        <Row gutter={[16, 16]}>
          <Col xs={24} sm={12} xl={6}>
            <Card variant="outlined" loading={statsLoading}>
              <Statistic title="累计到账" value={stats ? yuanFromCents(stats.total_paid_cents) : "¥0.00"} prefix={<WalletOutlined />} />
            </Card>
          </Col>
          <Col xs={24} sm={12} xl={6}>
            <Card variant="outlined" loading={statsLoading}>
              <Statistic title="到账笔数" value={stats?.total_paid_count ?? 0} suffix="笔" prefix={<CheckCircleOutlined />} styles={{ content: { color: token.colorSuccess } }} />
            </Card>
          </Col>
          <Col xs={24} sm={12} xl={6}>
            <Card variant="outlined" loading={statsLoading}>
              <Statistic title="今日到账" value={stats ? yuanFromCents(stats.today_paid_cents) : "¥0.00"} prefix={<DollarOutlined />} styles={{ content: { color: token.colorPrimary } }} />
            </Card>
          </Col>
          <Col xs={24} sm={12} xl={6}>
            <Card variant="outlined" loading={statsLoading}>
              <Statistic title="待支付订单" value={stats?.pending_count ?? 0} suffix="笔" prefix={<ClockCircleOutlined />} styles={{ content: { color: token.colorWarning } }} />
            </Card>
          </Col>
        </Row>

        <Card variant="outlined">
          <Tabs
            activeKey={activeTab}
            onChange={handleTabChange}
            items={[
              {
                key: "recharge",
                label: <Space><AccountBookOutlined />充值订单</Space>,
                children: (
                  <Space orientation="vertical" size={16} style={{ width: "100%" }}>
                    <Row gutter={[12, 12]} justify="space-between">
                      <Col flex="auto">
                        <Input
                          allowClear
                          prefix={<SearchOutlined />}
                          placeholder="搜索订单号 / 交易号"
                          value={keyword}
                          onChange={(event) => setKeyword(event.target.value)}
                          onPressEnter={loadOrders}
                        />
                      </Col>
                      <Col>
                        <Select
                          value={status}
                          onChange={setStatus}
                          style={{ width: 140 }}
                          options={[
                            { value: "", label: "全部状态" },
                            { value: "pending", label: "待支付" },
                            { value: "paid", label: "已到账" },
                            { value: "expired", label: "已过期" },
                            { value: "closed", label: "已关闭" },
                            { value: "refunded", label: "已退款" },
                          ]}
                        />
                      </Col>
                      <Col>
                        <Select
                          value={channel}
                          onChange={setChannel}
                          style={{ width: 140 }}
                          options={[
                            { value: "", label: "全部渠道" },
                            { value: "alipay", label: "支付宝" },
                            { value: "wxpay", label: "微信支付" },
                            { value: "admin", label: "管理员" },
                          ]}
                        />
                      </Col>
                      <Col>
                        <Button type="primary" icon={<SearchOutlined />} loading={ordersLoading} onClick={loadOrders}>
                          查询
                        </Button>
                      </Col>
                    </Row>
                    <Table
                      rowKey="id"
                      loading={ordersLoading}
                      columns={orderColumns}
                      dataSource={orders}
                      pagination={{ pageSize: 12, showSizeChanger: false }}
                      scroll={{ x: 980 }}
                      locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无充值订单" /> }}
                    />
                  </Space>
                ),
              },
              {
                key: "balance",
                label: <Space><HistoryOutlined />余额流水</Space>,
                children: (
                  <Space orientation="vertical" size={16} style={{ width: "100%" }}>
                    <Row gutter={[12, 12]} justify="space-between">
                      <Col>
                        <InputNumber
                          min={1}
                          precision={0}
                          placeholder="用户 ID"
                          value={logUserId}
                          onChange={(value) => setLogUserId(typeof value === "number" ? value : null)}
                          style={{ width: 160 }}
                        />
                      </Col>
                      <Col>
                        <Select
                          value={logType}
                          onChange={setLogType}
                          style={{ width: 160 }}
                          options={[
                            { value: "", label: "全部类型" },
                            { value: "recharge", label: "充值" },
                            { value: "order_pay", label: "订单支付" },
                            { value: "order_refund", label: "订单退款" },
                            { value: "admin_adjust", label: "后台调账" },
                          ]}
                        />
                      </Col>
                      <Col flex="auto" />
                      <Col>
                        <Button type="primary" icon={<SearchOutlined />} loading={logsLoading} onClick={loadLogs}>
                          查询
                        </Button>
                      </Col>
                    </Row>
                    <Table
                      rowKey="id"
                      loading={logsLoading}
                      columns={logColumns}
                      dataSource={logs}
                      pagination={{ pageSize: 12, showSizeChanger: false }}
                      scroll={{ x: 1160 }}
                      locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无余额流水" /> }}
                    />
                  </Space>
                ),
              },
            ]}
          />
        </Card>
      </Space>
    </PageSkeleton>
  )
}
