import Add from "@mui/icons-material/Add";
import DeleteOutlineOutlined from "@mui/icons-material/DeleteOutlineOutlined";
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 { IconButton } from "@/shared/ui/IconButton.jsx";
import { SideDrawer } from "@/shared/ui/SideDrawer.jsx";
import { TimeRangeFilter } from "@/shared/ui/TimeRangeFilter.jsx";
import styles from "@/features/host-agency-policy/host-agency-policy.module.css";

const settlementTriggerOptions = [
    ["automatic", "自动结算"],
    ["manual", "手动结算"],
];

export function TeamSalaryPolicyDrawer({ page }) {
    const saving = page.loadingAction === "team-policy-create" || page.loadingAction === "team-policy-update";
    const disabled = saving || (!page.editingPolicy ? !page.abilities.canTeamCreate : !page.abilities.canTeamUpdate);
    return (
        <SideDrawer
            actions={
                <>
                    <Button disabled={saving} onClick={page.closeDrawer}>
                        取消
                    </Button>
                    <Button disabled={disabled || page.loadingRegions} type="submit" variant="primary">
                        保存
                    </Button>
                </>
            }
            as="form"
            className={styles.policyDrawer}
            contentClassName={styles.drawerBody}
            open={page.drawerOpen}
            title={
                page.editingPolicy
                    ? `编辑${policyTitle(page.policyType)}政策`
                    : `新增${policyTitle(page.policyType)}政策`
            }
            width="wide"
            onClose={saving ? undefined : page.closeDrawer}
            onSubmit={page.submitPolicy}
        >
            <TeamPolicyBaseFields disabled={disabled} page={page} />
            <TeamPolicyLevelEditor disabled={disabled} page={page} />
        </SideDrawer>
    );
}

function TeamPolicyBaseFields({ disabled, page }) {
    const form = page.form;
    const setForm = (patch) => page.setForm((current) => ({ ...current, ...patch }));
    return (
        <section className={[styles.formSection, styles.baseSection].join(" ")}>
            <div className={styles.sectionHeader}>
                <h3>基础配置</h3>
            </div>
            <div className={styles.formGrid}>
                <TextField
                    required
                    className={styles.fieldWide}
                    disabled={disabled}
                    label="政策名称"
                    size="small"
                    value={form.name}
                    onChange={(event) => setForm({ name: event.target.value })}
                />
                <TextField
                    required
                    select
                    className={styles.fieldWide}
                    disabled={disabled || page.loadingRegions}
                    label="适用区域"
                    size="small"
                    value={form.regionId}
                    onChange={(event) => setForm({ regionId: event.target.value })}
                >
                    {page.regionOptions.map((region) => (
                        <MenuItem key={region.value} value={region.value}>
                            {region.label}
                        </MenuItem>
                    ))}
                </TextField>
                <TextField
                    required
                    select
                    className={styles.fieldCompact}
                    disabled={disabled}
                    label="触发方式"
                    size="small"
                    value={form.settlementTriggerMode}
                    onChange={(event) => setForm({ settlementTriggerMode: event.target.value })}
                >
                    {settlementTriggerOptions.map(([value, label]) => (
                        <MenuItem key={value} value={value}>
                            {label}
                        </MenuItem>
                    ))}
                </TextField>
                <TimeRangeFilter
                    className={styles.timeRangeField}
                    disabled={disabled}
                    label="生效时间"
                    value={{ endMs: form.effectiveTo, startMs: form.effectiveFrom }}
                    onChange={(range) => setForm({ effectiveFrom: range.startMs, effectiveTo: range.endMs })}
                />
                <div className={styles.enabledField}>
                    <span className={styles.toggleLabel}>政策状态</span>
                    <AdminSwitch
                        checked={form.enabled}
                        checkedLabel="启用"
                        disabled={disabled}
                        label="政策状态"
                        uncheckedLabel="停用"
                        onChange={(event) => setForm({ enabled: event.target.checked })}
                    />
                </div>
            </div>
        </section>
    );
}

function TeamPolicyLevelEditor({ disabled, page }) {
    return (
        <section className={[styles.formSection, styles.levelSection].join(" ")}>
            <div className={styles.sectionHeader}>
                <h3>等级配置</h3>
                <Button
                    className={styles.addLevelButton}
                    disabled={disabled}
                    startIcon={<Add fontSize="small" />}
                    onClick={page.addLevel}
                >
                    添加等级
                </Button>
            </div>
            <div className={styles.levelTable}>
                <div className={styles.teamLevelHeader}>
                    <span>等级</span>
                    <span>{thresholdLabel(page.policyType)}</span>
                    <span>比例%</span>
                    <span>{policyTitle(page.policyType)}美元</span>
                    <span>状态</span>
                    <span />
                </div>
                <div className={styles.levelList}>
                    {page.form.levels.map((level, index) => (
                        <div className={styles.teamLevelRow} key={`${level.level}-${index}`}>
                            <TextField
                                required
                                disabled={disabled}
                                size="small"
                                type="number"
                                value={level.level}
                                onChange={(event) =>
                                    page.updateLevel(index, {
                                        level: event.target.value,
                                        sortOrder: event.target.value,
                                    })
                                }
                            />
                            <TextField
                                required
                                disabled={disabled}
                                size="small"
                                value={level.thresholdUsd}
                                onChange={(event) => page.updateLevel(index, { thresholdUsd: event.target.value })}
                            />
                            <TextField
                                required
                                disabled={disabled}
                                size="small"
                                value={level.ratePercent}
                                onChange={(event) => page.updateLevel(index, { ratePercent: event.target.value })}
                            />
                            <TextField
                                required
                                disabled={disabled}
                                size="small"
                                value={level.salaryUsd}
                                onChange={(event) => page.updateLevel(index, { salaryUsd: event.target.value })}
                            />
                            <AdminSwitch
                                checked={level.status === "active"}
                                checkedLabel="启用"
                                disabled={disabled}
                                label={`等级 ${level.level || index + 1} 状态`}
                                uncheckedLabel="停用"
                                onChange={(event) =>
                                    page.updateLevel(index, { status: event.target.checked ? "active" : "disabled" })
                                }
                            />
                            <IconButton
                                disabled={disabled || page.form.levels.length <= 1}
                                label="删除等级"
                                sx={{ height: 34, minHeight: 34, width: 34 }}
                                onClick={() => page.removeLevel(index)}
                            >
                                <DeleteOutlineOutlined fontSize="small" />
                            </IconButton>
                        </div>
                    ))}
                </div>
            </div>
        </section>
    );
}

function policyTitle(policyType) {
    return policyType === "bd" ? "BD" : "Admin";
}

function thresholdLabel(policyType) {
    return policyType === "bd" ? "下属主播工资" : "BD工资";
}
