import Add from "@mui/icons-material/Add";
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,
    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,
} from "@/shared/ui/AdminListLayout.jsx";
import { createOptionsColumnFilter, createTextColumnFilter } from "@/shared/ui/tableFilters.js";
import { AppJumpConfigField } from "@/shared/ui/AppJumpConfigField.jsx";
import { UploadField } from "@/shared/ui/UploadField.jsx";
import { formatMillis } from "@/shared/utils/time.js";
import {
    taskActionLabels,
    taskActionOptions,
    taskMetricOptions,
    taskStatusLabels,
    taskStatusOptions,
    taskTypeOptions,
    taskUnitLabels,
    taskUnitOptions,
} from "@/features/daily-tasks/constants.js";
import { useDailyTasksPage } from "@/features/daily-tasks/hooks/useDailyTasksPage.js";
import styles from "@/features/daily-tasks/daily-tasks.module.css";

const baseColumns = [
    {
        key: "task",
        label: "任务",
        width: "minmax(260px, 1.4fr)",
        render: (task) => <TaskIdentity task={task} />,
    },
    {
        key: "metric",
        label: "指标",
        width: "minmax(220px, 1.1fr)",
        render: (task) => (
            <div className={styles.stack}>
                <span>{task.metricType}</span>
                <span className={styles.meta}>
                    {formatNumber(task.targetValue)} {taskUnitLabel(task.targetUnit)}
                </span>
            </div>
        ),
    },
    {
        key: "display",
        label: "属性 / 跳转",
        width: "minmax(220px, 1fr)",
        render: (task) => (
            <div className={styles.stack}>
                <span>{taskActionLabel(task.actionType)}</span>
                <span className={styles.meta}>{task.actionParam || task.actionPayloadJson || "-"}</span>
            </div>
        ),
    },
    {
        key: "target",
        label: "目标 / 奖励",
        width: "minmax(150px, 0.75fr)",
        render: (task) => (
            <div className={styles.stack}>
                <span>
                    {formatNumber(task.targetValue)} {taskUnitLabel(task.targetUnit)}
                </span>
                <span className={styles.meta}>{formatNumber(task.rewardCoinAmount)} 金币</span>
            </div>
        ),
    },
    {
        key: "effective",
        label: "有效期",
        width: "minmax(220px, 1.1fr)",
        render: (task) => (
            <div className={styles.stack}>
                <span>{task.effectiveFromMs ? formatMillis(task.effectiveFromMs) : "立即生效"}</span>
                <span className={styles.meta}>
                    {task.effectiveToMs ? formatMillis(task.effectiveToMs) : "长期有效"}
                </span>
            </div>
        ),
    },
    {
        key: "version",
        label: "版本 / 排序",
        width: "minmax(120px, 0.65fr)",
        render: (task) => (
            <div className={styles.stack}>
                <span>v{task.version || 1}</span>
                <span className={styles.meta}>{task.sortOrder || 0}</span>
            </div>
        ),
    },
    {
        key: "status",
        label: "状态",
        width: "minmax(116px, 0.6fr)",
    },
    {
        key: "updatedAt",
        label: "更新时间",
        width: "minmax(170px, 0.85fr)",
        render: (task) => formatMillis(task.updatedAtMs || task.createdAtMs),
    },
    {
        key: "actions",
        label: "操作",
        width: "minmax(76px, 0.4fr)",
    },
];

export function DailyTaskListPage() {
    const page = useDailyTasksPage();
    const items = page.data.items || [];
    const total = page.data.total || 0;
    const isEditing = page.activeAction === "edit";
    const columns = baseColumns.map((column) => {
        if (column.key === "task") {
            return {
                ...column,
                filter: createTextColumnFilter({
                    placeholder: "搜索任务名称、任务 ID、指标",
                    value: page.query,
                    onChange: page.changeQuery,
                }),
            };
        }
        if (column.key === "metric") {
            return column;
        }
        if (column.key === "status") {
            return {
                ...column,
                filter: createOptionsColumnFilter({
                    options: taskStatusOptions,
                    placeholder: "搜索状态",
                    value: page.status,
                    onChange: page.changeStatus,
                }),
                render: (task) => <TaskStatusSwitch page={page} task={task} />,
            };
        }
        if (column.key === "actions") {
            return {
                ...column,
                render: (task) => <TaskRowActions page={page} task={task} />,
            };
        }
        return column;
    });

    return (
        <AdminListPage>
            <AdminListToolbar
                filters={
                    <>
                        <AdminFilterSelect
                            label="任务类型"
                            options={[["", "全部类型"], ...taskTypeOptions]}
                            value={page.taskType}
                            onChange={page.changeTaskType}
                        />
                        <AdminFilterResetButton
                            disabled={!page.query && !page.status && !page.taskType}
                            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="1560px"
                        pagination={
                            total > 0
                                ? {
                                      page: page.page,
                                      pageSize: page.data.pageSize || 50,
                                      total,
                                      onPageChange: page.setPage,
                                  }
                                : undefined
                        }
                        rowKey={(task) => task.taskId}
                    />
                </AdminListBody>
            </DataState>
            <TaskFormDialog
                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.submitTask}
            />
        </AdminListPage>
    );
}

