import CloseOutlined from "@mui/icons-material/CloseOutlined";
import PublishOutlined from "@mui/icons-material/PublishOutlined";
import SaveOutlined from "@mui/icons-material/SaveOutlined";
import StopCircleOutlined from "@mui/icons-material/StopCircleOutlined";
import Alert from "@mui/material/Alert";
import Drawer from "@mui/material/Drawer";
import { useEffect, useMemo, useState } from "react";
import { Button } from "@/shared/ui/Button.jsx";
import { IconButton } from "@/shared/ui/IconButton.jsx";
import { PageSkeleton } from "@/shared/ui/PageSkeleton.jsx";
import styles from "@/features/activity-templates/activity-templates.module.css";
import { EDITOR_SECTIONS } from "@/features/activity-templates/constants.js";
import { ActivityTemplateStatusBadge } from "@/features/activity-templates/components/ActivityTemplateStatusBadge.jsx";
import { ActivityPhonePreview } from "@/features/activity-templates/components/ActivityPhonePreview.jsx";
import {
    BasicSettingsSection,
    DisplayConfigSection,
    RulesSettingsSection,
} from "@/features/activity-templates/components/BasicAndContentSections.jsx";
import {
    GiftSettingsSection,
    TaskSettingsSection,
} from "@/features/activity-templates/components/GiftTaskSections.jsx";
import {
    AssetsSettingsSection,
    RankingSettingsSection,
} from "@/features/activity-templates/components/RankingAssetsSections.jsx";

