import { useMemo, useState } from "react";
import { parseForm } from "@/shared/forms/validation";
import { usePaginatedQuery } from "@/shared/hooks/usePaginatedQuery.js";
import { useConfirm } from "@/shared/ui/ConfirmProvider.jsx";
import { useToast } from "@/shared/ui/ToastProvider.jsx";
import {
    adminAddAgencyHost,
    createAgency,
    deleteAgency,
    listAgencies,
    setAgencyJoinEnabled,
    setAgencyStatus,
} from "@/features/host-org/api";
import { useRegionOptions } from "@/shared/hooks/useRegionOptions.js";
import { emptyUserIdentityFilter, userIdentityFilterParams } from "@/shared/ui/userIdentityFilter.js";
import { useAgencyAbilities } from "@/features/host-org/permissions.js";
import { agencyHostAddSchema, createAgencySchema } from "@/features/host-org/schema";

const emptyAgencyForm = () => ({
    commandId: makeCommandId("agency"),
    joinEnabled: true,
    name: "",
    ownerUserId: "",
    parentBdUserId: "",
    reason: "",
});
const emptyAgencyHostForm = () => ({
    commandId: makeCommandId("agency-host"),
    targetUserId: "",
    reason: "",
});
const pageSize = 50;
const emptyData = { items: [], page: 1, pageSize, total: 0 };

