import AddOutlined from "@mui/icons-material/AddOutlined";
import SaveOutlined from "@mui/icons-material/SaveOutlined";
import Drawer from "@mui/material/Drawer";
import TextField from "@mui/material/TextField";
import { AdminSwitch } from "@/shared/ui/AdminSwitch.jsx";
import { Button } from "@/shared/ui/Button.jsx";
import { RewardTierEditorTable } from "@/shared/ui/RewardTierEditorTable.jsx";
import styles from "@/features/room-turnover-reward/room-turnover-reward.module.css";

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

    const addTier = () => {
        setForm((current) => ({
            ...current,
            tiers: [
                ...(current.tiers || []),
                {
                    tierId: 0,
                    tierCode: `room_turnover_${Date.now()}_${(current.tiers || []).length + 1}`,
                    tierName: "",
                    thresholdCoinSpent: "",
                    rewardCoinAmount: "",
                    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 form-drawer--activity-config" onSubmit={onSubmit}>
                <h2>房间流水奖励配置</h2>
                <div className="form-drawer__content">
                    <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>
                        <RewardTierEditorTable
                            columns={[
                                {
                                    key: "tier",
                                    label: "档位",
                                    render: (_tier, index) => (
                                        <span className="reward-tier-editor-table__index">档位 {index + 1}</span>
                                    ),
                                },
                                {
                                    key: "thresholdCoinSpent",
                                    label: "流水阈值",
                                    render: (tier, index) => (
                                        <TextField
                                            disabled={disabled}
                                            inputProps={{ "aria-label": "流水阈值", min: 1 }}
                                            placeholder="100000"
                                            type="number"
                                            value={tier.thresholdCoinSpent}
                                            onChange={(event) =>
                                                updateTier(index, { thresholdCoinSpent: event.target.value })
                                            }
                                        />
                                    ),
                                },
                                {
                                    key: "rewardCoinAmount",
                                    label: "奖励金币",
                                    render: (tier, index) => (
                                        <TextField
                                            disabled={disabled}
                                            inputProps={{ "aria-label": "奖励金币", min: 0 }}
                                            placeholder="1000"
                                            type="number"
                                            value={tier.rewardCoinAmount}
                                            onChange={(event) =>
                                                updateTier(index, { rewardCoinAmount: event.target.value })
                                            }
                                        />
                                    ),
                                },
                                {
                                    key: "status",
                                    label: "状态",
                                    render: (tier, index) => (
                                        <AdminSwitch
                                            checked={tier.status !== "inactive"}
                                            checkedLabel="启用"
                                            disabled={disabled}
                                            label={`档位 ${index + 1} 状态`}
                                            uncheckedLabel="停用"
                                            onChange={(event) =>
                                                updateTier(index, { status: event.target.checked ? "active" : "inactive" })
                                            }
                                        />
                                    ),
                                },
                            ]}
                            disabled={disabled}
                            emptyText="暂无档位"
                            gridTemplateColumns="72px minmax(160px, 1fr) minmax(160px, 1fr) 120px 52px"
                            rows={form.tiers || []}
                            onRemoveTier={removeTier}
                        />
                    </section>
                </div>
                <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>
    );
}