function TaskIdentity({ task }) {
    return (
        <div className={styles.identity}>
            <TaskIconPreview task={task} />
            <span className={styles.typeBadge}>{taskTypeLabel(task.taskType)}</span>
            <div className={styles.identityText}>
                <span className={styles.name}>{task.title || task.taskId}</span>
                <span className={styles.meta}>{task.taskId}</span>
            </div>
        </div>
    );
}

function TaskIconPreview({ task }) {
    const label = String(task.iconKey || "任务").slice(0, 2);
    return (
        <span className={styles.taskIcon} title={task.iconKey || task.iconUrl || "任务图标"}>
            {task.iconUrl ? <img alt="" src={task.iconUrl} /> : label}
        </span>
    );
}

function TaskStatusSwitch({ page, task }) {
    const checked = task.status === "active";
    const disabled =
        !page.abilities.canStatus || task.status === "archived" || page.loadingAction === `status-${task.taskId}`;
    return (
        <div className={styles.statusCell}>
            <AdminSwitch
                checked={checked}
                disabled={disabled}
                inputProps={{ "aria-label": checked ? "暂停任务" : "启用任务" }}
                onChange={(event) => page.toggleTask(task, event.target.checked)}
            />
            <span className={styles.meta}>{taskStatusLabel(task.status)}</span>
        </div>
    );
}

function TaskRowActions({ page, task }) {
    return (
        <AdminRowActions>
            <AdminActionIconButton
                disabled={!page.abilities.canUpdate}
                label="编辑任务"
                onClick={() => page.openEdit(task)}
            >
                <EditOutlined fontSize="small" />
            </AdminActionIconButton>
        </AdminRowActions>
    );
}

