import Add from "@mui/icons-material/Add";
import DeleteOutlineOutlined from "@mui/icons-material/DeleteOutlineOutlined";
import EditOutlined from "@mui/icons-material/EditOutlined";
import { AdminSwitch } from "@/shared/ui/AdminSwitch.jsx";
import MenuItem from "@mui/material/MenuItem";
import TextField from "@mui/material/TextField";
import {
    AdminFormDialog,
    AdminFormFieldGrid,
    AdminFormList,
    AdminFormListRow,
    AdminFormSection,
    AdminFormSwitchField,
} from "@/shared/ui/AdminFormDialog.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import { DataTable } from "@/shared/ui/DataTable.jsx";
import {
    AdminActionIconButton,
    AdminFilterResetButton,
    AdminFilterSelect,
    AdminListBody,
    AdminListPage,
    AdminListToolbar,
    AdminRowActions,
    AdminSearchBox,
} from "@/shared/ui/AdminListLayout.jsx";
import { ResourceGroupSelectField } from "@/shared/ui/ResourceGroupSelectDrawer.jsx";
import { formatMillis } from "@/shared/utils/time.js";
import {
    achievementStatusLabels,
    achievementStatusOptions,
    achievementTypeLabels,
    achievementTypeOptions,
    autoPinPolicyLabels,
    autoPinPolicyOptions,
    collectionTypeFilterOptions,
    collectionTypeLabels,
    collectionTypeOptions,
    targetUnitLabels,
    targetUnitOptions,
} from "@/features/achievements/constants.js";
import { useAchievementsPage } from "@/features/achievements/hooks/useAchievementsPage.js";
import styles from "@/features/achievements/achievements.module.css";

const baseColumns = [
    {
        key: "achievement",
        label: "成就",
        width: "minmax(260px, 1.4fr)",
        render: (achievement) => <AchievementIdentity achievement={achievement} />,
    },
    {
        key: "condition",
        label: "达成条件",
        width: "minmax(240px, 1.2fr)",
        render: (achievement) => <ConditionSummary conditions={achievement.conditions} />,
    },
    {
        key: "badge",
        label: "展示徽章",
        width: "minmax(190px, 0.9fr)",
    },
    {
        key: "reward",
        label: "奖励资源组",
        width: "minmax(190px, 0.9fr)",
    },
    {
        key: "display",
        label: "展示策略",
        width: "minmax(150px, 0.7fr)",
        render: (achievement) => (
            <div className={styles.stack}>
                <span>{autoPinPolicyLabel(achievement.autoPinPolicy)}</span>
                <span className={styles.meta}>{achievement.honorVisibility ? "荣誉墙可见" : "荣誉墙隐藏"}</span>
            </div>
        ),
    },
    {
        key: "effective",
        label: "有效期",
        width: "minmax(220px, 1.05fr)",
        render: (achievement) => (
            <div className={styles.stack}>
                <span>{achievement.effectiveFromMs ? formatMillis(achievement.effectiveFromMs) : "立即生效"}</span>
                <span className={styles.meta}>
                    {achievement.effectiveToMs ? formatMillis(achievement.effectiveToMs) : "长期有效"}
                </span>
            </div>
        ),
    },
    {
        key: "version",
        label: "版本 / 排序",
        width: "minmax(120px, 0.6fr)",
        render: (achievement) => (
            <div className={styles.stack}>
                <span>v{achievement.version || 1}</span>
                <span className={styles.meta}>{achievement.sortOrder || 0}</span>
            </div>
        ),
    },
    {
        key: "status",
        label: "状态",
        width: "minmax(116px, 0.55fr)",
    },
    {
        key: "updatedAt",
        label: "更新时间",
        width: "minmax(170px, 0.8fr)",
        render: (achievement) => formatMillis(achievement.updatedAtMs || achievement.createdAtMs),
    },
    {
        key: "actions",
        label: "操作",
        width: "minmax(76px, 0.35fr)",
    },
];

