import AddOutlined from "@mui/icons-material/AddOutlined";
import ArrowBackOutlined from "@mui/icons-material/ArrowBackOutlined";
import DeleteOutlineOutlined from "@mui/icons-material/DeleteOutlineOutlined";
import SaveOutlined from "@mui/icons-material/SaveOutlined";
import MenuItem from "@mui/material/MenuItem";
import Tab from "@mui/material/Tab";
import Tabs from "@mui/material/Tabs";
import TextField from "@mui/material/TextField";
import Tooltip from "@mui/material/Tooltip";
import { useMemo, useState } from "react";
import { AdminSwitch } from "@/shared/ui/AdminSwitch.jsx";
import { Button } from "@/shared/ui/Button.jsx";
import { IconButton } from "@/shared/ui/IconButton.jsx";
import { ResourceGroupSelectField } from "@/shared/ui/ResourceGroupSelectDrawer.jsx";
import { UploadField } from "@/shared/ui/UploadField.jsx";
import styles from "@/features/room-rocket/room-rocket.module.css";

const fuelSourceOptions = [["heat_value", "礼物贡献"]];

const broadcastScopeOptions = [
    ["region", "区域广播"],
    ["global", "全局广播"],
    ["none", "不广播"],
];

const rewardStackPolicyOptions = [
    ["allow_stack", "允许叠加"],
    ["priority_only", "优先级单份"],
];

const rewardTabs = [
    ["inRoomRewards", "在房奖励"],
    ["top1Rewards", "贡献第一"],
    ["igniterRewards", "点火人"],
];

