import AddOutlined from "@mui/icons-material/AddOutlined";
import SaveOutlined from "@mui/icons-material/SaveOutlined";
import Drawer from "@mui/material/Drawer";
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 { RewardTierEditorTable } from "@/shared/ui/RewardTierEditorTable.jsx";
import styles from "@/features/invite-activity-reward/invite-activity-reward.module.css";

const rewardTypeOptions = [
    ["recharge", "累计充值"],
    ["valid_invite", "Valid Users"],
];

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

    const addTier = () => {
        setForm((current) => ({
            ...current,
            tiers: [
                ...(current.tiers || []),
                {
                    tierId: 0,
                    rewardType: "recharge",
                    tierCode: `invite_reward_${Date.now()}_${(current.tiers || []).length + 1}`,
                    tierName: "",
                    thresholdCoinAmount: "",
                    thresholdValidInviteCount: "",
                    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="form-drawer__section-title">每邀请一人奖励</div>
                        <div className={styles.inlineFields}>
                            <TextField
                                disabled={disabled}
                                inputProps={{ min: 0, step: 1 }}
                                label="邀请人获得金币"
                                placeholder="0"
                                type="number"
                                value={form.perInviteInviterRewardCoinAmount || ""}
                                onChange={(event) =>
                                    setForm((current) => ({
                                        ...current,
                                        perInviteInviterRewardCoinAmount: event.target.value,
                                    }))
                                }
                            />
                            <TextField
                                disabled={disabled}
                                inputProps={{ min: 0, step: 1 }}
                                label="被邀请人获得金币"
                                placeholder="0"
                                type="number"
                                value={form.perInviteInviteeRewardCoinAmount || ""}
                                onChange={(event) =>
                                    setForm((current) => ({
                                        ...current,
                                        perInviteInviteeRewardCoinAmount: event.target.value,
                                    }))
                                }
                            />
                        </div>
                    </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: "rewardType",
                                    label: "类型",
                                    render: (tier, index) => (
                                        <TextField
                                            select
                                            disabled={disabled}
                                            value={tier.rewardType || "recharge"}
                                            onChange={(event) => updateTier(index, { rewardType: event.target.value })}
                                        >
                                            {rewardTypeOptions.map(([value, label]) => (
                                                <MenuItem key={value} value={value}>
                                                    {label}
                                                </MenuItem>
                                            ))}
                                        </TextField>
                                    ),
                                },
                                {
                                    key: "threshold",
                                    label: "门槛",
                                    render: (tier, index) => {
                                        const isRecharge = (tier.rewardType || "recharge") === "recharge";
                                        return (
                                            <TextField
                                                disabled={disabled}
                                                inputProps={{ min: 1, step: 1 }}
                                                placeholder={isRecharge ? "80000" : "1"}
                                                type="number"
                                                value={
                                                    isRecharge
                                                        ? tier.thresholdCoinAmount
                                                        : tier.thresholdValidInviteCount
                                                }
                                                onChange={(event) =>
                                                    updateTier(
                                                        index,
                                                        isRecharge
                                                            ? { thresholdCoinAmount: event.target.value }
                                                            : { thresholdValidInviteCount: event.target.value },
                                                    )
                                                }
                                            />
                                        );
                                    },
                                },
                                {
                                    key: "rewardCoinAmount",
                                    label: "奖励金币",
                                    render: (tier, index) => (
                                        <TextField
                                            disabled={disabled}
                                            inputProps={{ min: 1, step: 1 }}
                                            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(130px, 0.7fr) minmax(150px, 0.8fr) minmax(150px, 0.8fr) 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>
    );
}
