import MenuItem from "@mui/material/MenuItem";
import TextField from "@mui/material/TextField";
import { AdminSwitch } from "@/shared/ui/AdminSwitch.jsx";
import { JsonEditorField } from "@/shared/ui/JsonEditorField.jsx";
import { MultiValueAutocomplete } from "@/shared/ui/MultiValueAutocomplete.jsx";
import { TimeRangeFilter } from "@/shared/ui/TimeRangeFilter.jsx";
import styles from "@/features/activity-templates/activity-templates.module.css";
import { parseDisplayConfig } from "@/features/activity-templates/model.js";

export function BasicSettingsSection({ disabled, form, loadingRegions, regionOptions, updateField }) {
    const regionLabels = Object.fromEntries(regionOptions.map((option) => [option.value, option.label]));
    return (
        <EditorSection title="基础与投放">
            <div className={styles.formGridThree}>
                <TextField
                    disabled={disabled || Boolean(form.templateId)}
                    label="模版编码"
                    required
                    value={form.templateCode}
                    onChange={(event) => updateField("templateCode", normalizeCode(event.target.value))}
                />
                <TextField
                    disabled={disabled}
                    label="内部名称"
                    required
                    value={form.name}
                    onChange={(event) => updateField("name", event.target.value)}
                />
                <TextField disabled label="活动类型" value="礼物挑战赛" />
            </div>
            <div className={styles.localizedGrid}>
                <TextField
                    disabled={disabled}
                    label="活动标题（英语）"
                    value={form.titleEn}
                    onChange={(event) => updateField("titleEn", event.target.value)}
                />
                <TextField
                    disabled={disabled}
                    dir="rtl"
                    label="活动标题（阿语）"
                    value={form.titleAr}
                    onChange={(event) => updateField("titleAr", event.target.value)}
                />
            </div>
            <div className={styles.settingRow}>
                <div className={styles.settingCopy}>
                    <strong>活动时间</strong>
                    <span>UTC 毫秒存储，结束时间不包含在活动周期内</span>
                </div>
                <TimeRangeFilter
                    className={styles.timeRangeField}
                    disabled={disabled}
                    label="活动时间"
                    value={form.timeRange}
                    onChange={(value) => updateField("timeRange", value)}
                />
            </div>
            <div className={styles.settingRow}>
                <div className={styles.settingCopy}>
                    <strong>投放全部区域</strong>
                    <span>开启后不再提交指定区域</span>
                </div>
                <AdminSwitch
                    checked={form.allRegions}
                    checkedLabel="全部"
                    disabled={disabled}
                    label="投放全部区域"
                    uncheckedLabel="指定"
                    onChange={(event) => {
                        updateField("allRegions", event.target.checked);
                        if (event.target.checked) updateField("regionIds", []);
                    }}
                />
            </div>
            {!form.allRegions ? (
                <MultiValueAutocomplete
                    disabled={disabled}
                    getOptionLabel={(value) => regionLabels[String(value)] || `区域 #${value}`}
                    label="指定投放区域"
                    labels={regionLabels}
                    loading={loadingRegions}
                    options={regionOptions.map((option) => option.value)}
                    value={form.regionIds}
                    onChange={(value) => updateField("regionIds", value)}
                />
            ) : null}
        </EditorSection>
    );
}

export function RulesSettingsSection({ disabled, form, updateField }) {
    return (
        <EditorSection title="规则文案">
            <div className={styles.rulesGrid}>
                <TextField
                    disabled={disabled}
                    label="活动规则（英语）"
                    minRows={14}
                    multiline
                    value={form.rulesEn}
                    onChange={(event) => updateField("rulesEn", event.target.value)}
                />
                <TextField
                    disabled={disabled}
                    dir="rtl"
                    label="活动规则（阿语）"
                    minRows={14}
                    multiline
                    value={form.rulesAr}
                    onChange={(event) => updateField("rulesAr", event.target.value)}
                />
            </div>
        </EditorSection>
    );
}

