import AddOutlined from "@mui/icons-material/AddOutlined";
import BedroomParentOutlined from "@mui/icons-material/BedroomParentOutlined";
import DeleteOutlineOutlined from "@mui/icons-material/DeleteOutlineOutlined";
import TuneOutlined from "@mui/icons-material/TuneOutlined";
import Autocomplete from "@mui/material/Autocomplete";
import MenuItem from "@mui/material/MenuItem";
import TextField from "@mui/material/TextField";
import Tooltip from "@mui/material/Tooltip";
import { Button } from "@/shared/ui/Button.jsx";
import { IconButton } from "@/shared/ui/IconButton.jsx";
import {
    AdminFormAmountField,
    AdminFormDialog,
    AdminFormFieldGrid,
    AdminFormSection,
} from "@/shared/ui/AdminFormDialog.jsx";
import { AdminUserIdentity } from "@/shared/ui/AdminUserIdentity.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import { DataTable } from "@/shared/ui/DataTable.jsx";
import { AdminSwitch } from "@/shared/ui/AdminSwitch.jsx";
import { AdminFilterResetButton } from "@/shared/ui/AdminListLayout.jsx";
import { createOptionsColumnFilter } from "@/shared/ui/tableFilters.js";
import { formatMillis } from "@/shared/utils/time.js";
import {
    giftId,
    giftOptionLabel,
    robotLocationLabel,
    robotOptionLabel,
    useRobotRoomsPage,
} from "@/features/rooms/hooks/useRobotRoomsPage.js";
import styles from "@/features/rooms/rooms.module.css";

const statusOptions = [
    { label: "运行中", value: "active" },
    { label: "已停止", value: "stopped" },
    { label: "全部状态", value: "all" },
];

const columns = [
    {
        key: "room",
        label: "房间信息",
        width: "minmax(280px, 1.4fr)",
        render: (room) => <RobotRoomIdentity room={room} />,
    },
    {
        key: "owner",
        label: "房主机器人",
        width: "minmax(220px, 1fr)",
        render: (room) => <RobotIdentity user={room.owner} fallbackId={room.ownerRobotUserId} />,
    },
    {
        key: "robots",
        label: "机器人",
        width: "minmax(150px, 0.6fr)",
        render: (room) => (
            <RuleStack
                rows={[
                    `活跃 ${Number(room.activeRobotCount || 0).toLocaleString("zh-CN")}`,
                    `候选 ${Number(room.robotUserIds?.length || room.robots?.length || 0).toLocaleString("zh-CN")}`,
                ]}
            />
        ),
    },
    {
        key: "normalRule",
        label: "普通礼物",
        width: "minmax(190px, 0.8fr)",
        render: (room) => (
            <RuleStack
                rows={[
                    `${room.giftRule?.giftIds?.length || 0} 个礼物`,
                    `${formatSeconds(room.giftRule?.normalGiftIntervalMs)} / 次`,
                ]}
            />
        ),
    },
    {
        key: "luckyRule",
        label: "幸运礼物",
        width: "minmax(220px, 0.9fr)",
        render: (room) => (
            <RuleStack
                rows={[
                    `${room.giftRule?.luckyGiftIds?.length || 0} 个礼物`,
                    `${room.giftRule?.luckyComboMin || 0}-${room.giftRule?.luckyComboMax || 0} 连击`,
                    `${formatSeconds(room.giftRule?.luckyPauseMinMs)}-${formatSeconds(room.giftRule?.luckyPauseMaxMs)} 间隔`,
                ]}
            />
        ),
    },
    {
        key: "behaviorRule",
        label: "行为",
        width: "minmax(220px, 0.9fr)",
        render: (room) => (
            <RuleStack
                rows={[
                    `${formatDurationRange(room.giftRule?.robotStayMinMs, room.giftRule?.robotStayMaxMs)} 停留`,
                    `${formatDurationRange(room.giftRule?.robotReplaceMinMs, room.giftRule?.robotReplaceMaxMs)} 补位`,
                    `最多 ${Number(room.giftRule?.maxGiftSenders || 0).toLocaleString("zh-CN")} 个送礼`,
                ]}
            />
        ),
    },
    {
        key: "createdAt",
        label: "创建时间",
        width: "minmax(170px, 0.8fr)",
        render: (room) => formatMillis(room.createdAtMs),
    },
];

