import MenuItem from "@mui/material/MenuItem";
import TextField from "@mui/material/TextField";
import { useMemo } from "react";
import {
    appJumpExploreGameCodeOptions,
    appJumpTargetOptions,
    appJumpWindowOptions,
    buildAppJumpParam,
    normalizeJumpConfigType,
    parseAppJumpParam,
} from "@/shared/app-jump/appJumpConfig.js";
import { AdminFormFieldGrid } from "@/shared/ui/AdminFormDialog.jsx";
import styles from "@/shared/ui/AppJumpConfigField.module.css";

export function AppJumpConfigField({
    allowCustom = true,
    allowH5 = true,
    appParamLabel = "APP 参数 JSON",
    className = "",
    disabled = false,
    h5Label = "H5 链接",
    messages = {},
    onChange,
    paramValue,
    required = false,
    showHint = true,
    typeLabel = "跳转类型",
    typeValue,
}) {
    const type = normalizeJumpConfigType(typeValue);
    const appJump = useMemo(() => parseAppJumpParam(paramValue), [paramValue]);
    const appTargetOptions = useMemo(
        () => (allowCustom ? appJumpTargetOptions : appJumpTargetOptions.filter(([value]) => value !== "custom")),
        [allowCustom],
    );
    const appTargetValue = !allowCustom && appJump.target === "custom" ? "wallet" : appJump.target;
    const setType = (nextType) => {
        if (nextType === "app") {
            onChange({ param: buildAppJumpParam({ target: "wallet" }), type: "app" });
            return;
        }
        onChange({ param: "", type: "h5" });
    };
    const setAppJump = (patch) => {
        const next = { ...appJump, ...patch };
        if (next.target === "custom") {
            onChange({ param: next.raw, type: "app" });
            return;
        }
        onChange({ param: buildAppJumpParam(next), type: "app" });
    };

    return (
        <div className={[styles.root, className].filter(Boolean).join(" ")}>
            <AdminFormFieldGrid columns="repeat(2, minmax(0, 1fr))">
                <TextField
                    disabled={disabled}
                    label={typeLabel}
                    required={required}
                    select
                    value={type}
                    onChange={(event) => setType(event.target.value)}
                >
                    {allowH5 ? <MenuItem value="h5">H5</MenuItem> : null}
                    <MenuItem value="app">APP</MenuItem>
                </TextField>
                {type === "h5" ? (
                    <TextField
                        className={styles.wide}
                        disabled={disabled}
                        label={h5Label}
                        required={required}
                        value={paramValue}
                        onChange={(event) => onChange({ param: event.target.value, type: "h5" })}
                    />
                ) : (
                    <>
                        <TextField
                            disabled={disabled}
                            label={messages.appTarget || "APP 目标"}
                            required
                            select
                            value={appTargetValue}
                            onChange={(event) => setAppJump({ target: event.target.value })}
                        >
                            {appTargetOptions.map(([value, label]) => (
                                <MenuItem key={value} value={value}>
                                    {messages.targets?.[value] || label}
                                </MenuItem>
                            ))}
                        </TextField>
                        <AppJumpStructuredFields appJump={appJump} disabled={disabled} messages={messages} onChange={setAppJump} />
                        <TextField
                            className={styles.wide}
                            disabled={disabled}
                            label={appParamLabel}
                            minRows={2}
                            multiline
                            required
                            value={paramValue}
                            onChange={(event) => onChange({ param: event.target.value, type: "app" })}
                        />
                    </>
                )}
            </AdminFormFieldGrid>
            {type === "app" && showHint ? (
                <p className={styles.hint}>{messages.hint || "APP 参数会按公共跳转方案生成 JSON；需要特殊参数时可直接编辑 JSON。"}</p>
            ) : null}
        </div>
    );
}

function AppJumpStructuredFields({ appJump, disabled, messages, onChange }) {
    if (appJump.target === "custom" || appJump.target === "wallet" || appJump.target === "room_random") {
        return null;
    }

    return (
        <>
            {needsRoomId(appJump.target) ? (
                <TextField
                    disabled={disabled}
                    label={messages.roomId || "房间 ID"}
                    required
                    value={appJump.roomId}
                    onChange={(event) => onChange({ roomId: event.target.value })}
                />
            ) : null}
            {needsWindow(appJump.target) ? (
                <TextField
                    disabled={disabled}
                    label={messages.window || "房内窗口"}
                    required
                    select
                    value={appJump.window}
                    onChange={(event) => onChange({ window: event.target.value })}
                >
                    {appJumpWindowOptions.map(([value, label]) => (
                        <MenuItem key={value} value={value}>
                            {messages.windows?.[value] || label}
                        </MenuItem>
                    ))}
                </TextField>
            ) : null}
            {needsGameId(appJump.target, appJump.window) ? (
                <TextField
                    disabled={disabled}
                    label={messages.gameId || "游戏 ID"}
                    required={appJump.target === "room_game" || appJump.target === "room_random_game"}
                    value={appJump.gameId}
                    onChange={(event) => onChange({ gameId: event.target.value })}
                />
            ) : null}
            {needsExploreGameCode(appJump.target) ? (
                <TextField
                    disabled={disabled}
                    label="Game Code"
                    required
                    select
                    value={appJump.gameCode}
                    onChange={(event) => onChange({ gameCode: event.target.value })}
                >
                    {appJumpExploreGameCodeOptions.map(([value, label]) => (
                        <MenuItem key={value} value={value}>
                            {label}
                        </MenuItem>
                    ))}
                </TextField>
            ) : null}
            {needsGiftId(appJump.target, appJump.window) ? (
                <TextField
                    disabled={disabled}
                    label={messages.giftId || "礼物 ID"}
                    value={appJump.giftId}
                    onChange={(event) => onChange({ giftId: event.target.value })}
                />
            ) : null}
            {needsRedPacketNo(appJump.target, appJump.window) ? (
                <TextField
                    disabled={disabled}
                    label={messages.redPacketNo || "红包编号"}
                    value={appJump.redPacketNo}
                    onChange={(event) => onChange({ redPacketNo: event.target.value })}
                />
            ) : null}
        </>
    );
}

function needsRoomId(target) {
    return target === "room" || target === "room_window" || target === "room_game";
}

function needsWindow(target) {
    return target === "room_window" || target === "room_random_window";
}

function needsGameId(target, window) {
    return target === "room_game" || target === "room_random_game" || window === "game_window";
}

function needsExploreGameCode(target) {
    return target === "explore_game";
}

function needsGiftId(target, window) {
    return needsWindow(target) && window === "gift_panel";
}

function needsRedPacketNo(target, window) {
    return needsWindow(target) && window === "red_packet_claim";
}