export function DisplayConfigSection({ disabled, form, updateField }) {
    const config = parseDisplayConfig(form.displayConfigJson);
    const updateConfig = (path, value) => {
        const next = structuredClone(config);
        let target = next;
        path.slice(0, -1).forEach((key) => {
            target[key] = target[key] && typeof target[key] === "object" ? target[key] : {};
            target = target[key];
        });
        target[path[path.length - 1]] = value;
        updateField("displayConfigJson", JSON.stringify(next, null, 2));
    };

    return (
        <EditorSection title="展示配置">
            <div className={styles.formGridThree}>
                <TextField
                    disabled={disabled}
                    label="默认页面"
                    select
                    value={config.default_tab === "leaderboard" ? "leaderboard" : "tasks"}
                    onChange={(event) => updateConfig(["default_tab"], event.target.value)}
                >
                    <MenuItem value="tasks">福利任务</MenuItem>
                    <MenuItem value="leaderboard">荣誉榜单</MenuItem>
                </TextField>
                <TextField
                    disabled={disabled}
                    label="榜单默认维度"
                    select
                    value={config.leaderboard?.default_board === "total" ? "total" : "daily"}
                    onChange={(event) => updateConfig(["leaderboard", "default_board"], event.target.value)}
                >
                    <MenuItem value="daily">日榜</MenuItem>
                    <MenuItem value="total">总榜</MenuItem>
                </TextField>
                <TextField
                    disabled={disabled}
                    label="榜单每页条数"
                    slotProps={{ htmlInput: { min: 10, max: 100 } }}
                    type="number"
                    value={config.leaderboard?.page_size ?? 20}
                    onChange={(event) => updateConfig(["leaderboard", "page_size"], Number(event.target.value))}
                />
                <TextField
                    disabled={disabled}
                    label="积分展示上限"
                    slotProps={{ htmlInput: { min: 1 } }}
                    type="number"
                    value={config.leaderboard?.score_display_cap ?? 999999999}
                    onChange={(event) => updateConfig(["leaderboard", "score_display_cap"], Number(event.target.value))}
                />
                <TextField
                    disabled={disabled}
                    label="未上榜文案"
                    value={config.leaderboard?.unranked_label ?? "100+"}
                    onChange={(event) => updateConfig(["leaderboard", "unranked_label"], event.target.value)}
                />
                <TextField
                    disabled={disabled}
                    label="礼物轮播间隔（毫秒）"
                    slotProps={{ htmlInput: { min: 1000 } }}
                    type="number"
                    value={config.gifts?.interval_ms ?? 3000}
                    onChange={(event) => updateConfig(["gifts", "interval_ms"], Number(event.target.value))}
                />
            </div>
            <div className={styles.settingRow}>
                <div className={styles.settingCopy}>
                    <strong>礼物自动轮播</strong>
                    <span>礼物超出客户端容器宽度时自动滚动</span>
                </div>
                <AdminSwitch
                    checked={config.gifts?.auto_scroll !== false}
                    checkedLabel="开启"
                    disabled={disabled}
                    label="礼物自动轮播"
                    uncheckedLabel="关闭"
                    onChange={(event) => updateConfig(["gifts", "auto_scroll"], event.target.checked)}
                />
            </div>
            <JsonEditorField
                disabled={disabled}
                label="display_config_json"
                minRows={12}
                required
                value={form.displayConfigJson}
                onChange={(value) => updateField("displayConfigJson", value)}
            />
        </EditorSection>
    );
}

export function EditorSection({ actions, children, title }) {
    return (
        <section className={styles.editorSection}>
            <header className={styles.editorSectionHeader}>
                <h3>{title}</h3>
                {actions ? <div>{actions}</div> : null}
            </header>
            <div className={styles.editorSectionBody}>{children}</div>
        </section>
    );
}

function normalizeCode(value) {
    return String(value || "")
        .toLowerCase()
        .replace(/[^a-z0-9_-]/g, "");
}
