import ContentCopyOutlined from "@mui/icons-material/ContentCopyOutlined";
import Dialog from "@mui/material/Dialog";
import DialogActions from "@mui/material/DialogActions";
import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle";
import TextField from "@mui/material/TextField";
import { Button } from "@/shared/ui/Button.jsx";
import styles from "@/features/activity-templates/activity-templates.module.css";

export function ActivityTemplateCloneDialog({ form, onChange, onClose, onSubmit, open, saving, source }) {
    const validCode = /^[a-z][a-z0-9_-]{2,63}$/.test(form.templateCode);
    const valid = validCode && Boolean(form.name.trim());
    return (
        <Dialog fullWidth maxWidth="sm" open={open} onClose={saving ? undefined : onClose}>
            <form onSubmit={onSubmit}>
                <DialogTitle>复制活动模版</DialogTitle>
                <DialogContent className={styles.cloneDialogContent}>
                    <div className={styles.cloneSource}>
                        <strong>{source?.name || "-"}</strong>
                        <span>
                            {source?.templateCode || source?.templateId || "-"} ·{" "}
                            {form.sourceVersion ? `版本 v${form.sourceVersion}` : "当前编辑态"}
                        </span>
                    </div>
                    <TextField
                        autoFocus
                        error={Boolean(form.templateCode) && !validCode}
                        helperText={Boolean(form.templateCode) && !validCode ? "长度 3-64，以小写字母开头" : " "}
                        label="新模版编码"
                        required
                        value={form.templateCode}
                        onChange={(event) => onChange({ templateCode: normalizeCode(event.target.value) })}
                    />
                    <TextField
                        label="新内部名称"
                        required
                        value={form.name}
                        onChange={(event) => onChange({ name: event.target.value })}
                    />
                </DialogContent>
                <DialogActions>
                    <Button disabled={saving} onClick={onClose}>
                        取消
                    </Button>
                    <Button
                        disabled={saving || !valid}
                        startIcon={<ContentCopyOutlined fontSize="small" />}
                        type="submit"
                        variant="primary"
                    >
                        复制为草稿
                    </Button>
                </DialogActions>
            </form>
        </Dialog>
    );
}

function normalizeCode(value) {
    return String(value || "")
        .toLowerCase()
        .replace(/[^a-z0-9_-]/g, "");
}
