import AddOutlined from "@mui/icons-material/AddOutlined";
import ArchiveOutlined from "@mui/icons-material/ArchiveOutlined";
import ContentCopyOutlined from "@mui/icons-material/ContentCopyOutlined";
import EditOutlined from "@mui/icons-material/EditOutlined";
import HistoryOutlined from "@mui/icons-material/HistoryOutlined";
import QueryStatsOutlined from "@mui/icons-material/QueryStatsOutlined";
import PublishOutlined from "@mui/icons-material/PublishOutlined";
import RefreshOutlined from "@mui/icons-material/RefreshOutlined";
import StopCircleOutlined from "@mui/icons-material/StopCircleOutlined";
import VisibilityOutlined from "@mui/icons-material/VisibilityOutlined";
import TablePagination from "@mui/material/TablePagination";
import { lazy, Suspense } from "react";
import {
    ActivityTemplateCloneDialogSkeleton,
    ActivityTemplateDrawerSkeleton,
} from "@/features/activity-templates/components/ActivityTemplateOverlaySkeletons.jsx";
import { ActivityTemplateStatusBadge } from "@/features/activity-templates/components/ActivityTemplateStatusBadge.jsx";
import { ACTIVITY_TEMPLATE_STATUS_OPTIONS } from "@/features/activity-templates/constants.js";
import { canOpenActivityTemplateData } from "@/features/activity-templates/dataModel.js";
import { useActivityTemplatesPage } from "@/features/activity-templates/hooks/useActivityTemplatesPage.js";
import styles from "@/features/activity-templates/activity-templates.module.css";
import {
    AdminActionIconButton,
    AdminFilterResetButton,
    AdminFilterSelect,
    AdminListBody,
    AdminListPage,
    AdminListToolbar,
    AdminRowActions,
    AdminSearchBox,
} from "@/shared/ui/AdminListLayout.jsx";
import { Button } from "@/shared/ui/Button.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import { DataTable } from "@/shared/ui/DataTable.jsx";
import { RegionFilterControl } from "@/shared/ui/RegionFilterControl.jsx";
import { TimeRangeFilter } from "@/shared/ui/TimeRangeFilter.jsx";
import { formatMillis } from "@/shared/utils/time.js";

const ActivityTemplateCloneDialog = lazy(() =>
    import("@/features/activity-templates/components/ActivityTemplateCloneDialog.jsx").then((module) => ({
        default: module.ActivityTemplateCloneDialog,
    })),
);
const ActivityTemplateDataDrawer = lazy(() =>
    import("@/features/activity-templates/components/ActivityTemplateDataDrawer.jsx").then((module) => ({
        default: module.ActivityTemplateDataDrawer,
    })),
);
const ActivityTemplateEditorDrawer = lazy(() =>
    import("@/features/activity-templates/components/ActivityTemplateEditorDrawer.jsx").then((module) => ({
        default: module.ActivityTemplateEditorDrawer,
    })),
);
const ActivityTemplateVersionsDrawer = lazy(() =>
    import("@/features/activity-templates/components/ActivityTemplateVersionsDrawer.jsx").then((module) => ({
        default: module.ActivityTemplateVersionsDrawer,
    })),
);

