import AddOutlined from "@mui/icons-material/AddOutlined";
import DeleteOutlineOutlined from "@mui/icons-material/DeleteOutlineOutlined";
import EditOutlined from "@mui/icons-material/EditOutlined";
import ImageOutlined from "@mui/icons-material/ImageOutlined";
import TextField from "@mui/material/TextField";
import { useMemo } from "react";
import styles from "@/features/app-config/app-config.module.css";
import { usePopupConfigPage } from "@/features/app-config/hooks/usePopupConfigPage.js";
import {
    AdminFormDialog,
    AdminFormFieldGrid,
    AdminFormSection,
    AdminFormSwitchField,
} from "@/shared/ui/AdminFormDialog.jsx";
import {
    AdminActionIconButton,
    AdminListBody,
    AdminListPage,
    AdminListToolbar,
    AdminRowActions,
} from "@/shared/ui/AdminListLayout.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import { DataTable } from "@/shared/ui/DataTable.jsx";
import { createOptionsColumnFilter, createTextColumnFilter } from "@/shared/ui/tableFilters.js";
import { AppJumpConfigField } from "@/shared/ui/AppJumpConfigField.jsx";
import { TimeRangeFilter } from "@/shared/ui/TimeRangeFilter.jsx";
import { UploadField } from "@/shared/ui/UploadField.jsx";
import { formatMillis } from "@/shared/utils/time.js";

const statusOptions = [
    ["", "全部状态"],
    ["active", "启用"],
    ["disabled", "关闭"],
    ["expired", "过期"],
];

export function PopupConfigPage() {
    const page = usePopupConfigPage();
    const items = page.data.items || [];
    const columns = useMemo(() => popupColumns(page), [page]);

    return (
        <AdminListPage>
            <AdminListToolbar
                actions={
                    page.abilities.canUpdate ? (
                        <AdminActionIconButton label="新增弹窗" primary onClick={page.openCreate}>
                            <AddOutlined fontSize="small" />
                        </AdminActionIconButton>
                    ) : null
                }
            />
            <DataState error={page.error} loading={page.loading} onRetry={page.reload}>
                <AdminListBody>
                    <DataTable
                        columns={columns}
                        items={items}
                        minWidth="1180px"
                        pagination={{
                            itemCount: items.length,
                            page: 1,
                            pageSize: items.length || 1,
                            total: page.data.total ?? items.length,
                        }}
                        rowKey={(item) => item.id}
                    />
                </AdminListBody>
            </DataState>

            <AdminFormDialog
                loading={page.loadingAction === "create" || page.loadingAction === "edit"}
                open={Boolean(page.activeAction)}
                size="large"
                submitDisabled={
                    !page.abilities.canUpdate || page.loadingAction === "create" || page.loadingAction === "edit"
                }
                title={page.editingItem ? "编辑弹窗配置" : "新增弹窗配置"}
                onClose={page.closeDialog}
                onSubmit={page.submitPopup}
            >
                <div className={styles.popupFormLayout}>
                    <div className={styles.popupAssetPane}>
                        <AdminFormSection title="图片">
                            <UploadField
                                className={styles.popupUploadField}
                                disabled={!page.abilities.canUpdate || !page.abilities.canUpload}
                                label="弹窗图片"
                                previewClassName={styles.popupUploadPreview}
                                value={page.form.imageUrl}
                                onChange={(imageUrl) => page.setForm({ imageUrl })}
                            />
                        </AdminFormSection>
                    </div>
                    <div className={styles.popupFieldPane}>
                        <AdminFormSection title="基础信息">
                            <AdminFormFieldGrid columns="repeat(2, minmax(0, 1fr))">
                                <TextField
                                    className={styles.formWideField}
                                    disabled={!page.abilities.canUpdate}
                                    label="弹窗code"
                                    required
                                    value={page.form.code}
                                    onChange={(event) => page.setForm({ code: event.target.value })}
                                />
                                <TextField
                                    className={styles.formWideField}
                                    disabled={!page.abilities.canUpdate}
                                    label="弹窗名字"
                                    required
                                    value={page.form.name}
                                    onChange={(event) => page.setForm({ name: event.target.value })}
                                />
                                <TextField
                                    disabled={!page.abilities.canUpdate}
                                    label="展示周期(天)"
                                    slotProps={{ htmlInput: { min: 0, step: 1 } }}
                                    type="number"
                                    value={page.form.displayPeriodDays}
                                    onChange={(event) => page.setForm({ displayPeriodDays: event.target.value })}
                                />
                                <AppJumpConfigField
                                    appParamLabel="跳转地址（APP公共跳转JSON）"
                                    className={styles.formWideField}
                                    disabled={!page.abilities.canUpdate}
                                    h5Label="跳转地址（H5链接）"
                                    paramValue={page.form.jumpUrl}
                                    required
                                    typeLabel="跳转类型"
                                    typeValue={page.form.jumpType}
                                    onChange={({ param, type }) => page.setForm({ jumpType: type, jumpUrl: param })}
                                />
                            </AdminFormFieldGrid>
                        </AdminFormSection>
                        <AdminFormSection title="生效设置">
                            <AdminFormFieldGrid columns="repeat(2, minmax(0, 1fr))">
                                <TextField
                                    disabled={!page.abilities.canUpdate}
                                    label="排序"
                                    slotProps={{ htmlInput: { step: 1 } }}
                                    type="number"
                                    value={page.form.sortOrder}
                                    onChange={(event) => page.setForm({ sortOrder: event.target.value })}
                                />
                                <AdminFormSwitchField
                                    checked={page.form.status === "active"}
                                    checkedLabel="启用"
                                    disabled={!page.abilities.canUpdate}
                                    label="弹窗状态"
                                    switchProps={{ inputProps: { "aria-label": "弹窗启用状态" } }}
                                    uncheckedLabel={page.form.status === "expired" ? "过期" : "关闭"}
                                    onChange={(checked) => page.setForm({ status: checked ? "active" : "disabled" })}
                                />
                                <TimeRangeFilter
                                    className={styles.formWideField}
                                    disabled={!page.abilities.canUpdate}
                                    label="生效时间区间"
                                    value={{ endMs: page.form.endsAtMs, startMs: page.form.startsAtMs }}
                                    onChange={(range) =>
                                        page.setForm({ endsAtMs: range.endMs, startsAtMs: range.startMs })
                                    }
                                />
                            </AdminFormFieldGrid>
                        </AdminFormSection>
                    </div>
                </div>
            </AdminFormDialog>
        </AdminListPage>
    );
}