export function RoomRocketConfigEditor({
    abilities,
    configLoading,
    configSaving,
    form,
    onCancel,
    onSubmit,
    resourceGroups,
    setForm,
}) {
    const disabled = !abilities.canUpdate || configLoading || configSaving;
    const [activeLevel, setActiveLevel] = useState(1);
    const [rewardTab, setRewardTab] = useState("inRoomRewards");
    const [editorTab, setEditorTab] = useState("levels");
    const activeLevelIndex = useMemo(
        () =>
            Math.max(
                0,
                form.levels.findIndex((level) => Number(level.level) === Number(activeLevel)),
            ),
        [activeLevel, form.levels],
    );
    const level = form.levels[activeLevelIndex] || form.levels[0];

    return (
        <form className={styles.editorPage} onSubmit={onSubmit}>
            <div className={styles.editorActionBar}>
                <div className={styles.editorTitleGroup}>
                    <Button startIcon={<ArrowBackOutlined fontSize="small" />} type="button" onClick={onCancel}>
                        返回
                    </Button>
                    <div className={styles.stack}>
                        <span className={styles.title}>房间火箭配置</span>
                        <span className={styles.meta}>编辑 5 级火箭物料、奖励池和礼物燃料规则</span>
                    </div>
                </div>
                <div className={styles.editorActions}>
                    <Button disabled={configSaving} type="button" onClick={onCancel}>
                        取消
                    </Button>
                    <Button
                        disabled={disabled}
                        startIcon={<SaveOutlined fontSize="small" />}
                        type="submit"
                        variant="primary"
                    >
                        保存
                    </Button>
                </div>
            </div>

            <div className={styles.editorScrollBody}>
                <section className={styles.editorSection}>
                    <div className={styles.sectionTitle}>基础配置</div>
                    <div className={styles.basicGrid}>
                        <SwitchField
                            checked={form.enabled}
                            disabled={disabled}
                            label="火箭状态"
                            onChange={(event) => updateRoot(setForm, "enabled", event.target.checked)}
                        />
                        <SwitchField
                            checked={form.broadcastEnabled}
                            disabled={disabled}
                            label="发射广播"
                            onChange={(event) => updateRoot(setForm, "broadcastEnabled", event.target.checked)}
                        />
                        <SelectField
                            disabled={disabled}
                            label="燃料来源"
                            options={fuelSourceOptions}
                            value={form.fuelSource}
                            onChange={(value) => updateRoot(setForm, "fuelSource", value)}
                        />
                        <TextField
                            required
                            disabled={disabled}
                            label="发射倒计时 ms"
                            slotProps={{ htmlInput: { min: 0, step: 1000 } }}
                            type="number"
                            value={form.launchDelayMs}
                            onChange={(event) => updateRoot(setForm, "launchDelayMs", event.target.value)}
                        />
                        <SelectField
                            disabled={disabled}
                            label="广播范围"
                            options={broadcastScopeOptions}
                            value={form.broadcastScope}
                            onChange={(value) => updateRoot(setForm, "broadcastScope", value)}
                        />
                        <TextField
                            required
                            disabled={disabled}
                            label="广播延迟 ms"
                            slotProps={{ htmlInput: { min: 0, step: 1000 } }}
                            type="number"
                            value={form.broadcastDelayMs}
                            onChange={(event) => updateRoot(setForm, "broadcastDelayMs", event.target.value)}
                        />
                        <SelectField
                            disabled={disabled}
                            label="角色奖励策略"
                            options={rewardStackPolicyOptions}
                            value={form.rewardStackPolicy}
                            onChange={(value) => updateRoot(setForm, "rewardStackPolicy", value)}
                        />
                    </div>
                </section>

                <section className={styles.editorSection}>
                    <Tabs value={editorTab} onChange={(_, value) => setEditorTab(value)}>
                        <Tab label="等级配置" value="levels" />
                        <Tab label="礼物燃料规则" value="fuelRules" />
                    </Tabs>
                    {editorTab === "levels" ? (
                        <div className={styles.levelWorkspace}>
                            <aside className={styles.levelNav}>
                                {form.levels.map((item) => (
                                    <LevelNavItem
                                        active={Number(item.level) === Number(level?.level)}
                                        key={item.level}
                                        level={item}
                                        onClick={() => {
                                            setActiveLevel(item.level);
                                            setRewardTab("inRoomRewards");
                                        }}
                                    />
                                ))}
                            </aside>
                            {level ? (
                                <div className={styles.levelDetail}>
                                    <div className={styles.levelDetailHeader}>
                                        <div className={styles.stack}>
                                            <span className={styles.title}>L{level.level}</span>
                                            <span className={styles.meta}>
                                                当前等级溢出燃料作废，点火后下一等级立即开始
                                            </span>
                                        </div>
                                        <TextField
                                            required
                                            disabled={disabled}
                                            label="燃料阈值"
                                            slotProps={{ htmlInput: { min: 1, step: 1 } }}
                                            type="number"
                                            value={level.fuelThreshold}
                                            onChange={(event) =>
                                                updateLevel(setForm, activeLevelIndex, {
                                                    fuelThreshold: event.target.value,
                                                })
                                            }
                                        />
                                    </div>
                                    <div className={styles.materialGrid}>
                                        <UploadField
                                            density="compact"
                                            disabled={disabled}
                                            kind="image"
                                            label="封面图"
                                            value={level.coverUrl}
                                            onChange={(value) =>
                                                updateLevel(setForm, activeLevelIndex, { coverUrl: value })
                                            }
                                        />
                                        <UploadField
                                            density="compact"
                                            disabled={disabled}
                                            kind="file"
                                            label="火箭动效"
                                            uploadKind="file"
                                            value={level.animationUrl}
                                            onChange={(value) =>
                                                updateLevel(setForm, activeLevelIndex, { animationUrl: value })
                                            }
                                        />
                                        <UploadField
                                            density="compact"
                                            disabled={disabled}
                                            kind="file"
                                            label="发射动效"
                                            uploadKind="file"
                                            value={level.launchAnimationUrl}
                                            onChange={(value) =>
                                                updateLevel(setForm, activeLevelIndex, { launchAnimationUrl: value })
                                            }
                                        />
                                        <UploadField
                                            density="compact"
                                            disabled={disabled}
                                            kind="image"
                                            label="发射后图"
                                            value={level.launchedImageUrl}
                                            onChange={(value) =>
                                                updateLevel(setForm, activeLevelIndex, { launchedImageUrl: value })
                                            }
                                        />
                                    </div>
                                    <div className={styles.rewardPanel}>
                                        <div className={styles.rewardPanelHead}>
                                            <Tabs
                                                value={rewardTab}
                                                variant="scrollable"
                                                onChange={(_, value) => setRewardTab(value)}
                                            >
                                                {rewardTabs.map(([key, label]) => (
                                                    <Tab key={key} label={label} value={key} />
                                                ))}
                                            </Tabs>
                                            <Button
                                                disabled={disabled}
                                                startIcon={<AddOutlined fontSize="small" />}
                                                type="button"
                                                onClick={() => addReward(setForm, activeLevelIndex, rewardTab)}
                                            >
                                                添加奖项
                                            </Button>
                                        </div>
                                        <RewardTable
                                            disabled={disabled}
                                            levelIndex={activeLevelIndex}
                                            poolKey={rewardTab}
                                            resourceGroups={resourceGroups}
                                            rewards={level[rewardTab] || []}
                                            setForm={setForm}
                                        />
                                    </div>
                                </div>
                            ) : null}
                        </div>
                    ) : (
                        <FuelRuleEditor disabled={disabled} form={form} setForm={setForm} />
                    )}
                </section>
            </div>
        </form>
    );
}

