import { useCallback, useEffect, useMemo, useState } from "react";
import { getRoomWhitelistConfig, updateRoomWhitelistConfig } from "@/features/rooms/api";
import { useRoomAbilities } from "@/features/rooms/permissions.js";
import { roomWhitelistSchema } from "@/features/rooms/schema";
import { parseForm } from "@/shared/forms/validation";
import { useAdminQuery } from "@/shared/hooks/useAdminQuery.js";
import { useToast } from "@/shared/ui/ToastProvider.jsx";

const emptyData = {
    updatedAtMs: 0,
    userIds: [],
};

export function useRoomWhitelistPage() {
    const abilities = useRoomAbilities();
    const { showToast } = useToast();
    const [text, setText] = useState("");
    const [loadingAction, setLoadingAction] = useState("");
    const queryFn = useCallback(() => getRoomWhitelistConfig(), []);
    const {
        data = emptyData,
        error,
        loading,
        reload,
    } = useAdminQuery(queryFn, {
        errorMessage: "加载房间白名单失败",
        initialData: emptyData,
        queryKey: ["rooms", "whitelist"],
    });

    useEffect(() => {
        setText(normalizeUserIds(data?.userIds).join("\n"));
    }, [data]);

    const userIds = useMemo(() => normalizeUserIds(splitUserIds(text)), [text]);

    const submitWhitelist = async (event) => {
        event.preventDefault();
        setLoadingAction("save");
        try {
            const payload = parseForm(roomWhitelistSchema, { userIds });
            const saved = await updateRoomWhitelistConfig(payload);
            setText(normalizeUserIds(saved.userIds).join("\n"));
            await reload();
            showToast("房间白名单已保存", "success");
        } catch (err) {
            showToast(err.message || "保存失败", "error");
        } finally {
            setLoadingAction("");
        }
    };

    return {
        abilities,
        data,
        error,
        loading,
        loadingAction,
        reload,
        setText,
        submitWhitelist,
        text,
        userIds,
    };
}

function splitUserIds(value) {
    return String(value || "")
        .split(/[\s,，;；]+/)
        .map((item) => item.trim())
        .filter(Boolean);
}

function normalizeUserIds(values) {
    return Array.isArray(values) ? [...new Set(values.map((value) => String(value).trim()).filter(Boolean))] : [];
}
