import AddOutlined from "@mui/icons-material/AddOutlined";
import DeleteOutlineOutlined from "@mui/icons-material/DeleteOutlineOutlined";
import SaveOutlined from "@mui/icons-material/SaveOutlined";
import Drawer from "@mui/material/Drawer";
import IconButton from "@mui/material/IconButton";
import MenuItem from "@mui/material/MenuItem";
import TextField from "@mui/material/TextField";
import { AdminSwitch } from "@/shared/ui/AdminSwitch.jsx";
import { Button } from "@/shared/ui/Button.jsx";
import { ResourceGroupSelectField } from "@/shared/ui/ResourceGroupSelectDrawer.jsx";
import styles from "@/features/first-recharge-reward/first-recharge-reward.module.css";

const statusOptions = [
    ["active", "启用"],
    ["inactive", "停用"],
];

export function FirstRechargeRewardConfigDrawer({
    abilities,
    configLoading,
    configSaving,
    form,
    onClose,
    onSubmit,
    open,
    resourceGroups,
    setForm,
}) {
    const disabled = !abilities.canUpdate || configLoading || configSaving;

    const addTier = () => {
        setForm((current) => ({
            ...current,
            tiers: [
                ...(current.tiers || []),
                {
                    tierId: 0,
                    tierCode: "",
                    tierName: "",
                    minCoinAmount: "",
                    maxCoinAmount: "",
                    resourceGroupId: "",
                    status: "active",
                    sortOrder: String((current.tiers || []).length),
                },
            ],
        }));
    };

    const updateTier = (index, patch) => {
        setForm((current) => ({
            ...current,
            tiers: (current.tiers || []).map((tier, tierIndex) => (tierIndex === index ? { ...tier, ...patch } : tier)),
        }));
    };

    const removeTier = (index) => {
        setForm((current) => ({
            ...current,
            tiers: (current.tiers || []).filter((_, tierIndex) => tierIndex !== index),
        }));
    };

    return (
        <Drawer anchor="right" open={open} onClose={configSaving ? undefined : onClose}>
            <form className="form-drawer" onSubmit={onSubmit}>
                <h2>首冲奖励配置</h2>
                <section className="form-drawer__section">
                    <div className="form-drawer__section-title">发放状态</div>
                    <AdminSwitch
                        checked={form.enabled}
                        checkedLabel="开启"
                        disabled={disabled}
                        label="首冲奖励状态"
                        uncheckedLabel="关闭"
                        onChange={(event) => setForm((current) => ({ ...current, enabled: event.target.checked }))}
                    />
                </section>
                <section className="form-drawer__section">
                    <div className={styles.drawerSectionTitle}>
                        <span>奖励档位</span>
                        <Button
                            disabled={disabled}
                            startIcon={<AddOutlined fontSize="small" />}
                            type="button"
                            onClick={addTier}
                        >
                            添加档位
                        </Button>
                    </div>
                    <div className={styles.tierEditorList}>
                        {(form.tiers || []).map((tier, index) => (
                            <div className={styles.tierEditor} key={`${tier.tierId || "new"}-${index}`}>
                                <div className={styles.tierEditorHeader}>
                                    <span>档位 {index + 1}</span>
                                    <IconButton
                                        aria-label="删除档位"
                                        disabled={disabled}
                                        size="small"
                                        onClick={() => removeTier(index)}
                                    >
                                        <DeleteOutlineOutlined fontSize="small" />
                                    </IconButton>
                                </div>
                                <div className="form-drawer__grid">
                                    <TextField
                                        disabled={disabled}
                                        label="档位编码"
                                        value={tier.tierCode}
                                        onChange={(event) => updateTier(index, { tierCode: event.target.value })}
                                    />
                                    <TextField
                                        disabled={disabled}
                                        label="档位名称"
                                        value={tier.tierName}
                                        onChange={(event) => updateTier(index, { tierName: event.target.value })}
                                    />
                                    <TextField
                                        disabled={disabled}
                                        inputProps={{ min: 1 }}
                                        label="最小金币"
                                        type="number"
                                        value={tier.minCoinAmount}
                                        onChange={(event) => updateTier(index, { minCoinAmount: event.target.value })}
                                    />
                                    <TextField
                                        disabled={disabled}
                                        inputProps={{ min: 0 }}
                                        label="最大金币"
                                        placeholder="0 表示无上限"
                                        type="number"
                                        value={tier.maxCoinAmount}
                                        onChange={(event) => updateTier(index, { maxCoinAmount: event.target.value })}
                                    />
                                    <ResourceGroupSelectField
                                        disabled={disabled}
                                        drawerTitle="选择首冲奖励资源组"
                                        groups={resourceGroups}
                                        label="奖励资源组"
                                        value={tier.resourceGroupId}
                                        onChange={(value) => updateTier(index, { resourceGroupId: value })}
                                    />
                                    <TextField
                                        select
                                        disabled={disabled}
                                        label="状态"
                                        value={tier.status}
                                        onChange={(event) => updateTier(index, { status: event.target.value })}
                                    >
                                        {statusOptions.map(([value, label]) => (
                                            <MenuItem key={value} value={value}>
                                                {label}
                                            </MenuItem>
                                        ))}
                                    </TextField>
                                    <TextField
                                        disabled={disabled}
                                        inputProps={{ min: 0 }}
                                        label="排序"
                                        type="number"
                                        value={tier.sortOrder}
                                        onChange={(event) => updateTier(index, { sortOrder: event.target.value })}
                                    />
                                </div>
                            </div>
                        ))}
                        {!form.tiers?.length ? <div className={styles.emptyState}>暂无档位</div> : null}
                    </div>
                </section>
                <div className="form-drawer__actions">
                    <Button disabled={configSaving} type="button" onClick={onClose}>
                        取消
                    </Button>
                    <Button
                        disabled={disabled}
                        startIcon={<SaveOutlined fontSize="small" />}
                        type="submit"
                        variant="primary"
                    >
                        保存
                    </Button>
                </div>
            </form>
        </Drawer>
    );
}
