import { useEffect, useMemo, useState } from "react";
import { useSearchParams } from "react-router-dom";
import { usePaginatedQuery } from "@/shared/hooks/usePaginatedQuery.js";
import { listHosts } from "@/features/host-org/api";
import { useRegionOptions } from "@/shared/hooks/useRegionOptions.js";
import { emptyUserIdentityFilter, userIdentityFilterParams } from "@/shared/ui/userIdentityFilter.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 [searchParams, setSearchParams] = useSearchParams();
    const agencyIdParam = searchParams.get("agency_id") || searchParams.get("agencyId") || "";
    const [userFilter, setUserFilter] = useState(emptyUserIdentityFilter);
    const [status, setStatus] = useState("");
    const [regionId, setRegionId] = useState("");
    const [agencyId, setAgencyId] = useState(() => agencyIdParam);
    const [sortBy, setSortBy] = useState("");
    const [sortDirection, setSortDirection] = useState("");
    const [page, setPage] = useState(1);
    const filters = useMemo(
        () => ({
            agency_id: agencyId,
            region_id: regionId,
            sort_by: sortBy,
            sort_direction: sortDirection,
            status,
            ...userIdentityFilterParams(userFilter),
        }),
        [agencyId, regionId, sortBy, sortDirection, status, userFilter],
    );
    const {
        data = emptyData,
        error,
        loading,
        reload,
    } = usePaginatedQuery({
        errorMessage: "加载主播列表失败",
        fetcher: listHosts,
        filters,
        page,
        pageSize,
        queryKey: ["host-org", "hosts", filters, page],
    });

    useEffect(() => {
        if (agencyId === agencyIdParam) {
            return;
        }
        setAgencyId(agencyIdParam);
        setPage(1);
    }, [agencyId, agencyIdParam]);

    const changeUserFilter = (value) => {
        setUserFilter(value);
        setPage(1);
    };

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

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

    const syncAgencyIdSearchParam = (value) => {
        const nextSearchParams = new URLSearchParams(searchParams);
        const normalizedValue = String(value || "").trim();
        if (normalizedValue) {
            nextSearchParams.set("agency_id", normalizedValue);
            nextSearchParams.delete("agencyId");
        } else {
            nextSearchParams.delete("agency_id");
            nextSearchParams.delete("agencyId");
        }
        setSearchParams(nextSearchParams, { replace: true });
    };

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

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

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

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