import { useCallback, useMemo, useState } from "react";
import { AdminUserIdentity } from "@/shared/ui/AdminUserIdentity.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import { DataTable } from "@/shared/ui/DataTable.jsx";
import { createTextFieldsColumnFilter, createUserIdentityColumnFilter } from "@/shared/ui/tableFilters.js";
import {
    emptyUserIdentityFilter,
    normalizeUserIdentityFilter,
    userIdentityFilterParams,
} from "@/shared/ui/userIdentityFilter.js";
import { usePaginatedQuery } from "@/shared/hooks/usePaginatedQuery.js";
import { formatMillis } from "@/shared/utils/time.js";
import { listAppUserBans } from "@/features/app-users/api";
import { appUserStatusLabels } from "@/features/app-users/constants.js";
import styles from "@/features/app-users/app-users.module.css";

const pageSize = 50;
const emptyData = { items: [], page: 1, pageSize, total: 0 };
const emptyOperatorFilter = Object.freeze({ ...emptyUserIdentityFilter, adminAccount: "" });

export function AppUserBanListPage() {
    const [targetFilter, setTargetFilter] = useState(emptyUserIdentityFilter);
    const [operatorFilter, setOperatorFilter] = useState(emptyOperatorFilter);
    const [page, setPage] = useState(1);
    const filters = useMemo(
        () => ({
            operator_admin_keyword: String(operatorFilter.adminAccount || "").trim(),
            ...userIdentityFilterParams(targetFilter, {
                displayUserId: "target_display_user_id",
                userId: "target_user_id",
                username: "target_username",
            }),
            ...userIdentityFilterParams(operatorFilter, {
                displayUserId: "operator_display_user_id",
                userId: "operator_user_id",
                username: "operator_username",
            }),
        }),
        [operatorFilter, targetFilter],
    );
    const {
        data = emptyData,
        error,
        loading,
        reload,
    } = usePaginatedQuery({
        errorMessage: "加载封禁列表失败",
        fetcher: listAppUserBans,
        filters,
        page,
        pageSize,
        queryKey: ["app-users", "bans", filters, page],
    });

    const changeTargetFilter = useCallback((value) => {
        setTargetFilter(normalizeUserIdentityFilter(value));
        setPage(1);
    }, []);

    const changeOperatorFilter = useCallback((value) => {
        const normalized = normalizeUserIdentityFilter(value);
        setOperatorFilter({
            ...normalized,
            adminAccount: String(value?.adminAccount ?? "").trim(),
        });
        setPage(1);
    }, []);

    const columns = useMemo(
        () => [
            {
                key: "target",
                label: "封禁用户",
                width: "minmax(280px, 1.4fr)",
                filter: createUserIdentityColumnFilter({
                    value: targetFilter,
                    onChange: changeTargetFilter,
                }),
                render: (record) => <TargetIdentity target={record.target} />,
            },
            {
                key: "operator",
                label: "封禁人",
                width: "minmax(280px, 1.4fr)",
                filter: createTextFieldsColumnFilter({
                    fields: [
                        { key: "displayUserId", label: "短 ID", placeholder: "输入短 ID", value: operatorFilter.displayUserId },
                        { key: "userId", label: "长 ID", placeholder: "输入长 ID", value: operatorFilter.userId },
                        { key: "username", label: "昵称", placeholder: "输入昵称", value: operatorFilter.username },
                        {
                            key: "adminAccount",
                            label: "后台账号",
                            placeholder: "输入后台账号",
                            value: operatorFilter.adminAccount,
                        },
                    ],
                    onChange: changeOperatorFilter,
                }),
                render: (record) => <OperatorIdentity operator={record.operator} />,
            },
            {
                key: "status",
                label: "状态",
                width: "minmax(110px, 0.6fr)",
                render: (record) => <UserStatus status={record.newStatus} />,
            },
            {
                key: "reason",
                label: "原因",
                width: "minmax(190px, 1fr)",
                render: (record) => <span className="muted">{record.reason || "-"}</span>,
            },
            {
                key: "createdAtMs",
                label: "封禁时间",
                width: "190px",
                render: (record) => <span className="muted">{formatMillis(record.createdAtMs)}</span>,
            },
        ],
        [changeOperatorFilter, changeTargetFilter, operatorFilter, targetFilter],
    );

    return (
        <section className={styles.root}>
            <div className={styles.contentPanel}>
                <DataState error={error} loading={loading} onRetry={reload}>
                    <div className={styles.listBlock}>
                        <DataTable
                            columns={columns}
                            items={data.items || []}
                            minWidth="1180px"
                            pagination={
                                data.total > 0
                                    ? {
                                          page,
                                          pageSize: data.pageSize || pageSize,
                                          total: data.total,
                                          onPageChange: setPage,
                                      }
                                    : undefined
                            }
                            rowKey={(record) => record.id}
                        />
                    </div>
                </DataState>
            </div>
        </section>
    );
}

function TargetIdentity({ target }) {
    return <AdminUserIdentity openInAppUserDetail rows={[target?.displayUserId, target?.userId]} user={target} />;
}

function OperatorIdentity({ operator }) {
    if (!operator) {
        return <span className="muted">-</span>;
    }
    if (operator.type === "admin") {
        return (
            <AdminUserIdentity
                name={operator.account}
                rows={[operator.name, operator.adminId ? `Admin ID ${operator.adminId}` : "后台管理员"]}
                user={operator}
            />
        );
    }
    if (operator.type === "app_user") {
        return (
            <AdminUserIdentity
                openInAppUserDetail
                name={operator.name}
                rows={[operator.displayUserId, operator.userId]}
                user={operator}
            />
        );
    }
    return <span className="muted">system</span>;
}

function UserStatus({ status }) {
    return (
        <span className="status-badge status-badge--danger">
            <span className="status-point" />
            {appUserStatusLabels[status] || status || "-"}
        </span>
    );
}