export function AchievementConfigPage() {
    const page = useAchievementsPage();
    const items = page.data.items || [];
    const total = page.data.total || 0;
    const isEditing = page.activeAction === "edit";
    const columns = baseColumns.map((column) => {
        if (column.key === "badge") {
            return {
                ...column,
                render: (achievement) => (
                    <ResourceLabel id={achievement.primaryBadgeResourceId} resources={page.badgeResources} />
                ),
            };
        }
        if (column.key === "reward") {
            return {
                ...column,
                render: (achievement) => (
                    <ResourceGroupLabel groups={page.resourceGroups} id={achievement.rewardResourceGroupId} />
                ),
            };
        }
        if (column.key === "status") {
            return {
                ...column,
                render: (achievement) => <AchievementStatusSwitch achievement={achievement} page={page} />,
            };
        }
        if (column.key === "actions") {
            return {
                ...column,
                render: (achievement) => <AchievementRowActions achievement={achievement} page={page} />,
            };
        }
        return column;
    });

    return (
        <AdminListPage>
            <AdminListToolbar
                filters={
                    <>
                        <AdminFilterSelect
                            label="合集类型"
                            options={collectionTypeFilterOptions}
                            value={page.collectionType}
                            onChange={page.changeCollectionType}
                        />
                        <AdminSearchBox
                            placeholder="搜索合集 ID"
                            value={page.collectionId}
                            onChange={page.changeCollectionId}
                        />
                        <AdminFilterResetButton
                            disabled={!page.collectionType && !page.collectionId}
                            onClick={page.resetFilters}
                        />
                    </>
                }
                actions={
                    page.abilities.canCreate ? (
                        <AdminActionIconButton label="添加成就" primary onClick={page.openCreate}>
                            <Add fontSize="small" />
                        </AdminActionIconButton>
                    ) : null
                }
            />
            <DataState error={page.error} loading={page.loading} onRetry={page.reload}>
                <AdminListBody>
                    <DataTable
                        columns={columns}
                        items={items}
                        minWidth="1710px"
                        pagination={
                            total > 0
                                ? {
                                      page: page.page,
                                      pageSize: page.data.pageSize || 50,
                                      total,
                                      onPageChange: page.setPage,
                                  }
                                : undefined
                        }
                        rowKey={(achievement) => achievement.achievementId}
                    />
                </AdminListBody>
            </DataState>
            <AchievementFormDialog
                disabled={isEditing ? !page.abilities.canUpdate : !page.abilities.canCreate}
                form={page.form}
                loading={isEditing ? page.loadingAction === "edit" : page.loadingAction === "create"}
                mode={isEditing ? "edit" : "create"}
                open={page.activeAction === "create" || page.activeAction === "edit"}
                page={page}
                onClose={page.closeAction}
                onSubmit={page.submitAchievement}
            />
        </AdminListPage>
    );
}

function AchievementIdentity({ achievement }) {
    return (
        <div className={styles.identity}>
            <span className={styles.typeBadge}>{achievementTypeLabel(achievement.achievementType)}</span>
            <div className={styles.identityText}>
                <span className={styles.name}>{achievement.title || achievement.achievementId}</span>
                <span className={styles.meta}>{achievement.achievementId}</span>
                <span className={styles.meta}>
                    {collectionTypeLabel(achievement.collectionType)} · {achievement.collectionId || "ordinary"}
                </span>
            </div>
        </div>
    );
}

function ConditionSummary({ conditions = [] }) {
    const first = conditions[0] || {};
    if (!first.metricType) {
        return <span className={styles.emptyValue}>未配置</span>;
    }
    return (
        <div className={styles.stack}>
            <span>{first.metricType}</span>
            <span className={styles.meta}>
                {formatNumber(first.targetValue)} {targetUnitLabel(first.targetUnit)}
                {conditions.length > 1 ? ` · 共 ${conditions.length} 条` : ""}
            </span>
        </div>
    );
}

function AchievementStatusSwitch({ achievement, page }) {
    const checked = achievement.status === "active";
    const disabled =
        !page.abilities.canUpdate ||
        achievement.status === "archived" ||
        page.loadingAction === `status-${achievement.achievementId}`;
    return (
        <div className={styles.statusCell}>
            <AdminSwitch
                checked={checked}
                disabled={disabled}
                inputProps={{ "aria-label": checked ? "暂停成就" : "启用成就" }}
                onChange={(event) => page.toggleAchievement(achievement, event.target.checked)}
            />
            <span className={styles.meta}>{achievementStatusLabel(achievement.status)}</span>
        </div>
    );
}

function AchievementRowActions({ achievement, page }) {
    return (
        <AdminRowActions>
            <AdminActionIconButton
                disabled={!page.abilities.canUpdate}
                label="编辑成就"
                onClick={() => page.openEdit(achievement)}
            >
                <EditOutlined fontSize="small" />
            </AdminActionIconButton>
        </AdminRowActions>
    );
}

