import VisibilityOutlined from "@mui/icons-material/VisibilityOutlined";
import ReplayOutlined from "@mui/icons-material/ReplayOutlined";
import { RedPacketConfigDrawer } from "@/features/red-packets/components/RedPacketConfigDrawer.jsx";
import { RedPacketConfigSummary } from "@/features/red-packets/components/RedPacketConfigSummary.jsx";
import { RedPacketDetailDrawer } from "@/features/red-packets/components/RedPacketDetailDrawer.jsx";
import { useRedPacketPage } from "@/features/red-packets/hooks/useRedPacketPage.js";
import styles from "@/features/red-packets/red-packets.module.css";
import {
    AdminActionIconButton,
    AdminListBody,
    AdminListPage,
    AdminRowActions,
} from "@/shared/ui/AdminListLayout.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import { DataTable } from "@/shared/ui/DataTable.jsx";
import { createOptionsColumnFilter, createTextColumnFilter } from "@/shared/ui/tableFilters.js";
import { formatMillis } from "@/shared/utils/time.js";

const packetTypeOptions = [
    ["", "全部类型"],
    ["IMMEDIATE", "即时红包"],
    ["DELAYED", "延时红包"],
];

const statusOptions = [
    ["", "全部状态"],
    ["waiting_open", "待开启"],
    ["active", "进行中"],
    ["finished", "已抢完"],
    ["refunded", "已退款"],
];

export function RedPacketPage() {
    const page = useRedPacketPage();
    const total = page.packets.total || 0;
    const columns = [
        {
            key: "packet",
            label: "红包",
            width: "minmax(280px, 1.2fr)",
            render: (packet) => (
                <div className={styles.stack}>
                    <span className={styles.name}>{packet.packetId}</span>
                    <span className={styles.meta}>{packet.commandId || "-"}</span>
                </div>
            ),
        },
        {
            key: "room",
            label: "房间/区域",
            width: "minmax(180px, 0.75fr)",
            filter: createTextColumnFilter({
                placeholder: "搜索房间 ID",
                value: page.roomId,
                onChange: page.setRoomId,
            }),
            render: (packet) => (
                <div className={styles.stack}>
                    <span>{packet.roomId || "-"}</span>
                    <span className={styles.meta}>区域 {packet.regionId || "-"}</span>
                </div>
            ),
        },
        {
            key: "sender",
            label: "发送人",
            width: "minmax(130px, 0.55fr)",
            filter: createTextColumnFilter({
                placeholder: "搜索发送人 ID",
                value: page.senderUserId,
                onChange: page.setSenderUserId,
            }),
            render: (packet) => packet.senderUserId || "-",
        },
        {
            key: "type",
            label: "类型",
            width: "minmax(110px, 0.5fr)",
            filter: createOptionsColumnFilter({
                options: packetTypeOptions,
                placeholder: "搜索类型",
                value: page.packetType,
                onChange: page.setPacketType,
            }),
            render: (packet) => packetTypeLabel(packet.packetType),
        },
        {
            key: "amount",
            label: "金额/个数",
            width: "minmax(150px, 0.65fr)",
            render: (packet) => (
                <div className={styles.stack}>
                    <span>{formatNumber(packet.totalAmount)} 金币</span>
                    <span className={styles.meta}>
                        剩余 {formatNumber(packet.remainingAmount)} / {packet.remainingCount} 个
                    </span>
                </div>
            ),
        },
        {
            key: "claimed",
            label: "已领",
            width: "minmax(145px, 0.6fr)",
            render: (packet) => (
                <div className={styles.stack}>
                    <span>{formatNumber(packet.totalAmount - packet.remainingAmount)} 金币</span>
                    <span className={styles.meta}>{packet.packetCount - packet.remainingCount} 个</span>
                </div>
            ),
        },
        {
            key: "status",
            label: "状态",
            width: "minmax(110px, 0.5fr)",
            filter: createOptionsColumnFilter({
                options: statusOptions,
                placeholder: "搜索状态",
                value: page.status,
                onChange: page.setStatus,
            }),
            render: (packet) => packetStatusLabel(packet.status),
        },
        {
            key: "openAt",
            label: "开启时间",
            width: "minmax(180px, 0.75fr)",
            render: (packet) => formatMillis(packet.openAtMs),
        },
        {
            key: "expiresAt",
            label: "过期时间",
            width: "minmax(180px, 0.75fr)",
            render: (packet) => formatMillis(packet.expiresAtMs),
        },
        {
            key: "refund",
            label: "退款",
            width: "minmax(120px, 0.55fr)",
            render: (packet) =>
                packet.refundStatus
                    ? `${packetStatusLabel(packet.refundStatus)} ${formatNumber(packet.refundAmount)}`
                    : "-",
        },
        {
            key: "actions",
            label: "操作",
            width: "128px",
            render: (packet) => (
                <AdminRowActions>
                    {page.abilities.canUpdate && canRetryRefund(packet) ? (
                        <AdminActionIconButton label="重试退款" onClick={() => page.retryRefund(packet.packetId)}>
                            <ReplayOutlined fontSize="small" />
                        </AdminActionIconButton>
                    ) : null}
                    <AdminActionIconButton label="查看详情" onClick={() => page.openPacketDetail(packet.packetId)}>
                        <VisibilityOutlined fontSize="small" />
                    </AdminActionIconButton>
                </AdminRowActions>
            ),
        },
    ];

    return (
        <AdminListPage>
            <RedPacketConfigSummary
                canUpdate={page.abilities.canUpdate}
                config={page.config}
                configLoading={page.configLoading}
                onEdit={page.openConfigDrawer}
                onRefresh={page.reloadConfig}
            />
            <DataState error={page.packetsError} loading={page.packetsLoading} onRetry={page.reloadPackets}>
                <AdminListBody>
                    <DataTable
                        columns={columns}
                        items={page.packets.items || []}
                        minWidth="1500px"
                        pagination={
                            total > 0
                                ? {
                                      page: page.page,
                                      pageSize: page.packets.pageSize || 50,
                                      total,
                                      onPageChange: page.setPage,
                                  }
                                : undefined
                        }
                        rowKey={(packet) => packet.packetId}
                    />
                </AdminListBody>
            </DataState>
            <RedPacketConfigDrawer
                abilities={page.abilities}
                configLoading={page.configLoading}
                configSaving={page.configSaving}
                form={page.form}
                open={page.configDrawerOpen}
                setForm={page.setForm}
                onClose={page.closeConfigDrawer}
                onSubmit={page.submitConfig}
            />
            <RedPacketDetailDrawer
                loading={page.detailLoading}
                open={page.detailOpen}
                packet={page.selectedPacket}
                onClose={page.closePacketDetail}
            />
        </AdminListPage>
    );
}

function packetTypeLabel(type) {
    const normalized = String(type || "").toLowerCase();
    return normalized === "delayed" ? "延时红包" : "即时红包";
}

function packetStatusLabel(status) {
    const normalized = String(status || "").toLowerCase();
    return statusOptions.find(([value]) => value === normalized)?.[1] || status || "-";
}

function formatNumber(value) {
    return new Intl.NumberFormat("zh-CN").format(Number(value || 0));
}

function canRetryRefund(packet) {
    const status = String(packet.status || "").toLowerCase();
    return status === "active" || status === "waiting_open";
}