export function RoomRobotPage() {
    const page = useRobotRoomsPage();
    const items = page.data.items || [];
    const total = page.data.total || 0;
    const tableColumns = [
        ...columns.map((column) =>
            column.key === "createdAt"
                ? {
                      ...column,
                      filter: createOptionsColumnFilter({
                          options: statusOptions,
                          placeholder: "房间状态",
                          value: page.status,
                          onChange: page.changeStatus,
                      }),
                  }
                : column,
        ),
        {
            key: "status",
            label: "状态",
            width: "minmax(112px, 0.5fr)",
            render: (room) => <RobotRoomStatus page={page} room={room} />,
        },
    ];

    return (
        <section className={styles.root}>
            <div className={styles.contentPanel}>
                <div className={styles.toolbar}>
                    <section className={styles.filters}>
                        <AdminFilterResetButton disabled={page.status === "active"} onClick={page.resetFilters} />
                    </section>
                    {page.abilities.canRobotCreate ? (
                        <div className={styles.toolbarActions}>
                            <Button
                                startIcon={<TuneOutlined fontSize="small" />}
                                variant="secondary"
                                onClick={page.openHumanConfig}
                            >
                                真人房间机器人配置
                            </Button>
                            <Button
                                startIcon={<AddOutlined fontSize="small" />}
                                variant="primary"
                                onClick={page.openCreate}
                            >
                                增加机器人房间
                            </Button>
                        </div>
                    ) : null}
                </div>
                <HumanConfigPanel page={page} />

                <DataState error={page.error} loading={page.loading} onRetry={page.reload}>
                    <div className={styles.listBlock}>
                        <DataTable
                            columns={tableColumns}
                            items={items}
                            minWidth="1320px"
                            rowKey={(room) => room.roomId}
                            pagination={
                                total > 0
                                    ? {
                                          page: page.page,
                                          pageSize: page.data.pageSize || 50,
                                          total,
                                          onPageChange: page.setPage,
                                      }
                                    : undefined
                            }
                        />
                    </div>
                </DataState>
            </div>

            <AdminFormDialog
                loading={page.loadingAction === "create"}
                open={page.activeAction === "create"}
                size="wide"
                submitDisabled={!page.abilities.canRobotCreate || page.loadingAction === "create"}
                title="增加机器人房间"
                onClose={page.closeAction}
                onSubmit={page.submitCreate}
            >
                <AdminFormSection title="房主设置">
                    <Autocomplete
                        getOptionLabel={robotOptionLabel}
                        isOptionEqualToValue={(option, value) => option.userId === value.userId}
                        loading={page.availableRobotsLoading}
                        noOptionsText="当前无数据"
                        options={page.availableRobots}
                        renderInput={(params) => (
                            <TextField
                                {...params}
                                error={Boolean(page.availableRobotsError)}
                                helperText={page.availableRobotsError}
                                label="房主机器人"
                                required
                            />
                        )}
                        renderOption={(props, option) => (
                            <li {...props} key={option.userId}>
                                <OwnerRobotOption
                                    countryLabels={page.robotCountryLabels}
                                    loadingLocation={page.loadingRobotLocationOptions}
                                    option={option}
                                    regionLabels={page.robotRegionLabels}
                                />
                            </li>
                        )}
                        size="small"
                        value={page.selectedOwnerRobot}
                        onChange={(_, option) => page.selectOwnerRobot(option)}
                    />
                </AdminFormSection>
                <AdminFormSection title="进房规则">
                    <AdminFormFieldGrid>
                        <ConfigNumberField
                            label="最少进房人数"
                            value={page.form.minRobotCount}
                            onChange={(value) => page.setForm({ ...page.form, minRobotCount: value })}
                        />
                        <ConfigNumberField
                            label="最多进房人数"
                            value={page.form.maxRobotCount}
                            onChange={(value) => page.setForm({ ...page.form, maxRobotCount: value })}
                        />
                    </AdminFormFieldGrid>
                </AdminFormSection>
                <AdminFormSection title="普通礼物规则">
                    <GiftAutocomplete
                        error={Boolean(page.giftOptionsError)}
                        helperText={page.giftOptionsError}
                        label="礼物合集"
                        loading={page.giftOptionsLoading}
                        options={page.giftOptions}
                        required
                        value={page.selectedGiftOptions}
                        onChange={(options) => page.selectGiftIds("giftIds", options)}
                    />
                    <AdminFormFieldGrid>
                        <ConfigNumberField
                            label="普通礼物频次"
                            unit="毫秒"
                            value={page.form.normalGiftIntervalMs}
                            onChange={(value) => page.setForm({ ...page.form, normalGiftIntervalMs: value })}
                        />
                        <ConfigNumberField
                            label="最短停留"
                            unit="毫秒"
                            value={page.form.robotStayMinMs}
                            onChange={(value) => page.setForm({ ...page.form, robotStayMinMs: value })}
                        />
                        <ConfigNumberField
                            label="最长停留"
                            unit="毫秒"
                            value={page.form.robotStayMaxMs}
                            onChange={(value) => page.setForm({ ...page.form, robotStayMaxMs: value })}
                        />
                        <ConfigNumberField
                            label="最短补位"
                            min={0}
                            unit="毫秒"
                            value={page.form.robotReplaceMinMs}
                            onChange={(value) => page.setForm({ ...page.form, robotReplaceMinMs: value })}
                        />
                        <ConfigNumberField
                            label="最长补位"
                            min={0}
                            unit="毫秒"
                            value={page.form.robotReplaceMaxMs}
                            onChange={(value) => page.setForm({ ...page.form, robotReplaceMaxMs: value })}
                        />
                        <ConfigNumberField
                            label="同时送礼上限"
                            value={page.form.maxGiftSenders}
                            onChange={(value) => page.setForm({ ...page.form, maxGiftSenders: value })}
                        />
                    </AdminFormFieldGrid>
                </AdminFormSection>
                <AdminFormSection title="幸运礼物规则">
                    <GiftAutocomplete
                        error={Boolean(page.giftOptionsError)}
                        helperText={page.giftOptionsError}
                        label="幸运礼物合集"
                        loading={page.giftOptionsLoading}
                        options={page.giftOptions}
                        required
                        value={page.selectedLuckyGiftOptions}
                        onChange={(options) => page.selectGiftIds("luckyGiftIds", options)}
                    />
                    <AdminFormFieldGrid>
                        <ConfigNumberField
                            label="最少幸运连击"
                            value={page.form.luckyComboMin}
                            onChange={(value) => page.setForm({ ...page.form, luckyComboMin: value })}
                        />
                        <ConfigNumberField
                            label="最多幸运连击"
                            value={page.form.luckyComboMax}
                            onChange={(value) => page.setForm({ ...page.form, luckyComboMax: value })}
                        />
                        <ConfigNumberField
                            label="最短幸运间隔"
                            unit="毫秒"
                            value={page.form.luckyPauseMinMs}
                            onChange={(value) => page.setForm({ ...page.form, luckyPauseMinMs: value })}
                        />
                        <ConfigNumberField
                            label="最长幸运间隔"
                            unit="毫秒"
                            value={page.form.luckyPauseMaxMs}
                            onChange={(value) => page.setForm({ ...page.form, luckyPauseMaxMs: value })}
                        />
                    </AdminFormFieldGrid>
                </AdminFormSection>
            </AdminFormDialog>
            <HumanConfigDialog page={page} />
        </section>
    );
}

