import AddOutlined from "@mui/icons-material/AddOutlined";
import BedroomParentOutlined from "@mui/icons-material/BedroomParentOutlined";
import Autocomplete from "@mui/material/Autocomplete";
import TextField from "@mui/material/TextField";
import Tooltip from "@mui/material/Tooltip";
import { Button } from "@/shared/ui/Button.jsx";
import { AdminFormDialog } 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,
    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(120px, 0.5fr)",
        render: (room) => 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: "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={<AddOutlined fontSize="small" />} variant="primary" onClick={page.openCreate}>
                                增加机器人房间
                            </Button>
                        </div>
                    ) : null}
                </div>

                <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}
            >
                <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}>
                            <RobotIdentity user={option.user} fallbackId={option.userId} />
                        </li>
                    )}
                    size="small"
                    value={page.selectedOwnerRobot}
                    onChange={(_, option) => page.selectOwnerRobot(option)}
                />
                <Autocomplete
                    multiple
                    disableCloseOnSelect
                    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}>
                            <RobotIdentity user={option.user} fallbackId={option.userId} />
                        </li>
                    )}
                    size="small"
                    value={page.selectedCandidateRobots}
                    onChange={(_, options) => page.selectCandidateRobots(options)}
                />
                <div className={styles.formGrid}>
                    <TextField
                        label="最少进房人数"
                        required
                        type="number"
                        value={page.form.minRobotCount}
                        onChange={(event) => page.setForm({ ...page.form, minRobotCount: event.target.value })}
                    />
                    <TextField
                        label="最多进房人数"
                        required
                        type="number"
                        value={page.form.maxRobotCount}
                        onChange={(event) => page.setForm({ ...page.form, maxRobotCount: event.target.value })}
                    />
                </div>
                <Autocomplete
                    multiple
                    disableCloseOnSelect
                    getOptionLabel={giftOptionLabel}
                    isOptionEqualToValue={(option, value) => giftId(option) === giftId(value)}
                    loading={page.giftOptionsLoading}
                    noOptionsText="当前无数据"
                    options={page.giftOptions}
                    renderInput={(params) => (
                        <TextField
                            {...params}
                            error={Boolean(page.giftOptionsError)}
                            helperText={page.giftOptionsError}
                            label="礼物合集"
                            required
                        />
                    )}
                    size="small"
                    value={page.selectedGiftOptions}
                    onChange={(_, options) => page.selectGiftIds("giftIds", options)}
                />
                <TextField
                    label="普通礼物频次(毫秒)"
                    required
                    type="number"
                    value={page.form.normalGiftIntervalMs}
                    onChange={(event) => page.setForm({ ...page.form, normalGiftIntervalMs: event.target.value })}
                />
                <Autocomplete
                    multiple
                    disableCloseOnSelect
                    getOptionLabel={giftOptionLabel}
                    isOptionEqualToValue={(option, value) => giftId(option) === giftId(value)}
                    loading={page.giftOptionsLoading}
                    noOptionsText="当前无数据"
                    options={page.giftOptions}
                    renderInput={(params) => (
                        <TextField
                            {...params}
                            error={Boolean(page.giftOptionsError)}
                            helperText={page.giftOptionsError}
                            label="幸运礼物合集"
                            required
                        />
                    )}
                    size="small"
                    value={page.selectedLuckyGiftOptions}
                    onChange={(_, options) => page.selectGiftIds("luckyGiftIds", options)}
                />
                <div className={styles.formGrid}>
                    <TextField
                        label="最少幸运连击"
                        required
                        type="number"
                        value={page.form.luckyComboMin}
                        onChange={(event) => page.setForm({ ...page.form, luckyComboMin: event.target.value })}
                    />
                    <TextField
                        label="最多幸运连击"
                        required
                        type="number"
                        value={page.form.luckyComboMax}
                        onChange={(event) => page.setForm({ ...page.form, luckyComboMax: event.target.value })}
                    />
                    <TextField
                        label="最短幸运间隔(毫秒)"
                        required
                        type="number"
                        value={page.form.luckyPauseMinMs}
                        onChange={(event) => page.setForm({ ...page.form, luckyPauseMinMs: event.target.value })}
                    />
                    <TextField
                        label="最长幸运间隔(毫秒)"
                        required
                        type="number"
                        value={page.form.luckyPauseMaxMs}
                        onChange={(event) => page.setForm({ ...page.form, luckyPauseMaxMs: event.target.value })}
                    />
                </div>
            </AdminFormDialog>
        </section>
    );
}

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({ user = {}, fallbackId = "" }) {
    return <AdminUserIdentity openInAppUserDetail rows={[user.displayUserId, user.userId || fallbackId]} user={user} />;
}

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")}秒`;
}
