import { useCallback, useEffect, useMemo, useState } from "react";
import { downloadCsv } from "@/shared/api/download";
import { toPageQuery } from "@/shared/api/query";
import { useAdminQuery } from "@/shared/hooks/useAdminQuery.js";
import { mergePaginatedItems } from "@/shared/hooks/usePaginatedQuery.js";
import { exportLoginLogs, exportOperationLogs, listLoginLogs, listOperationLogs } from "@/features/logs/api";
import { useLogAbilities } from "@/features/logs/permissions.js";

const pageSize = 50;
const emptyData = { items: [], total: 0, page: 1, pageSize };

export function useLogsPage(type) {
    const [query, setQuery] = useState("");
    const [page, setPage] = useState(1);
    const [mergedData, setMergedData] = useState(emptyData);
    const abilities = useLogAbilities();
    const isLogin = type === "login";

    const requestQuery = useMemo(() => toPageQuery({ keyword: query, page, pageSize }), [page, query]);
    const queryFn = useCallback(async () => {
        const loader = isLogin ? listLoginLogs : listOperationLogs;
        return loader(requestQuery);
    }, [isLogin, requestQuery]);

    const { data, error, loading: queryLoading, reload } = useAdminQuery(queryFn, {
        errorMessage: "加载日志失败",
        initialData: emptyData,
        keepPreviousData: true,
        queryKey: ["logs", type, requestQuery],
    });

    useEffect(() => {
        setMergedData(emptyData);
    }, [query, type]);

    useEffect(() => {
        const nextData = data || emptyData;
        const nextItems = Array.isArray(nextData.items) ? nextData.items : [];
        const nextPage = Number(nextData.page || page || 1);
        const nextPageSize = Number(nextData.pageSize || pageSize);
        const nextTotal = Number(nextData.total || 0);

        setMergedData((current) => {
            if (nextPage <= 1) {
                return { ...nextData, items: nextItems, page: nextPage, pageSize: nextPageSize, total: nextTotal };
            }

            return {
                ...nextData,
                items: mergePaginatedItems(current.items || [], nextItems),
                page: nextPage,
                pageSize: nextPageSize,
                total: nextTotal,
            };
        });
    }, [data, page]);

    const loading = queryLoading && (mergedData.items || []).length === 0;

    const changeQuery = (value) => {
        setQuery(value);
        setPage(1);
    };

    const resetFilters = () => {
        setQuery("");
        setPage(1);
    };

    const downloadLogs = () => {
        const exporter = isLogin ? exportLoginLogs : exportOperationLogs;
        const filename = isLogin ? "hyapp-login-logs.csv" : "hyapp-operation-logs.csv";
        return downloadCsv(() => exporter({ keyword: query }), filename);
    };

    return {
        abilities,
        changeQuery,
        data: mergedData,
        downloadLogs,
        error,
        isLogin,
        loading,
        page,
        query,
        reload,
        resetFilters,
        setPage,
    };
}