export function ActivityTemplatesPage() {
    const page = useActivityTemplatesPage();
    const regionLabels = new Map(
        page.regionOptions.map((option) => [String(option.value), option.name || option.label]),
    );
    const columns = [
        {
            key: "template",
            label: "活动模版",
            width: "minmax(280px, 1.25fr)",
            render: (item) => (
                <div className={styles.templateIdentity}>
                    <span className={styles.templateTypeMark}>礼</span>
                    <span className={styles.cellStack}>
                        <strong>{item.name || "-"}</strong>
                        <small>{item.templateCode || item.templateId}</small>
                    </span>
                </div>
            ),
        },
        {
            key: "status",
            label: "状态",
            width: "120px",
            render: (item) => <ActivityTemplateStatusBadge status={item.lifecycleStatus || item.status} />,
        },
        {
            key: "period",
            label: "活动周期",
            width: "minmax(210px, .95fr)",
            render: (item) => (
                <div className={styles.cellStack}>
                    <span>{formatMillis(item.startMs)}</span>
                    <small>至 {formatMillis(item.endMs)}</small>
                </div>
            ),
        },
        {
            key: "scope",
            label: "投放区域",
            width: "minmax(170px, .7fr)",
            render: (item) => (
                <div className={styles.cellStack}>
                    <span>{item.allRegions ? "全部区域" : regionScopeLabel(item.regionIds, regionLabels)}</span>
                    <small>{item.allRegions ? "全量投放" : `${item.regionIds.length} 个区域`}</small>
                </div>
            ),
        },
        {
            key: "version",
            label: "版本",
            width: "130px",
            render: (item) => (
                <div className={styles.cellStack}>
                    <span>发布 v{item.publishedVersion || 0}</span>
                    <small>revision {item.revision || 0}</small>
                </div>
            ),
        },
        {
            key: "updated",
            label: "最近更新",
            width: "minmax(180px, .75fr)",
            render: (item) => (
                <div className={styles.cellStack}>
                    <span>{formatMillis(item.updatedAtMs)}</span>
                    <small>管理员 #{item.updatedByAdminId || "-"}</small>
                </div>
            ),
        },
        {
            key: "actions",
            label: "操作",
            width: "280px",
            render: (item) => {
                const actionLoading = page.loadingAction.includes(item.templateId);
                const editable = item.status === "draft" || item.status === "disabled";
                const canArchive = editable || item.lifecycleStatus === "ended";
                return (
                    <AdminRowActions>
                        {editable && page.abilities.canUpdate ? (
                            <AdminActionIconButton
                                disabled={actionLoading}
                                label="编辑"
                                onClick={() => page.openEdit(item)}
                            >
                                <EditOutlined fontSize="small" />
                            </AdminActionIconButton>
                        ) : (
                            <AdminActionIconButton
                                disabled={actionLoading}
                                label="查看"
                                onClick={() => page.openView(item)}
                            >
                                <VisibilityOutlined fontSize="small" />
                            </AdminActionIconButton>
                        )}
                        {page.abilities.canCreate ? (
                            <AdminActionIconButton
                                disabled={actionLoading}
                                label="复制"
                                onClick={() => page.openClone(item)}
                            >
                                <ContentCopyOutlined fontSize="small" />
                            </AdminActionIconButton>
                        ) : null}
                        {item.publishedVersion > 0 ? (
                            <AdminActionIconButton
                                disabled={actionLoading}
                                label="发布版本"
                                onClick={() => page.openVersions(item)}
                            >
                                <HistoryOutlined fontSize="small" />
                            </AdminActionIconButton>
                        ) : null}
                        {canOpenActivityTemplateData(item, page.abilities) ? (
                            <AdminActionIconButton
                                disabled={actionLoading}
                                label="数据中心"
                                onClick={() => page.openData(item)}
                            >
                                <QueryStatsOutlined fontSize="small" />
                            </AdminActionIconButton>
                        ) : null}
                        {page.abilities.canPublish && editable ? (
                            <AdminActionIconButton
                                disabled={actionLoading}
                                label="发布"
                                onClick={() => page.changeStatus(item, "published")}
                            >
                                <PublishOutlined fontSize="small" />
                            </AdminActionIconButton>
                        ) : null}
                        {page.abilities.canPublish &&
                        item.status === "published" &&
                        item.lifecycleStatus !== "ended" ? (
                            <AdminActionIconButton
                                disabled={actionLoading}
                                label="停用"
                                tone="danger"
                                onClick={() => page.changeStatus(item, "disabled")}
                            >
                                <StopCircleOutlined fontSize="small" />
                            </AdminActionIconButton>
                        ) : null}
                        {page.abilities.canDelete && canArchive ? (
                            <AdminActionIconButton
                                disabled={actionLoading}
                                label="归档"
                                tone="danger"
                                onClick={() => page.archiveTemplate(item)}
                            >
                                <ArchiveOutlined fontSize="small" />
                            </AdminActionIconButton>
                        ) : null}
                    </AdminRowActions>
                );
            },
        },
    ];

    return (
        <AdminListPage>
            <AdminListToolbar
                actions={
                    <>
                        <Button startIcon={<RefreshOutlined fontSize="small" />} onClick={page.reload}>
                            刷新
                        </Button>
                        {page.abilities.canCreate ? (
                            <Button
                                startIcon={<AddOutlined fontSize="small" />}
                                variant="primary"
                                onClick={page.openCreate}
                            >
                                新增模版
                            </Button>
                        ) : null}
                    </>
                }
                filters={
                    <>
                        <AdminSearchBox
                            label="搜索"
                            placeholder="内部名称 / 模版编码 / 模版 ID"
                            value={page.keyword}
                            onChange={page.setKeyword}
                        />
                        <AdminFilterSelect
                            label="状态"
                            options={ACTIVITY_TEMPLATE_STATUS_OPTIONS}
                            value={page.status}
                            onChange={page.setStatus}
                        />
                        <RegionFilterControl
                            emptyLabel="全部区域"
                            label="区域"
                            loading={page.loadingRegions}
                            options={page.regionOptions}
                            value={page.regionId}
                            onChange={page.setRegionId}
                        />
                        <TimeRangeFilter label="活动时间" value={page.timeRange} onChange={page.setTimeRange} />
                        <AdminFilterResetButton onClick={page.resetFilters} />
                    </>
                }
            />
            <DataState error={page.error} loading={page.loading} onRetry={page.reload}>
                <AdminListBody>
                    <DataTable
                        columns={columns}
                        items={page.data.items || []}
                        minWidth="1500px"
                        rowKey={(item) => item.templateId}
                        total={page.data.total || 0}
                    />
                    <TablePagination
                        component="div"
                        count={Number(page.data.total || 0)}
                        labelDisplayedRows={({ from, to, count }) => `${from}-${to} / ${count}`}
                        labelRowsPerPage="每页"
                        page={Math.max(0, page.page - 1)}
                        rowsPerPage={page.pageSize}
                        rowsPerPageOptions={[20, 50, 100]}
                        onPageChange={(_, nextPage) => page.setPage(nextPage + 1)}
                        onRowsPerPageChange={(event) => page.changePageSize(Number(event.target.value))}
                    />
                </AdminListBody>
            </DataState>
            {page.editorMode ? (
                <Suspense
                    fallback={
                        <ActivityTemplateDrawerSkeleton
                            className={styles.editorDrawer}
                            title="活动模版加载中"
                            onClose={page.closeEditor}
                        />
                    }
                >
                    <ActivityTemplateEditorDrawer
                        abilities={page.abilities}
                        dirty={page.editorDirty}
                        form={page.form}
                        gifts={page.gifts}
                        giftsLoading={page.giftsLoading}
                        loading={page.editorLoading}
                        loadingRegions={page.loadingRegions}
                        mode={page.editorMode}
                        open
                        regionOptions={page.regionOptions}
                        resourceGroups={page.resourceGroups}
                        saving={
                            page.loadingAction === "save" ||
                            page.loadingAction === "save-publish" ||
                            page.loadingAction === `status:${page.form.templateId}`
                        }
                        setForm={page.setForm}
                        validationIssues={page.validationIssues}
                        onClose={page.closeEditor}
                        onDisable={page.disableFromEditor}
                        onPublish={page.saveAndPublish}
                        onReload={page.reloadEditor}
                        onSubmit={page.submitForm}
                    />
                </Suspense>
            ) : null}
            {page.cloneSource ? (
                <Suspense fallback={<ActivityTemplateCloneDialogSkeleton onClose={page.closeClone} />}>
                    <ActivityTemplateCloneDialog
                        form={page.cloneForm}
                        open
                        saving={page.loadingAction === "clone"}
                        source={page.cloneSource}
                        onChange={page.updateCloneForm}
                        onClose={page.closeClone}
                        onSubmit={page.submitClone}
                    />
                </Suspense>
            ) : null}
            {page.versionSource ? (
                <Suspense
                    fallback={
                        <ActivityTemplateDrawerSkeleton
                            className={styles.versionDrawer}
                            title="发布版本加载中"
                            width="detail"
                            onClose={page.closeVersions}
                        />
                    }
                >
                    <ActivityTemplateVersionsDrawer
                        abilities={page.abilities}
                        data={page.versions}
                        error={page.versionsError}
                        loading={page.versionsLoading}
                        open
                        page={page.versionPage}
                        source={page.versionSource}
                        onClone={page.cloneVersion}
                        onClose={page.closeVersions}
                        onPageChange={page.setVersionPage}
                        onPreview={page.previewVersion}
                        onRetry={page.reloadVersions}
                    />
                </Suspense>
            ) : null}
            {page.dataSource ? (
                <Suspense
                    fallback={
                        <ActivityTemplateDrawerSkeleton
                            className={styles.dataDrawer}
                            title="数据中心加载中"
                            onClose={page.closeData}
                        />
                    }
                >
                    <ActivityTemplateDataDrawer
                        abilities={page.abilities}
                        key={`${page.dataSource.templateId}:${page.dataSource.publishedVersion || 0}`}
                        loadingRegions={page.loadingRegions}
                        open
                        regionOptions={page.regionOptions}
                        source={page.dataSource}
                        onClose={page.closeData}
                    />
                </Suspense>
            ) : null}
        </AdminListPage>
    );
}

function regionScopeLabel(regionIds, regionLabels) {
    const names = regionIds.map((regionId) => regionLabels.get(String(regionId)) || `#${regionId}`);
    if (names.length <= 2) return names.join("、") || "未配置";
    return `${names.slice(0, 2).join("、")} 等 ${names.length} 个`;
}