function HumanConfigPanel({ page }) {
    const config = page.humanConfig || {};
    return (
        <section className={styles.robotConfigPanel}>
            <div>
                <div className={styles.primaryText}>真人房间机器人</div>
                <div className={styles.meta}>
                    {page.humanConfigLoading
                        ? "配置加载中"
                        : page.humanConfigError || (config.enabled ? "已启用" : "未启用")}
                </div>
            </div>
            <RuleStack
                rows={[
                    `低于 ${Number(config.candidateRoomMaxOnline || 5).toLocaleString("zh-CN")} 人进房`,
                    `目标 ${Number(config.roomTargetMinOnline || config.roomFullStopOnline || 8).toLocaleString("zh-CN")}-${Number(config.roomTargetMaxOnline || config.roomFullStopOnline || 10).toLocaleString("zh-CN")} 人`,
                    `${formatDurationRange(config.robotStayMinMs || 60000, config.robotStayMaxMs || 600000)} 停留`,
                ]}
            />
            <RuleStack
                rows={[
                    "自动使用全站机器人",
                    `${formatDurationRange(
                        config.normalGiftIntervalMinMs || config.normalGiftIntervalMs || 10000,
                        config.normalGiftIntervalMaxMs || config.normalGiftIntervalMs || 10000,
                    )} / 次`,
                    `${Number(config.maxGiftSenders || 1).toLocaleString("zh-CN")} 个机器人送礼`,
                    `${config.giftIds?.length || 0} 个普通礼物`,
                    `${(config.luckyGiftIds?.length || 0) + (config.superLuckyGiftIds?.length || 0)} 个幸运礼物`,
                ]}
            />
            {page.abilities.canRobotUpdate ? (
                <div className={styles.humanConfigActions}>
                    <Button
                        loading={page.humanConfigLoading}
                        startIcon={<TuneOutlined fontSize="small" />}
                        variant="secondary"
                        onClick={page.openHumanCountryConfig}
                    >
                        {config.countryLimitEnabled ? "国家配置" : "国家启用"}
                    </Button>
                    <Button
                        loading={page.humanConfigLoading}
                        startIcon={<TuneOutlined fontSize="small" />}
                        variant="secondary"
                        onClick={page.openHumanConfig}
                    >
                        配置
                    </Button>
                </div>
            ) : null}
        </section>
    );
}