export function ActivityTemplateEditorDrawer({
    abilities,
    dirty,
    form,
    gifts,
    giftsLoading,
    loading,
    loadingRegions,
    mode,
    onClose,
    onDisable,
    onPublish,
    onReload,
    onSubmit,
    open,
    regionOptions,
    resourceGroups,
    saving,
    setForm,
    validationIssues,
}) {
    const [activeSection, setActiveSection] = useState("basic");

    useEffect(() => {
        if (open) setActiveSection("basic");
    }, [open, mode, form.templateId]);

    const isPublished = form.status === "published";
    const immutableMode = mode === "view" || mode === "version";
    const allowedToEdit = mode === "create" ? abilities.canCreate : mode === "edit" ? abilities.canUpdate : false;
    const readOnly = immutableMode || isPublished || !allowedToEdit;
    const canSave = !readOnly && !loading && !saving;
    const hasRevisionConflict = validationIssues?.some((issue) => issue.code === "revision_conflict");
    const sectionCounts = useMemo(
        () => ({
            assets: form.assets.filter((asset) => asset.url).length,
            gifts: form.gifts.length,
            ranking: form.dailyRankRewards.length + form.totalRankRewards.length,
            tasks: form.tasks.length,
        }),
        [form.assets, form.dailyRankRewards.length, form.gifts.length, form.tasks.length, form.totalRankRewards.length],
    );

    const updateField = (key, value) => setForm((current) => ({ ...current, [key]: value }));

    return (
        <Drawer
            anchor="right"
            open={open}
            slotProps={{ backdrop: { sx: { backgroundColor: "var(--overlay-scrim)" } } }}
            onClose={saving ? undefined : onClose}
        >
            <form
                className={["form-drawer", "form-drawer--workspace", styles.editorDrawer].join(" ")}
                onSubmit={onSubmit}
            >
                <header className={["form-drawer__header", styles.editorHeader].join(" ")}>
                    <div className="form-drawer__heading">
                        <div className={styles.editorTitleLine}>
                            <h2>{drawerTitle(mode, form)}</h2>
                            {form.templateId ? (
                                <ActivityTemplateStatusBadge status={form.lifecycleStatus || form.status} />
                            ) : null}
                            {dirty ? <span className={styles.dirtyBadge}>未保存</span> : null}
                        </div>
                        <span>
                            {form.templateId
                                ? `${form.templateCode || form.templateId} · revision ${form.revision}`
                                : "新建礼物挑战赛活动模版"}
                        </span>
                    </div>
                    <IconButton disabled={saving} label="关闭" onClick={onClose}>
                        <CloseOutlined fontSize="small" />
                    </IconButton>
                </header>

                <nav aria-label="活动模版配置分区" className={["form-drawer__tabs", styles.editorTabs].join(" ")}>
                    {EDITOR_SECTIONS.map((section) => (
                        <button
                            aria-current={section.key === activeSection ? "page" : undefined}
                            className={section.key === activeSection ? "is-active" : ""}
                            key={section.key}
                            type="button"
                            onClick={() => setActiveSection(section.key)}
                        >
                            <span>{section.label}</span>
                            {sectionCounts[section.key] !== undefined ? (
                                <small>{sectionCounts[section.key]}</small>
                            ) : null}
                        </button>
                    ))}
                </nav>

                <div className={["form-drawer__workspace", styles.editorWorkspace].join(" ")}>
                    {loading ? (
                        <div className={styles.editorLoading}>
                            <PageSkeleton />
                        </div>
                    ) : (
                        <>
                            <main className={styles.editorMain}>
                                {isPublished ? (
                                    <Alert
                                        action={
                                            mode !== "version" && onDisable && abilities.canPublish ? (
                                                <Button disabled={saving} onClick={onDisable}>
                                                    停用
                                                </Button>
                                            ) : null
                                        }
                                        severity="info"
                                    >
                                        {mode === "version"
                                            ? "发布版本为不可变快照。"
                                            : "已发布版本只读，停用后可编辑并重新发布。"}
                                    </Alert>
                                ) : null}
                                {validationIssues?.length ? (
                                    <Alert
                                        action={
                                            hasRevisionConflict && form.templateId && onReload ? (
                                                <Button disabled={saving} onClick={onReload}>
                                                    重新加载
                                                </Button>
                                            ) : null
                                        }
                                        severity="error"
                                    >
                                        <div className={styles.validationList}>
                                            {validationIssues.slice(0, 8).map((issue, index) => (
                                                <span key={`${issue.field || "form"}-${issue.code || index}-${index}`}>
                                                    {issue.field ? `${issue.field}：` : ""}
                                                    {issue.message}
                                                </span>
                                            ))}
                                        </div>
                                    </Alert>
                                ) : null}
                                {activeSection === "basic" ? (
                                    <BasicSettingsSection
                                        disabled={readOnly}
                                        form={form}
                                        loadingRegions={loadingRegions}
                                        regionOptions={regionOptions}
                                        updateField={updateField}
                                    />
                                ) : null}
                                {activeSection === "gifts" ? (
                                    <GiftSettingsSection
                                        disabled={readOnly}
                                        form={form}
                                        gifts={gifts}
                                        giftsLoading={giftsLoading}
                                        updateField={updateField}
                                    />
                                ) : null}
                                {activeSection === "tasks" ? (
                                    <TaskSettingsSection
                                        disabled={readOnly}
                                        form={form}
                                        resourceGroups={resourceGroups}
                                        updateField={updateField}
                                    />
                                ) : null}
                                {activeSection === "ranking" ? (
                                    <RankingSettingsSection
                                        disabled={readOnly}
                                        form={form}
                                        resourceGroups={resourceGroups}
                                        updateField={updateField}
                                    />
                                ) : null}
                                {activeSection === "rules" ? (
                                    <RulesSettingsSection disabled={readOnly} form={form} updateField={updateField} />
                                ) : null}
                                {activeSection === "assets" ? (
                                    <AssetsSettingsSection disabled={readOnly} form={form} updateField={updateField} />
                                ) : null}
                                {activeSection === "display" ? (
                                    <DisplayConfigSection disabled={readOnly} form={form} updateField={updateField} />
                                ) : null}
                            </main>
                            <ActivityPhonePreview form={form} resourceGroups={resourceGroups} />
                        </>
                    )}
                </div>

                <div className={["form-drawer__actions", styles.editorActions].join(" ")}>
                    <Button disabled={saving} onClick={onClose}>
                        {readOnly ? "关闭" : "取消"}
                    </Button>
                    {canSave ? (
                        <Button disabled={saving} startIcon={<SaveOutlined fontSize="small" />} type="submit">
                            保存草稿
                        </Button>
                    ) : null}
                    {canSave && abilities.canPublish ? (
                        <Button
                            disabled={saving}
                            startIcon={<PublishOutlined fontSize="small" />}
                            variant="primary"
                            onClick={onPublish}
                        >
                            保存并发布
                        </Button>
                    ) : null}
                    {isPublished && !immutableMode && abilities.canPublish ? (
                        <Button
                            disabled={saving}
                            startIcon={<StopCircleOutlined fontSize="small" />}
                            variant="danger"
                            onClick={onDisable}
                        >
                            停用模版
                        </Button>
                    ) : null}
                </div>
            </form>
        </Drawer>
    );
}

function drawerTitle(mode, form) {
    if (mode === "create") return "新增活动模版";
    if (mode === "version") return `发布版本 v${form.publishedVersion || "-"}`;
    if (mode === "view") return "查看活动模版";
    return "编辑活动模版";
}
