import { useMemo, useState } from "react";
import { usePaginatedQuery } from "@/shared/hooks/usePaginatedQuery.js";
import { listHosts } from "@/features/host-org/api";
import { useRegionOptions } from "@/shared/hooks/useRegionOptions.js";
import { useHostAbilities } from "@/features/host-org/permissions.js";

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

export function useHostHostsPage() {
    const abilities = useHostAbilities();
    const { loadingRegions, regionOptions } = useRegionOptions();
    const [query, setQuery] = useState("");
    const [status, setStatus] = useState("");
    const [regionId, setRegionId] = useState("");
    const [agencyId, setAgencyId] = useState("");
    const [sortBy, setSortBy] = useState("");
    const [sortDirection, setSortDirection] = useState("");
    const [page, setPage] = useState(1);
    const filters = useMemo(
        () => ({
            agency_id: agencyId,
            keyword: query,
            region_id: regionId,
            sort_by: sortBy,
            sort_direction: sortDirection,
            status,
        }),
        [agencyId, query, regionId, sortBy, sortDirection, status],
    );
    const {
        data = emptyData,
        error,
        loading,
        reload,
    } = usePaginatedQuery({
        errorMessage: "加载主播列表失败",
        fetcher: listHosts,
        filters,
        page,
        pageSize,
        queryKey: ["host-org", "hosts", filters, page],
    });

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

    const changeStatus = (value) => {
        setStatus(value);
        setPage(1);
    };

    const changeRegionId = (value) => {
        setRegionId(value);
        setPage(1);
    };

    const changeAgencyId = (value) => {
        setAgencyId(value);
        setPage(1);
    };

    const changeSort = (field) => {
        setSortDirection((current) => (sortBy === field ? (current === "asc" ? "desc" : "asc") : "desc"));
        setSortBy(field);
        setPage(1);
    };

    const resetFilters = () => {
        setQuery("");
        setStatus("");
        setRegionId("");
        setAgencyId("");
        setSortBy("");
        setSortDirection("");
        setPage(1);
    };

    return {
        abilities,
        agencyId,
        changeAgencyId,
        changeQuery,
        changeRegionId,
        changeStatus,
        data,
        diamondSortDirection: sortBy === "diamond" ? sortDirection : "",
        error,
        loading,
        loadingRegions,
        page,
        query,
        regionId,
        regionOptions,
        reload,
        resetFilters,
        setPage,
        sortBy,
        sortDirection,
        status,
        changeSort,
        toggleDiamondSort: () => changeSort("diamond"),
    };
}