function HumanConfigDialog({ page }) {
    return (
        <AdminFormDialog
            loading={page.loadingAction === "human-config"}
            open={page.activeAction === "human-config"}
            size="wide"
            submitDisabled={!page.abilities.canRobotUpdate || page.loadingAction === "human-config"}
            title="真人房间机器人配置"
            onClose={page.closeAction}
            onSubmit={page.submitHumanConfig}
        >
            <AdminFormSection
                actions={
                    <div className={styles.configSwitchActions}>
                        <span className={styles.switchField}>
                            <AdminSwitch
                                checked={Boolean(page.humanConfigForm.enabled)}
                                checkedLabel="启用"
                                label="启用真人房间机器人"
                                uncheckedLabel="关闭"
                                onChange={(_, checked) =>
                                    page.setHumanConfigForm({ ...page.humanConfigForm, enabled: checked })
                                }
                            />
                        </span>
                    </div>
                }
                title="基础规则"
            >
                <AdminFormFieldGrid>
                    <ConfigNumberField
                        label="真人房间低于人数"
                        value={page.humanConfigForm.candidateRoomMaxOnline}
                        onChange={(value) =>
                            page.setHumanConfigForm({
                                ...page.humanConfigForm,
                                candidateRoomMaxOnline: value,
                            })
                        }
                    />
                    <ConfigNumberField
                        label="目标人数下限"
                        value={page.humanConfigForm.roomTargetMinOnline}
                        onChange={(value) =>
                            page.setHumanConfigForm({ ...page.humanConfigForm, roomTargetMinOnline: value })
                        }
                    />
                    <ConfigNumberField
                        label="目标人数上限"
                        value={page.humanConfigForm.roomTargetMaxOnline}
                        onChange={(value) =>
                            page.setHumanConfigForm({ ...page.humanConfigForm, roomTargetMaxOnline: value })
                        }
                    />
                </AdminFormFieldGrid>
            </AdminFormSection>

            <AdminFormSection title="送礼机器人规则">
                <AdminFormFieldGrid>
                    <ConfigNumberField
                        label="最短送礼间隔"
                        unit="毫秒"
                        value={page.humanConfigForm.normalGiftIntervalMinMs}
                        onChange={(value) =>
                            page.setHumanConfigForm({
                                ...page.humanConfigForm,
                                normalGiftIntervalMinMs: value,
                            })
                        }
                    />
                    <ConfigNumberField
                        label="最长送礼间隔"
                        unit="毫秒"
                        value={page.humanConfigForm.normalGiftIntervalMaxMs}
                        onChange={(value) =>
                            page.setHumanConfigForm({
                                ...page.humanConfigForm,
                                normalGiftIntervalMaxMs: value,
                            })
                        }
                    />
                    <ConfigNumberField
                        label="最短停留"
                        unit="毫秒"
                        value={page.humanConfigForm.robotStayMinMs}
                        onChange={(value) =>
                            page.setHumanConfigForm({ ...page.humanConfigForm, robotStayMinMs: value })
                        }
                    />
                    <ConfigNumberField
                        label="最长停留"
                        unit="毫秒"
                        value={page.humanConfigForm.robotStayMaxMs}
                        onChange={(value) =>
                            page.setHumanConfigForm({ ...page.humanConfigForm, robotStayMaxMs: value })
                        }
                    />
                    <ConfigNumberField
                        label="最短补位"
                        min={0}
                        unit="毫秒"
                        value={page.humanConfigForm.robotReplaceMinMs}
                        onChange={(value) =>
                            page.setHumanConfigForm({ ...page.humanConfigForm, robotReplaceMinMs: value })
                        }
                    />
                    <ConfigNumberField
                        label="最长补位"
                        min={0}
                        unit="毫秒"
                        value={page.humanConfigForm.robotReplaceMaxMs}
                        onChange={(value) =>
                            page.setHumanConfigForm({ ...page.humanConfigForm, robotReplaceMaxMs: value })
                        }
                    />
                    <ConfigNumberField
                        label="房间送礼机器人数"
                        value={page.humanConfigForm.maxGiftSenders}
                        onChange={(value) =>
                            page.setHumanConfigForm({ ...page.humanConfigForm, maxGiftSenders: value })
                        }
                    />
                </AdminFormFieldGrid>
            </AdminFormSection>

            <AdminFormSection title="礼物合集">
                <GiftAutocomplete
                    label="普通礼物合集"
                    loading={page.giftOptionsLoading}
                    options={page.giftOptions}
                    required
                    value={page.selectedHumanGiftOptions.giftIds}
                    onChange={(options) => page.selectHumanGiftIds("giftIds", options)}
                />
                <GiftAutocomplete
                    label="幸运礼物合集"
                    loading={page.giftOptionsLoading}
                    options={page.giftOptions}
                    value={page.selectedHumanGiftOptions.luckyGiftIds}
                    onChange={(options) => page.selectHumanGiftIds("luckyGiftIds", options)}
                />
                <GiftAutocomplete
                    label="超级幸运礼物合集"
                    loading={page.giftOptionsLoading}
                    options={page.giftOptions}
                    value={page.selectedHumanGiftOptions.superLuckyGiftIds}
                    onChange={(options) => page.selectHumanGiftIds("superLuckyGiftIds", options)}
                />
            </AdminFormSection>

            <AdminFormSection title="幸运连击规则">
                <AdminFormFieldGrid>
                    <ConfigNumberField
                        label="最少幸运连击"
                        value={page.humanConfigForm.luckyComboMin}
                        onChange={(value) =>
                            page.setHumanConfigForm({ ...page.humanConfigForm, luckyComboMin: value })
                        }
                    />
                    <ConfigNumberField
                        label="最多幸运连击"
                        value={page.humanConfigForm.luckyComboMax}
                        onChange={(value) =>
                            page.setHumanConfigForm({ ...page.humanConfigForm, luckyComboMax: value })
                        }
                    />
                    <ConfigNumberField
                        label="最短幸运间隔"
                        unit="毫秒"
                        value={page.humanConfigForm.luckyPauseMinMs}
                        onChange={(value) =>
                            page.setHumanConfigForm({ ...page.humanConfigForm, luckyPauseMinMs: value })
                        }
                    />
                    <ConfigNumberField
                        label="最长幸运间隔"
                        unit="毫秒"
                        value={page.humanConfigForm.luckyPauseMaxMs}
                        onChange={(value) =>
                            page.setHumanConfigForm({ ...page.humanConfigForm, luckyPauseMaxMs: value })
                        }
                    />
                </AdminFormFieldGrid>
            </AdminFormSection>

            <AdminFormSection
                actions={
                    <div className={styles.configSwitchActions}>
                        <span className={styles.switchField}>
                            <AdminSwitch
                                checked={Boolean(page.humanConfigForm.countryLimitEnabled)}
                                checkedLabel="启用"
                                label="启用国家配置"
                                uncheckedLabel="关闭"
                                onChange={(_, checked) => page.setHumanCountryLimitEnabled(checked)}
                            />
                        </span>
                    </div>
                }
                title="国家进房配置"
            >
                {page.humanConfigForm.countryLimitEnabled ? <HumanCountryRules page={page} /> : null}
            </AdminFormSection>
        </AdminFormDialog>
    );
}