function LevelNavItem({ active, level, onClick }) {
    const materialCount = [level.coverUrl, level.animationUrl, level.launchAnimationUrl, level.launchedImageUrl].filter(
        Boolean,
    ).length;
    const rewardCount = rewardTabs.filter(([key]) => (level[key] || []).length > 0).length;

    return (
        <button
            className={[styles.levelNavItem, active ? styles.levelNavItemActive : ""].join(" ")}
            type="button"
            onClick={onClick}
        >
            <span className={styles.levelNavMain}>L{level.level}</span>
            <span className={styles.levelNavMeta}>阈值 {formatNumber(level.fuelThreshold)}</span>
            <span className={styles.levelNavMeta}>
                物料 {materialCount}/4 · 奖励 {rewardCount}/3
            </span>
        </button>
    );
}

function RewardTable({ disabled, levelIndex, poolKey, resourceGroups, rewards, setForm }) {
    const quantityEnabled = poolKey === "inRoomRewards";

    if (!rewards.length) {
        return <div className={styles.emptyState}>未配置奖项</div>;
    }

    return (
        <div className={styles.rewardTable}>
            <div className={[styles.rewardTableHead, quantityEnabled ? styles.rewardTableWithQuantity : ""].join(" ")}>
                <span>资源组</span>
                <span>权重</span>
                {quantityEnabled ? <span>数量</span> : null}
                <span>展示名</span>
                <span>图标</span>
                <span />
            </div>
            {rewards.map((reward, rewardIndex) => (
                <div
                    className={[styles.rewardTableRow, quantityEnabled ? styles.rewardTableWithQuantity : ""].join(" ")}
                    key={reward.rewardItemId || rewardIndex}
                >
                    <ResourceGroupSelectField
                        disabled={disabled}
                        groups={resourceGroups}
                        label="资源组"
                        value={reward.resourceGroupId}
                        onChange={(value) =>
                            updateReward(setForm, levelIndex, poolKey, rewardIndex, { resourceGroupId: value })
                        }
                    />
                    <TextField
                        required
                        disabled={disabled}
                        label="权重"
                        slotProps={{ htmlInput: { min: 1, step: 1 } }}
                        type="number"
                        value={reward.weight}
                        onChange={(event) =>
                            updateReward(setForm, levelIndex, poolKey, rewardIndex, { weight: event.target.value })
                        }
                    />
                    {quantityEnabled ? (
                        <TextField
                            required
                            disabled={disabled}
                            label="数量"
                            slotProps={{ htmlInput: { min: 1, step: 1 } }}
                            type="number"
                            value={reward.quantity}
                            onChange={(event) =>
                                updateReward(setForm, levelIndex, poolKey, rewardIndex, {
                                    quantity: event.target.value,
                                })
                            }
                        />
                    ) : null}
                    <TextField
                        disabled={disabled}
                        label="展示名"
                        value={reward.displayName}
                        onChange={(event) =>
                            updateReward(setForm, levelIndex, poolKey, rewardIndex, { displayName: event.target.value })
                        }
                    />
                    <UploadField
                        density="compact"
                        disabled={disabled}
                        kind="image"
                        label="奖励图标"
                        value={reward.iconUrl}
                        onChange={(value) =>
                            updateReward(setForm, levelIndex, poolKey, rewardIndex, { iconUrl: value })
                        }
                    />
                    <Tooltip arrow title="删除奖项">
                        <span>
                            <IconButton
                                disabled={disabled}
                                label="删除奖项"
                                tone="danger"
                                type="button"
                                onClick={() => removeReward(setForm, levelIndex, poolKey, rewardIndex)}
                            >
                                <DeleteOutlineOutlined fontSize="small" />
                            </IconButton>
                        </span>
                    </Tooltip>
                </div>
            ))}
        </div>
    );
}

