import { useCallback, useEffect, useState } from "react";
import { parseForm } from "@/shared/forms/validation";
import { useAdminQuery } from "@/shared/hooks/useAdminQuery.js";
import { useToast } from "@/shared/ui/ToastProvider.jsx";
import { getRiskConfig, updateRiskConfig } from "@/features/risk-config/api";
import { useRiskConfigAbilities } from "@/features/risk-config/permissions.js";
import { riskConfigSchema } from "@/features/risk-config/schema";

const emptyData = {
    appCode: "",
    maxAccountsPerDevice: 1,
    updatedAtMs: 0,
    updatedByAdminId: 0,
};

export function useRiskConfigPage() {
    const abilities = useRiskConfigAbilities();
    const { showToast } = useToast();
    const [form, setForm] = useState(emptyData);
    const [loadingAction, setLoadingAction] = useState("");
    const queryFn = useCallback(() => getRiskConfig(), []);
    const {
        data = emptyData,
        error,
        loading,
        reload,
    } = useAdminQuery(queryFn, {
        errorMessage: "加载风控配置失败",
        initialData: emptyData,
        queryKey: ["risk-config", "register"],
    });

    useEffect(() => {
        if (!data) {
            return;
        }
        setForm({
            appCode: data.appCode || "",
            maxAccountsPerDevice: Number(data.maxAccountsPerDevice || 1),
            updatedAtMs: Number(data.updatedAtMs || 0),
            updatedByAdminId: Number(data.updatedByAdminId || 0),
        });
    }, [data]);

    const changeMaxAccountsPerDevice = (value) => {
        setForm((current) => ({ ...current, maxAccountsPerDevice: value }));
    };

    const submitConfig = async (event) => {
        event.preventDefault();
        setLoadingAction("save");
        try {
            const payload = parseForm(riskConfigSchema, {
                maxAccountsPerDevice: form.maxAccountsPerDevice,
            });
            const saved = await updateRiskConfig({
                max_accounts_per_device: payload.maxAccountsPerDevice,
            });
            setForm(saved);
            await reload();
            showToast("风控配置已保存", "success");
        } catch (err) {
            showToast(err.message || "保存失败", "error");
        } finally {
            setLoadingAction("");
        }
    };

    return {
        abilities,
        changeMaxAccountsPerDevice,
        data,
        error,
        form,
        loading,
        loadingAction,
        reload,
        submitConfig,
    };
}