function AchievementFormDialog({ disabled, form, loading, mode, onClose, onSubmit, open, page }) {
    return (
        <AdminFormDialog
            loading={loading}
            open={open}
            size="wide"
            submitDisabled={disabled || loading}
            submitLabel={mode === "edit" ? "保存成就" : "创建成就"}
            title={mode === "edit" ? "编辑成就" : "创建成就"}
            onClose={onClose}
            onSubmit={onSubmit}
        >
            <AdminFormSection title="基础信息">
                <AdminFormFieldGrid>
                    <TextField
                        disabled={disabled}
                        label="合集类型"
                        required
                        select
                        value={form.collectionType}
                        onChange={changeField(page.setForm, "collectionType")}
                    >
                        {collectionTypeOptions.map(([value, label]) => (
                            <MenuItem key={value} value={value}>
                                {label}
                            </MenuItem>
                        ))}
                    </TextField>
                    <TextField
                        disabled={disabled}
                        label="成就类型"
                        required
                        select
                        value={form.achievementType}
                        onChange={changeField(page.setForm, "achievementType")}
                    >
                        {achievementTypeOptions.map(([value, label]) => (
                            <MenuItem key={value} value={value}>
                                {label}
                            </MenuItem>
                        ))}
                    </TextField>
                    <TextField
                        disabled={disabled}
                        label="合集 ID"
                        value={form.collectionId}
                        onChange={changeField(page.setForm, "collectionId")}
                    />
                    <TextField
                        disabled={disabled}
                        label="状态"
                        required
                        select
                        value={form.status}
                        onChange={changeField(page.setForm, "status")}
                    >
                        {achievementStatusOptions.map(([value, label]) => (
                            <MenuItem key={value} value={value}>
                                {label}
                            </MenuItem>
                        ))}
                    </TextField>
                    <TextField
                        disabled={disabled}
                        label="成就名称"
                        required
                        value={form.title}
                        onChange={changeField(page.setForm, "title")}
                    />
                    <TextField
                        disabled={disabled}
                        label="描述"
                        value={form.description}
                        onChange={changeField(page.setForm, "description")}
                    />
                </AdminFormFieldGrid>
            </AdminFormSection>
            <AdminFormSection
                actions={
                    <AdminActionIconButton
                        disabled={disabled}
                        label="添加条件"
                        type="button"
                        onClick={page.addCondition}
                    >
                        <Add fontSize="small" />
                    </AdminActionIconButton>
                }
                title="达成条件"
            >
                <AdminFormList>
                    {form.conditions.map((condition, index) => (
                        <AdminFormListRow
                            key={index}
                            columns="minmax(180px, 1fr) minmax(110px, 0.55fr) minmax(120px, 0.6fr) minmax(220px, 1.1fr) 44px"
                        >
                            <TextField
                                disabled={disabled}
                                label="指标类型"
                                required
                                value={condition.metricType}
                                onChange={(event) => page.updateCondition(index, "metricType", event.target.value)}
                            />
                            <TextField
                                disabled={disabled}
                                inputProps={{ min: 1 }}
                                label="目标值"
                                required
                                type="number"
                                value={condition.targetValue}
                                onChange={(event) => page.updateCondition(index, "targetValue", event.target.value)}
                            />
                            <TextField
                                disabled={disabled}
                                label="目标单位"
                                required
                                select
                                value={condition.targetUnit}
                                onChange={(event) => page.updateCondition(index, "targetUnit", event.target.value)}
                            >
                                {targetUnitOptions.map(([value, label]) => (
                                    <MenuItem key={value} value={value}>
                                        {label}
                                    </MenuItem>
                                ))}
                            </TextField>
                            <TextField
                                disabled={disabled}
                                label="维度过滤 JSON"
                                value={condition.dimensionFilterJson}
                                onChange={(event) =>
                                    page.updateCondition(index, "dimensionFilterJson", event.target.value)
                                }
                            />
                            <AdminActionIconButton
                                disabled={disabled || form.conditions.length <= 1}
                                label="删除条件"
                                type="button"
                                onClick={() => page.removeCondition(index)}
                            >
                                <DeleteOutlineOutlined fontSize="small" />
                            </AdminActionIconButton>
                        </AdminFormListRow>
                    ))}
                </AdminFormList>
            </AdminFormSection>
            <AdminFormSection title="徽章与奖励">
                <AdminFormFieldGrid>
                    <ResourceSelect
                        disabled={disabled}
                        label="达成展示徽章"
                        resources={page.badgeResources}
                        value={form.primaryBadgeResourceId}
                        onChange={changeField(page.setForm, "primaryBadgeResourceId")}
                    />
                    <ResourceGroupSelectField
                        allowEmpty
                        disabled={disabled}
                        groups={page.resourceGroups}
                        label="达成奖励资源组"
                        value={form.rewardResourceGroupId}
                        onChange={(value) => page.setForm((current) => ({ ...current, rewardResourceGroupId: value }))}
                    />
                    <TextField
                        disabled={disabled}
                        label="展示策略"
                        select
                        value={form.autoPinPolicy}
                        onChange={changeField(page.setForm, "autoPinPolicy")}
                    >
                        {autoPinPolicyOptions.map(([value, label]) => (
                            <MenuItem key={value} value={value}>
                                {label}
                            </MenuItem>
                        ))}
                    </TextField>
                    <AdminFormSwitchField
                        checked={form.honorVisibility}
                        checkedLabel="显示"
                        disabled={disabled}
                        label="荣誉墙"
                        uncheckedLabel="隐藏"
                        onChange={(checked) => page.setForm((current) => ({ ...current, honorVisibility: checked }))}
                    />
                </AdminFormFieldGrid>
            </AdminFormSection>
            <AdminFormSection title="时间与展示">
                <AdminFormFieldGrid>
                    <TextField
                        disabled={disabled}
                        label="开始时间"
                        type="datetime-local"
                        value={form.effectiveFrom}
                        InputLabelProps={{ shrink: true }}
                        onChange={changeField(page.setForm, "effectiveFrom")}
                    />
                    <TextField
                        disabled={disabled}
                        label="结束时间"
                        type="datetime-local"
                        value={form.effectiveTo}
                        InputLabelProps={{ shrink: true }}
                        onChange={changeField(page.setForm, "effectiveTo")}
                    />
                    <TextField
                        disabled={disabled}
                        label="排序"
                        type="number"
                        value={form.sortOrder}
                        onChange={changeField(page.setForm, "sortOrder")}
                    />
                    <TextField
                        disabled={disabled}
                        label="展示配置 JSON"
                        value={form.displayConfigJson}
                        onChange={changeField(page.setForm, "displayConfigJson")}
                    />
                </AdminFormFieldGrid>
            </AdminFormSection>
        </AdminFormDialog>
    );
}