function ConfigNumberField({ label, min = 1, onChange, size, unit, value }) {
    const fieldProps = {
        label,
        required: true,
        size,
        slotProps: { htmlInput: { min, step: 1 } },
        type: "number",
        value,
        onChange: (event) => onChange(event.target.value),
    };

    return unit ? <AdminFormAmountField {...fieldProps} unit={unit} /> : <TextField {...fieldProps} />;
}

function HumanCountryRules({ page }) {
    const rows = page.humanConfigForm.countryRules || [];
    return (
        <section className={styles.countryRulesSection}>
            <div className={styles.countryRulesHeader}>
                <div className={styles.meta}>按机器人账号国家限制同时进入真人房的房间数量</div>
                <Button
                    startIcon={<AddOutlined fontSize="small" />}
                    variant="secondary"
                    onClick={page.addHumanCountryRule}
                >
                    添加国家
                </Button>
            </div>
            <div className={styles.countryRuleRows}>
                {rows.map((rule, index) => (
                    <div className={styles.countryRuleRow} key={`${rule.countryCode || "country"}-${index}`}>
                        <TextField
                            label="国家"
                            required
                            select
                            size="small"
                            value={rule.countryCode || ""}
                            onChange={(event) =>
                                page.updateHumanCountryRule(index, { countryCode: event.target.value })
                            }
                        >
                            {countrySelectOptions(page.countryOptions, rule.countryCode).map((option) => (
                                <MenuItem key={option.value} value={option.value}>
                                    {option.label}
                                </MenuItem>
                            ))}
                        </TextField>
                        <ConfigNumberField
                            label="进房数量"
                            size="small"
                            value={rule.maxRoomCount}
                            onChange={(value) => page.updateHumanCountryRule(index, { maxRoomCount: value })}
                        />
                        <TextField
                            className={styles.countryRuleOwners}
                            label="房主ID列表"
                            placeholder="输入房主ID，逗号分隔"
                            size="small"
                            value={rule.allowedOwnerIds || ""}
                            onChange={(event) =>
                                page.updateHumanCountryRule(index, { allowedOwnerIds: event.target.value })
                            }
                        />
                        <Tooltip arrow title="删除">
                            <span className={styles.countryRuleRemove}>
                                <IconButton
                                    label="删除国家规则"
                                    tone="danger"
                                    onClick={() => page.removeHumanCountryRule(index)}
                                >
                                    <DeleteOutlineOutlined fontSize="small" />
                                </IconButton>
                            </span>
                        </Tooltip>
                    </div>
                ))}
                {rows.length === 0 ? <div className={styles.meta}>当前无数据</div> : null}
            </div>
        </section>
    );
}