function popupColumns(page) {
    const columns = [
        {
            key: "image",
            label: "图片",
            render: (item) => <PopupImage src={item.imageUrl} />,
            width: "minmax(96px, 0.45fr)",
        },
        {
            key: "name",
            label: "弹窗名字",
            render: (item) => <Stack primary={item.name || "-"} secondary={item.code || "-"} />,
            filter: createTextColumnFilter({
                placeholder: "搜索code、名字、跳转地址",
                value: page.keyword,
                onChange: page.setKeyword,
            }),
            width: "minmax(200px, 0.9fr)",
        },
        {
            key: "jump",
            label: "跳转",
            render: (item) => <Stack primary={typeLabel(item.jumpType)} secondary={item.jumpUrl || "-"} />,
            width: "minmax(260px, 1.25fr)",
        },
        {
            key: "displayPeriodDays",
            label: "展示周期",
            render: (item) => periodLabel(item.displayPeriodDays),
            width: "minmax(110px, 0.55fr)",
        },
        {
            key: "status",
            label: "状态",
            render: (item) => <StatusBadge status={item.status} />,
            filter: createOptionsColumnFilter({
                options: statusOptions,
                placeholder: "搜索状态",
                value: page.status,
                onChange: page.setStatus,
            }),
            width: "minmax(100px, 0.5fr)",
        },
        {
            key: "sortOrder",
            label: "排序",
            width: "minmax(80px, 0.4fr)",
        },
        {
            key: "effectiveTime",
            label: "生效时间",
            render: (item) => effectiveTimeLabel(item.startsAtMs, item.endsAtMs),
            width: "minmax(220px, 1fr)",
        },
        {
            key: "updatedAtMs",
            label: "更新时间",
            render: (item) => formatMillis(item.updatedAtMs),
            width: "minmax(160px, 0.75fr)",
        },
    ];

    if (!page.abilities.canUpdate) {
        return columns;
    }

    return [
        ...columns,
        {
            key: "actions",
            label: "操作",
            render: (item) => <PopupActions item={item} page={page} />,
            width: "minmax(96px, 0.45fr)",
        },
    ];
}

function PopupImage({ src }) {
    if (!src) {
        return (
            <span className={styles.popupCoverEmpty}>
                <ImageOutlined fontSize="small" />
            </span>
        );
    }
    return <img alt="" className={styles.popupCover} src={src} />;
}

function PopupActions({ item, page }) {
    const deleting = page.loadingAction === `delete:${item.id}`;
    return (
        <AdminRowActions>
            <AdminActionIconButton
                disabled={Boolean(page.loadingAction)}
                label="编辑"
                onClick={() => page.openEdit(item)}
            >
                <EditOutlined fontSize="small" />
            </AdminActionIconButton>
            <AdminActionIconButton
                disabled={deleting || Boolean(page.loadingAction)}
                label="删除"
                onClick={() => page.removePopup(item)}
            >
                <DeleteOutlineOutlined fontSize="small" />
            </AdminActionIconButton>
        </AdminRowActions>
    );
}

function Stack({ primary, secondary }) {
    return (
        <div className="cell-stack">
            <span>{primary || "-"}</span>
            <span className="muted">{secondary || "-"}</span>
        </div>
    );
}

function StatusBadge({ status }) {
    const tone = status === "active" ? "succeeded" : status === "expired" ? "warning" : "stopped";
    return (
        <span className={`status-badge status-badge--${tone}`}>
            <span className="status-point" />
            {statusLabel(status)}
        </span>
    );
}

function typeLabel(value) {
    return value === "app" ? "APP" : "H5";
}

function periodLabel(value) {
    const days = Number(value || 0);
    if (!Number.isFinite(days) || days <= 0) {
        return "每次打开";
    }
    return `${days} 天一次`;
}

function effectiveTimeLabel(startsAtMs, endsAtMs) {
    const start = startsAtMs ? formatMillis(startsAtMs) : "不限";
    const end = endsAtMs ? formatMillis(endsAtMs) : "不限";
    return `${start} - ${end}`;
}

function statusLabel(status) {
    if (status === "active") {
        return "启用";
    }
    if (status === "expired") {
        return "过期";
    }
    return "关闭";
}
