import KeyboardArrowDownOutlined from "@mui/icons-material/KeyboardArrowDownOutlined";
import KeyboardArrowRightOutlined from "@mui/icons-material/KeyboardArrowRightOutlined";
import { useState } from "react";
import { InviteActivityRewardConfigDrawer } from "@/features/invite-activity-reward/components/InviteActivityRewardConfigDrawer.jsx";
import { InviteActivityRewardConfigSummary } from "@/features/invite-activity-reward/components/InviteActivityRewardConfigSummary.jsx";
import { useInviteActivityRewardPage } from "@/features/invite-activity-reward/hooks/useInviteActivityRewardPage.js";
import styles from "@/features/invite-activity-reward/invite-activity-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 { createTextColumnFilter, createUserIdentityColumnFilter } from "@/shared/ui/tableFilters.js";
import { formatMillis } from "@/shared/utils/time.js";

export function InviteActivityRewardPage() {
    const page = useInviteActivityRewardPage();
    const total = page.summaries.total || 0;
    const [expandedKey, setExpandedKey] = useState("");
    const toggleSummary = (summary) => {
        setExpandedKey((current) => (current === summary.key ? "" : summary.key));
    };
    const columns = [
        {
            key: "user",
            label: "用户信息",
            width: "minmax(280px, 1.1fr)",
            render: (summary) => <SummaryUser expanded={expandedKey === summary.key} summary={summary} />,
            filter: createUserIdentityColumnFilter({
                value: page.userFilter,
                onChange: page.changeUserFilter,
            }),
        },
        {
            key: "cycle",
            label: "周期",
            width: "minmax(140px, 0.55fr)",
            render: (summary) => summary.cycleKey || "-",
            filter: createTextColumnFilter({
                placeholder: "周期，如 2026-06",
                value: page.cycleKey,
                onChange: page.changeCycleKey,
            }),
        },
        {
            key: "inviteCount",
            label: "邀请人数",
            width: "minmax(130px, 0.5fr)",
            render: (summary) => `${formatNumber(summary.inviteCount)} 人`,
        },
        {
            key: "validInviteCount",
            label: "有效邀请人数",
            width: "minmax(150px, 0.55fr)",
            render: (summary) => `${formatNumber(summary.validInviteCount)} 人`,
        },
        {
            key: "totalRechargeCoinAmount",
            label: "邀请人数总充值",
            width: "minmax(170px, 0.65fr)",
            render: (summary) => formatNumber(summary.totalRechargeCoinAmount),
        },
        {
            key: "totalRewardCoinAmount",
            label: "总奖励金币",
            width: "minmax(150px, 0.55fr)",
            render: (summary) => formatNumber(summary.totalRewardCoinAmount),
        },
    ];

    return (
        <AdminListPage>
            <InviteActivityRewardConfigSummary
                canUpdate={page.abilities.canUpdate}
                config={page.config}
                configLoading={page.configLoading}
                onEdit={page.openConfigDrawer}
                onRefresh={page.reloadConfig}
            />
            <DataState error={page.summariesError} loading={page.summariesLoading} onRetry={page.reloadSummaries}>
                <AdminListBody>
                    <DataTable
                        columns={columns}
                        items={page.summaries.items || []}
                        minWidth="1180px"
                        pagination={
                            total > 0
                                ? {
                                      page: page.page,
                                      pageSize: page.summaries.pageSize || 50,
                                      total,
                                      onPageChange: page.setPage,
                                  }
                                : undefined
                        }
                        renderRowDetail={(summary) =>
                            expandedKey === summary.key ? <InviteeDetail key={`${summary.key}:detail`} summary={summary} /> : null
                        }
                        rowKey={(summary) => summary.key}
                        getRowProps={(summary) => ({
                            "aria-expanded": expandedKey === summary.key,
                            className: expandedKey === summary.key ? styles.rowExpanded : "",
                            role: "button",
                            tabIndex: 0,
                            onClick: () => toggleSummary(summary),
                            onKeyDown: (event) => {
                                if (event.key !== "Enter" && event.key !== " ") {
                                    return;
                                }
                                event.preventDefault();
                                toggleSummary(summary);
                            },
                        })}
                    />
                </AdminListBody>
            </DataState>
            <InviteActivityRewardConfigDrawer
                abilities={page.abilities}
                configLoading={page.configLoading}
                configSaving={page.configSaving}
                form={page.form}
                open={page.configDrawerOpen}
                setForm={page.setForm}
                onClose={page.closeConfigDrawer}
                onSubmit={page.submitConfig}
            />
        </AdminListPage>
    );
}

function SummaryUser({ expanded, summary }) {
    const user = summary.user || {};
    return (
        <div className={styles.expandUser}>
            <span className={styles.expandIcon} aria-hidden="true">
                {expanded ? <KeyboardArrowDownOutlined fontSize="small" /> : <KeyboardArrowRightOutlined fontSize="small" />}
            </span>
            <AdminUserIdentity openInAppUserDetail user={{ ...user, userId: user.userId || summary.userId }} />
        </div>
    );
}

function InviteeDetail({ summary }) {
    const invitees = summary.invitees || [];
    return (
        <div className={["admin-row", styles.detailRow].join(" ")}>
            <div className={styles.detailCell}>
                <div className={styles.inviteeTable}>
                    <div className={styles.inviteeHeader}>
                        <span>被邀请用户</span>
                        <span>充值</span>
                        <span>邀请时间</span>
                    </div>
                    {invitees.length ? (
                        invitees.map((invitee) => (
                            <div className={styles.inviteeRow} key={`${summary.key}:${invitee.userId}`}>
                                <AdminUserIdentity
                                    openInAppUserDetail
                                    user={{ ...(invitee.user || {}), userId: invitee.user?.userId || invitee.userId }}
                                />
                                <span>{formatNumber(invitee.rechargeCoinAmount)}</span>
                                <span>{invitee.invitedAtMs ? formatMillis(invitee.invitedAtMs) : "-"}</span>
                            </div>
                        ))
                    ) : (
                        <div className={styles.inviteeEmpty}>当前没有被邀请用户明细</div>
                    )}
                </div>
            </div>
        </div>
    );
}

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