function ResourceSelect({ disabled, label, onChange, resources, value }) {
    const options = withSelectedResource(resources, value);
    return (
        <TextField select disabled={disabled} label={label} value={String(value || "")} onChange={onChange}>
            <MenuItem value="">不配置</MenuItem>
            {options.map((resource) => (
                <MenuItem key={resource.resourceId} value={String(resource.resourceId)}>
                    {resource.name || resource.resourceCode || resource.resourceId}
                </MenuItem>
            ))}
        </TextField>
    );
}

function ResourceLabel({ id, resources }) {
    if (!id) {
        return <span className={styles.emptyValue}>未配置</span>;
    }
    const resource = resources.find((item) => Number(item.resourceId) === Number(id));
    return (
        <div className={styles.stack}>
            <span className={styles.resourceText}>{resource?.name || resource?.resourceCode || `资源 #${id}`}</span>
            <span className={styles.meta}>ID {id}</span>
        </div>
    );
}

function ResourceGroupLabel({ groups, id }) {
    if (!id) {
        return <span className={styles.emptyValue}>未配置</span>;
    }
    const group = groups.find((item) => Number(item.groupId) === Number(id));
    return (
        <div className={styles.stack}>
            <span className={styles.resourceText}>{group?.name || group?.groupCode || `资源组 #${id}`}</span>
            <span className={styles.meta}>ID {id}</span>
        </div>
    );
}

function changeField(setter, key) {
    return (event) => {
        const value = event.target.value;
        setter((current) => ({ ...current, [key]: value }));
    };
}

function withSelectedResource(resources, value) {
    const selectedId = Number(value || 0);
    if (!selectedId || resources.some((resource) => Number(resource.resourceId) === selectedId)) {
        return resources;
    }
    return [{ resourceId: selectedId, name: `资源 #${selectedId}` }, ...resources];
}

function achievementStatusLabel(status) {
    return achievementStatusLabels[status] || status || "-";
}

function achievementTypeLabel(type) {
    return achievementTypeLabels[type] || type || "-";
}

function autoPinPolicyLabel(policy) {
    return autoPinPolicyLabels[policy] || policy || "-";
}

function collectionTypeLabel(type) {
    return collectionTypeLabels[type] || type || "-";
}

function targetUnitLabel(unit) {
    return targetUnitLabels[unit] || unit || "";
}

function formatNumber(value) {
    return Number(value || 0).toLocaleString("zh-CN");
}
