import { useSearchParams } from "react-router-dom";
import { DataState } from "@/shared/ui/DataState.jsx";
import { DataTable } from "@/shared/ui/DataTable.jsx";
import { AdminListBody, AdminListPage } from "@/shared/ui/AdminListLayout.jsx";
import { RoomRocketConfigEditor } from "@/features/room-rocket/components/RoomRocketConfigEditor.jsx";
import { RoomRocketConfigSummary } from "@/features/room-rocket/components/RoomRocketConfigSummary.jsx";
import { useRoomRocketPage } from "@/features/room-rocket/hooks/useRoomRocketPage.js";
import styles from "@/features/room-rocket/room-rocket.module.css";

const columns = [
    {
        key: "level",
        label: "等级",
        width: "minmax(160px, 0.7fr)",
        render: (level) => (
            <div className={styles.stack}>
                <span className={styles.name}>L{level.level}</span>
                <span className={styles.meta}>阈值 {formatNumber(level.fuelThreshold)}</span>
            </div>
        ),
    },
    {
        key: "materials",
        label: "物料",
        width: "minmax(280px, 1.3fr)",
        render: (level) => <MaterialState level={level} />,
    },
    {
        key: "inRoomRewards",
        label: "在房奖励",
        width: "minmax(220px, 1fr)",
        render: (level, _index, context) => (
            <RewardSummary showQuantity groups={context.resourceGroups} rewards={level.inRoomRewards} />
        ),
    },
    {
        key: "top1Rewards",
        label: "贡献第一",
        width: "minmax(220px, 1fr)",
        render: (level, _index, context) => (
            <RewardSummary groups={context.resourceGroups} rewards={level.top1Rewards} />
        ),
    },
    {
        key: "igniterRewards",
        label: "点火人",
        width: "minmax(220px, 1fr)",
        render: (level, _index, context) => (
            <RewardSummary groups={context.resourceGroups} rewards={level.igniterRewards} />
        ),
    },
];

export function RoomRocketPage() {
    const page = useRoomRocketPage();
    const [searchParams, setSearchParams] = useSearchParams();
    const editing = searchParams.get("mode") === "edit";

    const enterEdit = () => {
        page.resetForm();
        setSearchParams({ mode: "edit" });
    };

    const exitEdit = () => {
        page.resetForm();
        setSearchParams({});
    };

    if (editing) {
        return (
            <AdminListPage>
                <DataState
                    error={page.configError}
                    loading={page.configLoading && !page.config}
                    onRetry={page.reloadConfig}
                >
                    <RoomRocketConfigEditor
                        abilities={page.abilities}
                        configLoading={page.configLoading}
                        configSaving={page.configSaving}
                        form={page.form}
                        resourceGroups={page.resourceGroups}
                        setForm={page.setForm}
                        onCancel={exitEdit}
                        onSubmit={(event) => page.submitConfig(event, exitEdit)}
                    />
                </DataState>
            </AdminListPage>
        );
    }

    return (
        <AdminListPage>
            <RoomRocketConfigSummary
                canUpdate={page.abilities.canUpdate}
                config={page.config}
                configLoading={page.configLoading}
                onEdit={enterEdit}
                onRefresh={page.reloadConfig}
            />
            <DataState
                error={page.configError}
                loading={page.configLoading && !page.config}
                onRetry={page.reloadConfig}
            >
                <AdminListBody>
                    <DataTable
                        columns={columns}
                        context={{ resourceGroups: page.resourceGroups }}
                        items={page.config?.levels || []}
                        minWidth="1120px"
                        rowKey={(level) => level.level}
                    />
                </AdminListBody>
            </DataState>
        </AdminListPage>
    );
}

function MaterialState({ level }) {
    const items = [
        ["封面", level.coverUrl],
        ["动效", level.animationUrl],
        ["发射", level.launchAnimationUrl],
        ["发射后图", level.launchedImageUrl],
    ];
    return (
        <div className={styles.assetBadges}>
            {items.map(([label, url]) => (
                <span
                    className={["status-badge", url ? "status-badge--running" : "status-badge--stopped"].join(" ")}
                    key={label}
                >
                    <span className="status-point" />
                    {label}
                </span>
            ))}
        </div>
    );
}

function RewardSummary({ groups, rewards = [], showQuantity = false }) {
    if (!rewards.length) {
        return <span className={styles.meta}>未配置</span>;
    }
    return (
        <div className={styles.stack}>
            <span className={styles.name}>
                {rewards.length} 个奖项{showQuantity ? ` · ${rewardQuantityTotal(rewards)} 份` : ""}
            </span>
            <span className={styles.meta}>
                {rewards
                    .slice(0, 2)
                    .map((reward) =>
                        showQuantity
                            ? `${resourceGroupName(groups, reward.resourceGroupId)} *${Number(reward.quantity || 1)}`
                            : resourceGroupName(groups, reward.resourceGroupId),
                    )
                    .join("、")}
            </span>
        </div>
    );
}

function rewardQuantityTotal(rewards) {
    return rewards.reduce((total, reward) => total + Number(reward.quantity || 1), 0);
}

function resourceGroupName(groups, id) {
    const group = groups.find((item) => Number(item.groupId) === Number(id));
    return group?.name || group?.groupCode || (id ? `#${id}` : "-");
}

function formatNumber(value) {
    return Number(value || 0).toLocaleString("zh-CN");
}