function GiftAutocomplete({ error = false, helperText = "", label, loading, onChange, options, required = false, value }) {
    return (
        <Autocomplete
            multiple
            disableCloseOnSelect
            getOptionLabel={giftOptionLabel}
            isOptionEqualToValue={(option, selected) => giftId(option) === giftId(selected)}
            loading={loading}
            noOptionsText="当前无数据"
            options={options}
            renderInput={(params) => (
                <TextField
                    {...params}
                    error={error}
                    helperText={helperText}
                    label={required ? <RequiredLabel>{label}</RequiredLabel> : label}
                />
            )}
            size="small"
            value={value}
            onChange={(_, selected) => onChange(selected)}
        />
    );
}

function RobotRoomIdentity({ room }) {
    return (
        <div className={styles.identity}>
            <span className={styles.cover}>
                {room.coverUrl ? <img src={room.coverUrl} alt="" /> : <BedroomParentOutlined fontSize="small" />}
            </span>
            <div className={styles.identityText}>
                <div className={styles.name}>{room.title || "-"}</div>
                <div className={styles.meta}>长ID {room.roomId || "-"}</div>
                <div className={styles.meta}>短ID {room.roomShortId || "-"}</div>
            </div>
        </div>
    );
}

function RobotIdentity({ fallbackId = "", openInAppUserDetail = true, user = {} }) {
    return (
        <AdminUserIdentity
            openInAppUserDetail={openInAppUserDetail}
            rows={[user.displayUserId, user.userId || fallbackId]}
            user={user}
        />
    );
}