function TaskFormDialog({ disabled, form, loading, mode, onClose, onSubmit, open, page }) {
    return (
        <AdminFormDialog
            loading={loading}
            open={open}
            size="large"
            submitDisabled={disabled || loading}
            title={mode === "edit" ? "编辑任务" : "创建任务"}
            onClose={onClose}
            onSubmit={onSubmit}
        >
            <AdminFormSection title="基础信息">
                <AdminFormFieldGrid>
                    <TextField
                        disabled={disabled}
                        label="任务类型"
                        required
                        select
                        value={form.taskType}
                        onChange={(event) => page.setForm({ ...form, taskType: event.target.value })}
                    >
                        {taskTypeOptions.map(([value, label]) => (
                            <MenuItem key={value} value={value}>
                                {label}
                            </MenuItem>
                        ))}
                    </TextField>
                    <AdminFormSwitchField
                        checked={form.status === "active"}
                        checkedLabel="启用"
                        disabled={disabled || form.status === "archived"}
                        label="任务状态"
                        switchProps={{ inputProps: { "aria-label": "任务启用状态" } }}
                        uncheckedLabel={taskSwitchUncheckedLabel(form.status, mode)}
                        onChange={(checked) =>
                            page.setForm({ ...form, status: nextTaskStatusFromSwitch(form.status, checked, mode) })
                        }
                    />
                    <TextField
                        disabled={disabled}
                        label="任务名称"
                        required
                        value={form.title}
                        onChange={(event) => page.setForm({ ...form, title: event.target.value })}
                    />
                </AdminFormFieldGrid>
            </AdminFormSection>
            <AdminFormSection title="目标与奖励">
                <AdminFormFieldGrid>
                    <TextField
                        disabled={disabled}
                        label="指标类型"
                        required
                        select
                        value={form.metricType}
                        onChange={(event) => page.setForm({ ...form, metricType: event.target.value })}
                    >
                        {taskMetricOptions.map(([value, label]) => (
                            <MenuItem key={value} value={value}>
                                {label}
                            </MenuItem>
                        ))}
                    </TextField>
                    <TextField
                        disabled={disabled}
                        label="目标单位"
                        required
                        select
                        value={form.targetUnit}
                        onChange={(event) => page.setForm({ ...form, targetUnit: event.target.value })}
                    >
                        {taskUnitOptions.map(([value, label]) => (
                            <MenuItem key={value} value={value}>
                                {label}
                            </MenuItem>
                        ))}
                    </TextField>
                    <TextField
                        disabled={disabled}
                        label="目标值"
                        required
                        type="number"
                        value={form.targetValue}
                        onChange={(event) => page.setForm({ ...form, targetValue: event.target.value })}
                    />
                    <TextField
                        disabled={disabled}
                        label="奖励金币"
                        required
                        type="number"
                        value={form.rewardCoinAmount}
                        onChange={(event) => page.setForm({ ...form, rewardCoinAmount: event.target.value })}
                    />
                    <TextField
                        disabled={disabled}
                        label="排序"
                        type="number"
                        value={form.sortOrder}
                        onChange={(event) => page.setForm({ ...form, sortOrder: event.target.value })}
                    />
                </AdminFormFieldGrid>
            </AdminFormSection>
            <AdminFormSection title="展示与跳转">
                <div className={styles.jumpConfigGrid}>
                    <div className={styles.jumpConfigSide}>
                        <TextField
                            disabled={disabled}
                            label="跳转类型"
                            required
                            select
                            value={form.actionType === "none" ? "none" : "app"}
                            onChange={(event) => page.changeFormActionType(event.target.value)}
                        >
                            {taskActionOptions.map(([value, label]) => (
                                <MenuItem key={value} value={value}>
                                    {label}
                                </MenuItem>
                            ))}
                        </TextField>
                        <UploadField
                            className={styles.iconUpload}
                            density="compact"
                            disabled={disabled || !page.abilities.canUpload}
                            label="任务图标"
                            value={form.iconUrl}
                            onChange={(iconUrl) => page.setForm({ ...form, iconUrl })}
                        />
                    </div>
                    {form.actionType === "none" ? null : (
                        <AppJumpConfigField
                            allowCustom={false}
                            allowH5={false}
                            appParamLabel="APP 公共跳转 JSON"
                            className={styles.flutterJumpField}
                            disabled={disabled}
                            paramValue={form.appJumpParam}
                            required
                            typeLabel="跳转协议"
                            typeValue="app"
                            onChange={({ param }) =>
                                page.setForm({
                                    ...form,
                                    actionType: page.appJumpTypeFromParam(param),
                                    appJumpParam: param,
                                })
                            }
                        />
                    )}
                </div>
            </AdminFormSection>
            <AdminFormSection title="有效期">
                <AdminFormFieldGrid columns="repeat(2, minmax(0, 1fr))">
                    <TextField
                        disabled={disabled}
                        label="有效开始时间"
                        slotProps={{ inputLabel: { shrink: true } }}
                        type="datetime-local"
                        value={form.effectiveFrom}
                        onChange={(event) => page.setForm({ ...form, effectiveFrom: event.target.value })}
                    />
                    <TextField
                        disabled={disabled}
                        label="有效结束时间"
                        slotProps={{ inputLabel: { shrink: true } }}
                        type="datetime-local"
                        value={form.effectiveTo}
                        onChange={(event) => page.setForm({ ...form, effectiveTo: event.target.value })}
                    />
                </AdminFormFieldGrid>
            </AdminFormSection>
            <AdminFormSection title="说明">
                <TextField
                    disabled={disabled}
                    label="任务描述"
                    multiline
                    minRows={2}
                    value={form.description}
                    onChange={(event) => page.setForm({ ...form, description: event.target.value })}
                />
            </AdminFormSection>
        </AdminFormDialog>
    );
}

function taskTypeLabel(value) {
    return taskTypeOptions.find(([optionValue]) => optionValue === value)?.[1] || value || "-";
}

function taskStatusLabel(value) {
    return taskStatusLabels[value] || value || "-";
}

function taskActionLabel(value) {
    return taskActionLabels[value] || value || "-";
}

function taskSwitchUncheckedLabel(status, mode) {
    if (status === "archived") {
        return "归档";
    }
    return status === "draft" || mode === "create" ? "草稿" : "暂停";
}

function nextTaskStatusFromSwitch(status, checked, mode) {
    if (checked) {
        return "active";
    }
    if (status === "archived") {
        return "archived";
    }
    return status === "draft" || mode === "create" ? "draft" : "paused";
}

function taskUnitLabel(value) {
    return taskUnitLabels[value] || value || "";
}

function formatNumber(value) {
    const number = Number(value || 0);
    return Number.isFinite(number) ? number.toLocaleString("zh-CN") : "0";
}
