import MenuItem from "@mui/material/MenuItem";
import TextField from "@mui/material/TextField";
import { useState } from "react";
import { AdapterConfigFields } from "@/features/games/components/AdapterConfigFields.jsx";
import {
    adapterDefinition,
    adapterSecretState,
    adapterTypeOptions,
    migrateAdapterConfigJson,
    readAdapterConfig,
} from "@/features/games/adapterConfigModel.js";
import {
    AdminFormDialog,
    AdminFormFieldGrid,
    AdminFormSection,
    AdminFormSwitchField,
} from "@/shared/ui/AdminFormDialog.jsx";
import styles from "@/features/games/components/PlatformFormDialog.module.css";

export function PlatformFormDialog({ form, loading, mode, open, page, onClose, onSubmit }) {
    const [assetsUploading, setAssetsUploading] = useState(false);
    const definition = adapterDefinition(form.adapterType);
    const configValid = Boolean(readAdapterConfig(form.adapterConfigJson));
    const disabled = !page.abilities.canUpdate;
    const fixedAdapterType = adapterTypeOptions.find(
        ([value]) => adapterDefinition(value).fixedPlatformCode === form.platformCode.trim(),
    )?.[0];
    const { configuredSecretUsable, required: secretRequired } = adapterSecretState(form, mode === "edit");

    const submitForm = (event) => {
        if (assetsUploading) {
            // 禁用按钮之外再拦截 Enter 隐式提交，避免把上传前的旧 URL 写入平台配置。
            event.preventDefault();
            return;
        }
        onSubmit(event);
    };

    const changeAdapter = (adapterType) => {
        const previousDefinition = adapterDefinition(form.adapterType);
        const nextDefinition = adapterDefinition(adapterType);
        const adapterDrafts = {
            ...(form.adapterDrafts || {}),
            [form.adapterType]: {
                adapterConfigJson: form.adapterConfigJson,
                apiBaseUrl: form.apiBaseUrl,
                callbackIpWhitelistText: form.callbackIpWhitelistText,
            },
        };
        const savedDraft = adapterDrafts[adapterType];
        const next = {
            ...form,
            adapterType,
            adapterDrafts,
            // 不允许把上一厂商刚输入的签名密钥带进新协议；编辑迁移时下方会强制重新录入。
            callbackSecret: "",
            // 每个厂商保留独立草稿，切回时恢复；首次切入才从公共字段和游戏目录生成兼容配置。
            adapterConfigJson:
                savedDraft?.adapterConfigJson ??
                migrateAdapterConfigJson(form.adapterConfigJson, form.adapterType, adapterType),
            apiBaseUrl: savedDraft?.apiBaseUrl ?? "",
            callbackIpWhitelistText: savedDraft?.callbackIpWhitelistText ?? "",
        };
        if (mode === "create" && nextDefinition.fixedPlatformCode) {
            const canReplaceName =
                !form.platformName.trim() || form.platformName.trim() === previousDefinition.fixedPlatformName;
            // ZGame/AMG 的回调按固定 platformCode 查启动会话；这里必须锁定，不能让可保存但无法结算的配置进入库。
            next.platformCode = nextDefinition.fixedPlatformCode;
            if (canReplaceName) {
                next.platformName = nextDefinition.fixedPlatformName;
            }
        } else if (
            mode === "create" &&
            previousDefinition.fixedPlatformCode &&
            form.platformCode.trim() === previousDefinition.fixedPlatformCode
        ) {
            next.platformCode = "";
            if (form.platformName.trim() === previousDefinition.fixedPlatformName) {
                next.platformName = "";
            }
        }
        page.setPlatformForm(next);
    };

    return (
        <AdminFormDialog
            disabled={disabled}
            loading={loading}
            open={open}
            size="large"
            submitDisabled={disabled || loading || assetsUploading || !configValid}
            submitLabel={mode === "edit" ? "保存平台" : "创建平台"}
            title={mode === "edit" ? "编辑平台" : "添加平台"}
            onClose={onClose}
            onSubmit={submitForm}
        >
            <AdminFormSection title="平台信息">
                <AdminFormFieldGrid columns="repeat(4, minmax(0, 1fr))">
                    <TextField
                        disabled={disabled || mode === "edit" || Boolean(definition.fixedPlatformCode)}
                        helperText={definition.fixedPlatformCode ? "协议固定 Code" : undefined}
                        label="平台 Code"
                        required
                        value={form.platformCode}
                        onChange={(event) => page.setPlatformForm({ ...form, platformCode: event.target.value })}
                    />
                    <TextField
                        disabled={disabled}
                        label="平台名称"
                        required
                        value={form.platformName}
                        onChange={(event) => page.setPlatformForm({ ...form, platformName: event.target.value })}
                    />
                    <AdminFormSwitchField
                        checked={form.status === "active"}
                        checkedLabel="启用"
                        disabled={disabled}
                        label="游戏平台启用状态"
                        uncheckedLabel="维护"
                        onChange={(checked) =>
                            page.setPlatformForm({
                                ...form,
                                status: checked ? "active" : form.status === "disabled" ? "disabled" : "maintenance",
                            })
                        }
                    />
                    <TextField
                        disabled={disabled}
                        label="排序"
                        type="number"
                        value={form.sortOrder}
                        onChange={(event) => page.setPlatformForm({ ...form, sortOrder: event.target.value })}
                    />
                </AdminFormFieldGrid>
            </AdminFormSection>
            <AdminFormSection title="接入与回调">
                <AdminFormFieldGrid columns="repeat(2, minmax(0, 1fr))">
                    <TextField
                        // 上传结果归属当前厂商目录；上传结束前不允许切换适配器，避免结果落到另一份协议草稿。
                        disabled={disabled || assetsUploading || (mode === "edit" && Boolean(fixedAdapterType))}
                        helperText={mode === "edit" && fixedAdapterType ? "协议固定适配器" : undefined}
                        label="适配器"
                        select
                        value={form.adapterType}
                        onChange={(event) => changeAdapter(event.target.value)}
                    >
                        {adapterTypeOptions.map(([value, label]) => {
                            const optionDefinition = adapterDefinition(value);
                            const fixedCodeMismatch =
                                mode === "edit" &&
                                optionDefinition.fixedPlatformCode &&
                                optionDefinition.fixedPlatformCode !== form.platformCode.trim();
                            return (
                                <MenuItem disabled={Boolean(fixedCodeMismatch)} key={value} value={value}>
                                    {label}
                                </MenuItem>
                            );
                        })}
                    </TextField>
                    {definition.apiUrl !== false ? (
                        <TextField
                            disabled={disabled}
                            label={definition.apiUrlLabel || "默认 H5 / API URL"}
                            required={definition.apiUrlRequired}
                            value={form.apiBaseUrl}
                            onChange={(event) => page.setPlatformForm({ ...form, apiBaseUrl: event.target.value })}
                        />
                    ) : null}
                    <SecretField
                        configured={configuredSecretUsable}
                        disabled={disabled}
                        label={definition.callbackSecretLabel || "回调密钥"}
                        placeholder={definition.callbackSecretPlaceholder}
                        required={secretRequired}
                        value={form.callbackSecret}
                        onChange={(callbackSecret) => page.setPlatformForm({ ...form, callbackSecret })}
                    />
                    {definition.ipWhitelist ? (
                        <TextField
                            className={styles.ipWhitelist}
                            disabled={disabled}
                            label="回调 IP 白名单（每行一个 IP / CIDR）"
                            maxRows={3}
                            minRows={1}
                            multiline
                            value={form.callbackIpWhitelistText}
                            onChange={(event) =>
                                page.setPlatformForm({ ...form, callbackIpWhitelistText: event.target.value })
                            }
                        />
                    ) : null}
                </AdminFormFieldGrid>
            </AdminFormSection>
            <AdminFormSection title={`${definition.label} 参数`}>
                <AdapterConfigFields
                    adapterType={form.adapterType}
                    disabled={disabled}
                    // open 变化时立即重挂载，关闭过渡期间也会作废旧上传结果，不能回写下一次打开的表单。
                    key={open ? "active-platform-form" : "inactive-platform-form"}
                    uploadDisabled={!page.abilities.canUpload}
                    value={form.adapterConfigJson}
                    onChange={(adapterConfigJson) =>
                        page.setPlatformForm((current) => ({ ...current, adapterConfigJson }))
                    }
                    onUploadingChange={setAssetsUploading}
                />
            </AdminFormSection>
        </AdminFormDialog>
    );
}

function SecretField({ configured, disabled, label, placeholder, required, value, onChange }) {
    const whitespaceOnly = required && Boolean(value) && !value.trim();
    return (
        <TextField
            autoComplete="off"
            disabled={disabled}
            error={whitespaceOnly}
            helperText={whitespaceOnly ? "密钥不能只包含空格" : configured && !value ? "已配置，留空不修改" : undefined}
            label={label}
            placeholder={placeholder}
            required={required}
            type="text"
            value={value}
            onChange={(event) => onChange(event.target.value)}
        />
    );
}