function OwnerRobotOption({ countryLabels, loadingLocation, option, regionLabels }) {
    return (
        <div className={styles.ownerRobotOption}>
            <RobotIdentity openInAppUserDetail={false} user={option.user} fallbackId={option.userId} />
            <span className={styles.ownerRobotLocation}>
                {loadingLocation ? "国家/区域加载中" : robotLocationLabel(option, countryLabels, regionLabels)}
            </span>
        </div>
    );
}

function RequiredLabel({ children }) {
    return (
        <span>
            {children} <span aria-hidden="true">*</span>
        </span>
    );
}

function countrySelectOptions(options = [], currentValue = "") {
    const current = String(currentValue || "").toUpperCase();
    const merged = options.map((option) => ({
        label: option.label,
        value: option.value,
    }));
    if (current && !merged.some((option) => option.value === current)) {
        merged.unshift({ label: current, value: current });
    }
    if (!merged.length) {
        return current ? [{ label: current, value: current }] : [{ label: "暂无可用国家", value: "" }];
    }
    return merged;
}

function RobotRoomStatus({ page, room }) {
    const checked = room.status === "active";
    return (
        <div className={styles.statusCell}>
            <Tooltip arrow title={checked ? "停止" : "启动"}>
                <span>
                    <AdminSwitch
                        checked={checked}
                        checkedLabel="运行"
                        disabled={!page.abilities.canRobotUpdate || page.loadingAction === `status-${room.roomId}`}
                        label={checked ? "停止机器人房间" : "启动机器人房间"}
                        uncheckedLabel="停止"
                        onChange={() => page.setRoomStatus(room)}
                    />
                </span>
            </Tooltip>
        </div>
    );
}

function RuleStack({ rows }) {
    return (
        <div className={styles.stack}>
            {rows.map((row) => (
                <span className={styles.meta} key={row}>
                    {row}
                </span>
            ))}
        </div>
    );
}

function formatSeconds(ms) {
    const seconds = Math.round(Number(ms || 0) / 1000);
    return `${seconds.toLocaleString("zh-CN")}秒`;
}

function formatDurationRange(minMs, maxMs) {
    return `${formatSeconds(minMs)}-${formatSeconds(maxMs)}`;
}
