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 { ResourceGroupSelectField } from "@/shared/ui/ResourceGroupSelectDrawer.jsx";
import styles from "@/features/first-recharge-reward/first-recharge-reward.module.css";

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: `first_recharge_${Date.now()}_${(current.tiers || []).length + 1}`,
                    tierName: "",
                    usdAmount: "",
                    googleProductId: "",
                    discountPercent: "70",
                    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 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: "usdAmount",
                                    label: "USD",
                                    render: (tier, index) => (
                                        <TextField
                                            disabled={disabled}
                                            inputProps={{ "aria-label": "美元档位", min: 0.01, step: 0.01 }}
                                            placeholder="0.99"
                                            type="number"
                                            value={tier.usdAmount}
                                            onChange={(event) => updateTier(index, { usdAmount: event.target.value })}
                                        />
                                    ),
                                },
                                {
                                    key: "googleProductId",
                                    label: "Google 商品 ID",
                                    render: (tier, index) => (
                                        <TextField
                                            disabled={disabled}
                                            inputProps={{ "aria-label": "Google 商品 ID" }}
                                            placeholder="first_recharge_google_099"
                                            value={tier.googleProductId}
                                            onChange={(event) =>
                                                updateTier(index, { googleProductId: event.target.value })
                                            }
                                        />
                                    ),
                                },
                                {
                                    key: "resourceGroupId",
                                    label: "奖励资源组",
                                    render: (tier, index) => (
                                        <ResourceGroupSelectField
                                            disabled={disabled}
                                            drawerTitle="选择首充礼包资源组"
                                            groups={resourceGroups}
                                            label="奖励资源组"
                                            value={tier.resourceGroupId}
                                            onChange={(value) => updateTier(index, { resourceGroupId: value })}
                                        />
                                    ),
                                },
                                {
                                    key: "discountPercent",
                                    label: "优惠%",
                                    render: (tier, index) => (
                                        <TextField
                                            disabled={disabled}
                                            inputProps={{ "aria-label": "优惠百分比", min: 0, max: 100, step: 1 }}
                                            type="number"
                                            value={tier.discountPercent}
                                            onChange={(event) =>
                                                updateTier(index, { discountPercent: 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(110px, 0.6fr) minmax(230px, 1.2fr) minmax(260px, 1.4fr) 92px 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>
    );
}