function FuelRuleEditor({ disabled, form, setForm }) {
    return (
        <div className={styles.fuelRuleEditor}>
            <div className={styles.fuelRuleToolbar}>
                <span className={styles.meta}>未命中特殊规则的礼物按基础燃料来源计算</span>
                <Button
                    disabled={disabled}
                    startIcon={<AddOutlined fontSize="small" />}
                    type="button"
                    onClick={() => addFuelRule(setForm)}
                >
                    添加规则
                </Button>
            </div>
            {form.giftFuelRules.length ? (
                <div className={styles.fuelRuleTable}>
                    <div className={styles.fuelRuleTableHead}>
                        <span>礼物 ID</span>
                        <span>礼物类型</span>
                        <span>倍率 ppm</span>
                        <span>固定燃料</span>
                        <span>排除</span>
                        <span />
                    </div>
                    {form.giftFuelRules.map((rule, index) => (
                        <div className={styles.fuelRuleTableRow} key={rule.ruleId || index}>
                            <TextField
                                disabled={disabled}
                                label="礼物 ID"
                                value={rule.giftId}
                                onChange={(event) => updateFuelRule(setForm, index, { giftId: event.target.value })}
                            />
                            <TextField
                                disabled={disabled}
                                label="礼物类型"
                                value={rule.giftTypeCode}
                                onChange={(event) =>
                                    updateFuelRule(setForm, index, { giftTypeCode: event.target.value })
                                }
                            />
                            <TextField
                                disabled={disabled}
                                label="倍率 ppm"
                                slotProps={{ htmlInput: { min: 0, step: 1 } }}
                                type="number"
                                value={rule.multiplierPpm}
                                onChange={(event) =>
                                    updateFuelRule(setForm, index, { multiplierPpm: event.target.value })
                                }
                            />
                            <TextField
                                disabled={disabled}
                                label="固定燃料"
                                slotProps={{ htmlInput: { min: 0, step: 1 } }}
                                type="number"
                                value={rule.fixedFuel}
                                onChange={(event) => updateFuelRule(setForm, index, { fixedFuel: event.target.value })}
                            />
                            <SwitchField
                                checked={rule.excluded}
                                disabled={disabled}
                                label="排除"
                                onChange={(event) => updateFuelRule(setForm, index, { excluded: event.target.checked })}
                            />
                            <Tooltip arrow title="删除规则">
                                <span>
                                    <IconButton
                                        disabled={disabled}
                                        label="删除规则"
                                        tone="danger"
                                        type="button"
                                        onClick={() => removeFuelRule(setForm, index)}
                                    >
                                        <DeleteOutlineOutlined fontSize="small" />
                                    </IconButton>
                                </span>
                            </Tooltip>
                        </div>
                    ))}
                </div>
            ) : (
                <div className={styles.emptyState}>未配置礼物特殊规则</div>
            )}
        </div>
    );
}

