import { FirstRechargeRewardConfigDrawer } from "@/features/first-recharge-reward/components/FirstRechargeRewardConfigDrawer.jsx";
import { FirstRechargeRewardConfigSummary } from "@/features/first-recharge-reward/components/FirstRechargeRewardConfigSummary.jsx";
import { useFirstRechargeRewardPage } from "@/features/first-recharge-reward/hooks/useFirstRechargeRewardPage.js";
import styles from "@/features/first-recharge-reward/first-recharge-reward.module.css";
import { AdminListBody, AdminListPage } from "@/shared/ui/AdminListLayout.jsx";
import { AdminUserIdentity } from "@/shared/ui/AdminUserIdentity.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import { DataTable } from "@/shared/ui/DataTable.jsx";
import { createOptionsColumnFilter, createUserIdentityColumnFilter } from "@/shared/ui/tableFilters.js";
import { formatMillis } from "@/shared/utils/time.js";

const claimStatusOptions = [
    ["pending", "发放中"],
    ["granted", "已发放"],
    ["failed", "发放失败"],
];

const columnsBase = [
    {
        key: "user",
        label: "用户信息",
        width: "minmax(260px, 1.1fr)",
        render: (claim) => <ClaimUser claim={claim} />,
    },
    {
        key: "tier",
        label: "商品档位",
        width: "minmax(260px, 1fr)",
        render: (claim) => (
            <div className={styles.stack}>
                <span>{claim.googleProductId || claim.tierCode || "-"}</span>
                <span className={styles.meta}>
                    {formatUsdMinor(claim.tierUsdMinorAmount || claim.rechargeUsdMinor)}
                </span>
            </div>
        ),
    },
    {
        key: "recharge",
        label: "充值",
        width: "minmax(180px, 0.8fr)",
        render: (claim) => (
            <div className={styles.stack}>
                <span>{formatNumber(claim.rechargeCoinAmount)} 金币</span>
                <span className={styles.meta}>资源组 #{claim.resourceGroupId || "-"}</span>
            </div>
        ),
    },
    {
        key: "status",
        label: "状态",
        width: "minmax(120px, 0.55fr)",
        render: (claim) => claimStatusLabel(claim.status),
    },
    {
        key: "rechargedAt",
        label: "充值时间",
        width: "minmax(180px, 0.85fr)",
        render: (claim) => formatMillis(claim.rechargedAtMs || claim.createdAtMs),
    },
    {
        key: "claimId",
        label: "记录",
        width: "minmax(260px, 1fr)",
        render: (claim) => (
            <div className={styles.stack}>
                <span>{claim.claimId}</span>
                <span className={styles.meta}>{claim.transactionId || "-"}</span>
            </div>
        ),
    },
    {
        key: "failure",
        label: "失败原因",
        width: "minmax(180px, 0.85fr)",
        render: (claim) => claim.failureReason || "-",
    },
];

export function FirstRechargeRewardPage() {
    const page = useFirstRechargeRewardPage();
    const total = page.claims.total || 0;
    const columns = columnsBase.map((column) => {
        if (column.key === "user") {
            return {
                ...column,
                filter: createUserIdentityColumnFilter({
                    value: page.userFilter,
                    onChange: page.changeUserFilter,
                }),
            };
        }
        if (column.key === "status") {
            return {
                ...column,
                filter: createOptionsColumnFilter({
                    options: [["", "全部状态"], ...claimStatusOptions],
                    placeholder: "搜索状态",
                    value: page.status,
                    onChange: page.changeStatus,
                }),
            };
        }
        return column;
    });

    return (
        <AdminListPage>
            <FirstRechargeRewardConfigSummary
                canUpdate={page.abilities.canUpdate}
                config={page.config}
                configLoading={page.configLoading}
                resourceGroups={page.resourceGroups}
                onEdit={page.openConfigDrawer}
                onRefresh={page.reloadConfig}
            />
            <DataState error={page.claimsError} loading={page.claimsLoading} onRetry={page.reloadClaims}>
                <AdminListBody>
                    <DataTable
                        columns={columns}
                        items={page.claims.items || []}
                        minWidth="1380px"
                        pagination={
                            total > 0
                                ? {
                                      page: page.page,
                                      pageSize: page.claims.pageSize || 50,
                                      total,
                                      onPageChange: page.setPage,
                                  }
                                : undefined
                        }
                        rowKey={(claim) => claim.claimId}
                    />
                </AdminListBody>
            </DataState>
            <FirstRechargeRewardConfigDrawer
                abilities={page.abilities}
                configLoading={page.configLoading}
                configSaving={page.configSaving}
                form={page.form}
                open={page.configDrawerOpen}
                resourceGroups={page.resourceGroups}
                setForm={page.setForm}
                onClose={page.closeConfigDrawer}
                onSubmit={page.submitConfig}
            />
        </AdminListPage>
    );
}

function ClaimUser({ claim }) {
    const user = claim.user || {};
    return <AdminUserIdentity openInAppUserDetail user={{ ...user, userId: user.userId || claim.userId }} />;
}

function claimStatusLabel(status) {
    return claimStatusOptions.find(([value]) => value === status)?.[1] || status || "-";
}

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

function formatUsdMinor(value) {
    const amount = Number(value || 0);
    if (!Number.isFinite(amount) || amount <= 0) {
        return "$-";
    }
    return `$${(amount / 100).toFixed(2)}`;
}