export function useHostAgenciesPage() {
    const abilities = useAgencyAbilities();
    const confirm = useConfirm();
    const { showToast } = useToast();
    const { loadingRegions, regionOptions } = useRegionOptions();
    const [query, setQuery] = useState("");
    const [ownerFilter, setOwnerFilter] = useState(emptyUserIdentityFilter);
    const [status, setStatus] = useState("");
    const [regionId, setRegionId] = useState("");
    const [parentBdFilter, setParentBdFilter] = useState(emptyUserIdentityFilter);
    const [sortBy, setSortBy] = useState("");
    const [sortDirection, setSortDirection] = useState("");
    const [page, setPage] = useState(1);
    const [agencyForm, setAgencyForm] = useState(emptyAgencyForm);
    const [rowPatches, setRowPatches] = useState({});
    const [removedAgencyIds, setRemovedAgencyIds] = useState(() => new Set());
    const [loadingAction, setLoadingAction] = useState("");
    const [activeAction, setActiveAction] = useState("");
    const [activeAgency, setActiveAgency] = useState(null);
    const [agencyHostForm, setAgencyHostForm] = useState(emptyAgencyHostForm);
    const filters = useMemo(
        () => ({
            keyword: query,
            region_id: regionId,
            sort_by: sortBy,
            sort_direction: sortDirection,
            status,
            ...userIdentityFilterParams(ownerFilter, {
                displayUserId: "owner_display_user_id",
                userId: "owner_user_id",
                username: "owner_username",
            }),
            ...userIdentityFilterParams(parentBdFilter, {
                displayUserId: "parent_bd_display_user_id",
                userId: "parent_bd_user_id",
                username: "parent_bd_username",
            }),
        }),
        [ownerFilter, parentBdFilter, query, regionId, sortBy, sortDirection, status],
    );
    const {
        data = emptyData,
        error,
        loading,
        reload,
    } = usePaginatedQuery({
        errorMessage: "加载 Agency 列表失败",
        fetcher: listAgencies,
        filters,
        page,
        pageSize,
        queryKey: ["host-org", "agencies", filters, page],
    });
    const viewData = useMemo(() => {
        const rawItems = Array.isArray(data.items) ? data.items : [];
        const items = rawItems
            .filter((item) => !removedAgencyIds.has(String(item.agencyId)))
            .map((item) => ({ ...item, ...(rowPatches[String(item.agencyId)] || {}) }));
        const visibleRemovedCount = rawItems.length - items.length;

        return {
            ...data,
            items,
            total: Math.max(0, Number(data.total || 0) - visibleRemovedCount),
        };
    }, [data, removedAgencyIds, rowPatches]);

    const patchAgencyRow = (agencyId, patch) => {
        setRowPatches((current) => {
            const key = String(agencyId);
            return { ...current, [key]: { ...(current[key] || {}), ...patch } };
        });
    };

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

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

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

    const changeParentBdFilter = (value) => {
        setParentBdFilter(value);
        setPage(1);
    };

    const changeOwnerFilter = (value) => {
        setOwnerFilter(value);
        setPage(1);
    };

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

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

    const submitAgency = async (event) => {
        event.preventDefault();
        await runAction("agency", "Agency 已创建", async () => {
            const payload = parseForm(createAgencySchema, agencyForm);
            const data = await createAgency(payload);
            setAgencyForm(emptyAgencyForm());
            setActiveAction("");
            await reload();
            return data;
        });
    };

    const openAgencyHostForm = (agency) => {
        if (!agency?.agencyId || agency.status !== "active") {
            return;
        }
        setActiveAgency(agency);
        setAgencyHostForm(emptyAgencyHostForm());
        setActiveAction("agency-host");
    };

    const submitAgencyHost = async (event) => {
        event.preventDefault();
        if (!activeAgency?.agencyId) {
            return;
        }
        await runAction(`agency-host-${activeAgency.agencyId}`, "Host 已添加", async () => {
            const payload = parseForm(agencyHostAddSchema, agencyHostForm);
            const data = await adminAddAgencyHost(activeAgency.agencyId, payload);
            setAgencyHostForm(emptyAgencyHostForm());
            setActiveAgency(null);
            setActiveAction("");
            await reload();
            return data;
        });
    };

    const toggleAgencyStatusFromList = async (agency, enabled) => {
        if (!abilities.canStatus || !agency?.agencyId) {
            return;
        }
        const nextStatus = enabled ? "active" : "closed";
        if (agency.status === nextStatus || agency.status === "deleted") {
            return;
        }
        await runAction(`agency-status-${agency.agencyId}`, enabled ? "Agency 已启用" : "Agency 已关闭", async () => {
            const data = await setAgencyStatus(agency.agencyId, {
                commandId: makeCommandId("agency-status"),
                reason: enabled ? "open agency from list switch" : "close agency from list switch",
                status: nextStatus,
            });
            patchAgencyRow(
                agency.agencyId,
                agencyActionPatch(data, enabled ? { status: nextStatus } : { status: nextStatus, joinEnabled: false }),
            );
            return data;
        });
    };

    const closeAgencyFromList = async (agency) => {
        await toggleAgencyStatusFromList(agency, false);
    };

    const toggleAgencyJoinEnabledFromList = async (agency, joinEnabled) => {
        if (!abilities.canStatus || !agency?.agencyId || agency.status !== "active") {
            return;
        }
        await runAction(`agency-join-${agency.agencyId}`, "入会开关已更新", async () => {
            const data = await setAgencyJoinEnabled(agency.agencyId, {
                commandId: makeCommandId("agency-join"),
                joinEnabled,
                reason: "set agency join enabled from list switch",
            });
            patchAgencyRow(agency.agencyId, agencyActionPatch(data, { joinEnabled }));
            return data;
        });
    };

    const removeAgencyFromList = async (agency) => {
        if (!abilities.canDelete || !agency?.agencyId) {
            return;
        }
        const ok = await confirm({
            confirmText: "删除",
            message: `确认删除 Agency ${agency.name || agency.agencyId}？只删除 Agency 身份，不删除主播；下属主播会解除关联。`,
            title: "删除 Agency",
            tone: "danger",
        });
        if (!ok) {
            return;
        }

        await runAction(`agency-delete-${agency.agencyId}`, "Agency 已删除", async () => {
            const data = await deleteAgency(agency.agencyId, {
                commandId: makeCommandId("agency-delete"),
                reason: "delete agency from list",
            });
            setRemovedAgencyIds((current) => {
                const next = new Set(current);
                next.add(String(agency.agencyId));
                return next;
            });
            return data;
        });
    };

    const runAction = async (action, successMessage, submitter) => {
        setLoadingAction(action);
        try {
            await submitter();
            showToast(successMessage, "success");
        } catch (err) {
            showToast(err.message || "操作失败", "error");
        } finally {
            setLoadingAction("");
        }
    };

    return {
        abilities,
        activeAction,
        activeAgency,
        agencyForm,
        agencyHostForm,
        changeOwnerFilter,
        changeParentBdFilter,
        changeQuery,
        changeRegionId,
        changeStatus,
        closeAgencyFromList,
        data: viewData,
        error,
        loading,
        loadingAction,
        loadingRegions,
        ownerFilter,
        page,
        parentBdFilter,
        query,
        regionId,
        regionOptions,
        reload,
        resetFilters,
        closeAction: () => {
            setActiveAction("");
            setActiveAgency(null);
        },
        openAgencyForm: () => setActiveAction("agency"),
        openAgencyHostForm,
        removeAgencyFromList,
        setAgencyForm,
        setAgencyHostForm,
        setPage,
        sortBy,
        sortDirection,
        status,
        submitAgency,
        submitAgencyHost,
        changeSort,
        toggleAgencyStatusFromList,
        toggleAgencyJoinEnabledFromList,
    };
}

function makeCommandId(prefix) {
    return `${prefix}-${Date.now()}`;
}

function agencyActionPatch(data, fallback = {}) {
    const patch = { ...fallback };
    for (const key of ["activeHostCount", "status", "joinEnabled", "updatedAtMs"]) {
        if (data?.[key] !== undefined) {
            patch[key] = data[key];
        }
    }
    return patch;
}