function SelectField({ disabled, label, onChange, options, value }) {
    return (
        <TextField
            select
            disabled={disabled}
            label={label}
            value={value}
            onChange={(event) => onChange(event.target.value)}
        >
            {options.map(([optionValue, optionLabel]) => (
                <MenuItem key={optionValue} value={optionValue}>
                    {optionLabel}
                </MenuItem>
            ))}
        </TextField>
    );
}

function SwitchField({ checked, disabled, label, onChange }) {
    return (
        <div className={styles.switchField}>
            <span>{label}</span>
            <AdminSwitch
                checked={checked}
                checkedLabel="开启"
                disabled={disabled}
                label={label}
                uncheckedLabel="关闭"
                onChange={onChange}
            />
        </div>
    );
}

function updateRoot(setForm, key, value) {
    setForm((current) => ({ ...current, [key]: value }));
}

function updateLevel(setForm, levelIndex, patch) {
    setForm((current) => ({
        ...current,
        levels: current.levels.map((level, index) => (index === levelIndex ? { ...level, ...patch } : level)),
    }));
}

function addReward(setForm, levelIndex, poolKey) {
    setForm((current) => ({
        ...current,
        levels: current.levels.map((level, index) =>
            index === levelIndex
                ? {
                      ...level,
                      [poolKey]: [
                          ...(level[poolKey] || []),
                          {
                              displayName: "",
                              iconUrl: "",
                              quantity: "1",
                              resourceGroupId: "",
                              rewardItemId: `level_${level.level}_${poolKey}_${Date.now()}`,
                              weight: "100",
                          },
                      ],
                  }
                : level,
        ),
    }));
}

function updateReward(setForm, levelIndex, poolKey, rewardIndex, patch) {
    setForm((current) => ({
        ...current,
        levels: current.levels.map((level, index) =>
            index === levelIndex
                ? {
                      ...level,
                      [poolKey]: (level[poolKey] || []).map((reward, itemIndex) =>
                          itemIndex === rewardIndex ? { ...reward, ...patch } : reward,
                      ),
                  }
                : level,
        ),
    }));
}

function removeReward(setForm, levelIndex, poolKey, rewardIndex) {
    setForm((current) => ({
        ...current,
        levels: current.levels.map((level, index) =>
            index === levelIndex
                ? { ...level, [poolKey]: (level[poolKey] || []).filter((_, itemIndex) => itemIndex !== rewardIndex) }
                : level,
        ),
    }));
}

function addFuelRule(setForm) {
    setForm((current) => ({
        ...current,
        giftFuelRules: [
            ...current.giftFuelRules,
            {
                excluded: false,
                fixedFuel: "0",
                giftId: "",
                giftTypeCode: "",
                multiplierPpm: "1000000",
                ruleId: `gift_fuel_rule_${Date.now()}`,
            },
        ],
    }));
}

function updateFuelRule(setForm, index, patch) {
    setForm((current) => ({
        ...current,
        giftFuelRules: current.giftFuelRules.map((rule, itemIndex) =>
            itemIndex === index ? { ...rule, ...patch } : rule,
        ),
    }));
}

function removeFuelRule(setForm, index) {
    setForm((current) => ({
        ...current,
        giftFuelRules: current.giftFuelRules.filter((_, itemIndex) => itemIndex !== index),
    }));
}

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