import { useCallback, useEffect, 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 {
    createBD,
    createBDLeader,
    deleteBDLeader,
    listBDLeaders,
    listBDs,
    setBDLeaderStatus,
    setBDStatus,
    updateBDLeaderPositionAlias,
} from "@/features/host-org/api";
import { listAppUsers } from "@/features/app-users/api";
import { useRegionOptions } from "@/shared/hooks/useRegionOptions.js";
import { emptyUserIdentityFilter, userIdentityFilterParams } from "@/shared/ui/userIdentityFilter.js";
import { useBDAbilities } from "@/features/host-org/permissions.js";
import { createBDSchema, createBDLeaderSchema } from "@/features/host-org/schema";

const emptyBDLeaderForm = () => ({
    commandId: makeCommandId("bd-leader"),
    positionAlias: "",
    reason: "",
    targetUserId: "",
});
const emptyBDForm = () => ({ commandId: makeCommandId("bd"), parentLeaderUserId: "", reason: "", targetUserId: "" });
const pageSize = 50;
const emptyData = { items: [], page: 1, pageSize, total: 0 };
const emptyLookup = () => ({ error: "", loading: false, user: null });

export function useHostBdsPage({ profileType = "bd" } = {}) {
    const abilities = useBDAbilities();
    const confirm = useConfirm();
    const { showToast } = useToast();
    const { loadingRegions, regionOptions } = useRegionOptions();
    const [userFilter, setUserFilter] = useState(emptyUserIdentityFilter);
    const [status, setStatus] = useState("");
    const [regionId, setRegionId] = useState("");
    const [parentLeaderFilter, setParentLeaderFilter] = useState(emptyUserIdentityFilter);
    const [sortBy, setSortBy] = useState("");
    const [sortDirection, setSortDirection] = useState("");
    const [page, setPage] = useState(1);
    const [bdLeaderForm, setBDLeaderForm] = useState(emptyBDLeaderForm);
    const [bdForm, setBDForm] = useState(emptyBDForm);
    const [bdUserLookup, setBDUserLookup] = useState(emptyLookup);
    const [leaderBDs, setLeaderBDs] = useState(emptyData);
    const [leaderBDsError, setLeaderBDsError] = useState("");
    const [leaderBDsLoading, setLeaderBDsLoading] = useState(false);
    const [selectedLeader, setSelectedLeader] = useState(null);
    const [loadingAction, setLoadingAction] = useState("");
    const [activeAction, setActiveAction] = useState("");
    const [profileOverrides, setProfileOverrides] = useState({});
    const filters = useMemo(
        () => ({
            region_id: regionId,
            sort_by: sortBy,
            sort_direction: sortDirection,
            status,
            ...userIdentityFilterParams(userFilter),
            ...(profileType === "bd"
                ? userIdentityFilterParams(parentLeaderFilter, {
                      displayUserId: "parent_leader_display_user_id",
                      userId: "parent_leader_user_id",
                      username: "parent_leader_username",
                  })
                : {}),
        }),
        [parentLeaderFilter, profileType, regionId, sortBy, sortDirection, status, userFilter],
    );
    const fetcher = profileType === "bd" ? listBDs : listBDLeaders;
    const {
        data = emptyData,
        error,
        loading,
        reload,
    } = usePaginatedQuery({
        errorMessage: profileType === "leader" ? "加载 BD Leader 列表失败" : "加载 BD 列表失败",
        fetcher,
        filters,
        page,
        pageSize,
        queryKey: ["host-org", "bds", profileType, filters, page],
    });
    const displayData = useMemo(
        () => ({
            ...data,
            items: (data.items || []).map((item) => ({
                ...item,
                ...(profileOverrides[String(item.userId)] || {}),
            })),
        }),
        [data, profileOverrides],
    );

    const loadLeaderBDs = useCallback(async (leader) => {
        if (!leader?.userId) {
            setLeaderBDs(emptyData);
            return;
        }
        setLeaderBDsError("");
        setLeaderBDsLoading(true);
        try {
            const data = await listBDs({
                page: 1,
                page_size: 100,
                parent_leader_user_id: leader.userId,
            });
            setLeaderBDs(data || emptyData);
        } catch (err) {
            setLeaderBDsError(err.message || "加载下级 BD 失败");
        } finally {
            setLeaderBDsLoading(false);
        }
    }, []);

    useEffect(() => {
        if (activeAction !== "leader-add-bd") {
            return undefined;
        }

        const keyword = String(bdForm.targetUserId || "").trim();
        if (!keyword) {
            setBDUserLookup(emptyLookup());
            return undefined;
        }

        let cancelled = false;
        const timer = window.setTimeout(async () => {
            setBDUserLookup({ error: "", loading: true, user: null });
            try {
                const data = await listAppUsers({ keyword, page: 1, page_size: 5 });
                if (cancelled) {
                    return;
                }
                setBDUserLookup({ error: "", loading: false, user: pickUserMatch(data?.items || [], keyword) });
            } catch (err) {
                if (cancelled) {
                    return;
                }
                setBDUserLookup({ error: err.message || "搜索用户失败", loading: false, user: null });
            }
        }, 300);

        return () => {
            cancelled = true;
            window.clearTimeout(timer);
        };
    }, [activeAction, bdForm.targetUserId]);

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

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

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

    const changeParentLeaderFilter = (value) => {
        setParentLeaderFilter(value);
        setPage(1);
    };

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

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

    const submitBDLeader = async (event) => {
        event.preventDefault();
        await runAction("bd-leader", "BD Leader 已创建", async () => {
            const payload = parseForm(createBDLeaderSchema, bdLeaderForm);
            const data = await createBDLeader(payload);
            setBDLeaderForm(emptyBDLeaderForm());
            setActiveAction("");
            await reload();
            return data;
        });
    };

    const submitBD = async (event) => {
        event.preventDefault();
        await runAction("bd", "BD 已创建", async () => {
            const payload = parseForm(createBDSchema, bdForm);
            const data = await createBD(payload);
            setBDForm(emptyBDForm());
            setActiveAction("");
            await reload();
            return data;
        });
    };

    const submitLeaderBD = async (event) => {
        event.preventDefault();
        await runAction("leader-add-bd", "下级 BD 已添加", async () => {
            const payload = parseForm(createBDSchema, bdForm);
            const data = await createBD(payload);
            setBDForm(emptyBDForm());
            setBDUserLookup(emptyLookup());
            setActiveAction("");
            await reload();
            return data;
        });
    };

    const toggleBDLeader = async (leader, enabled) => {
        const status = enabled ? "active" : "disabled";
        await runAction(
            `bd-leader-status-${leader.userId}`,
            enabled ? "BD Leader 已启用" : "BD Leader 已停用",
            async () => {
                const data = await setBDLeaderStatus(leader.userId, {
                    commandId: makeCommandId("bd-leader-status"),
                    reason: "",
                    status,
                });
                await reload();
                return data;
            },
        );
    };

    const toggleBD = async (bd, enabled) => {
        const status = enabled ? "active" : "disabled";
        await runAction(`bd-status-${bd.userId}`, enabled ? "BD 已启用" : "BD 已停用", async () => {
            const data = await setBDStatus(bd.userId, {
                commandId: makeCommandId("bd-status"),
                reason: "",
                status,
            });
            await reload();
            return data;
        });
    };

    const saveBDLeaderPositionAlias = useCallback(
        async (leader, rawAlias) => {
            const userId = leader?.userId;
            const positionAlias = String(rawAlias ?? "").trim();
            const currentAlias = String(leader?.positionAlias ?? "").trim();
            if (!userId || positionAlias === currentAlias) {
                return leader;
            }
            if (Array.from(positionAlias).length > 64) {
                const err = new Error("职位别名不能超过 64 个字符");
                showToast(err.message, "error");
                throw err;
            }

            try {
                const profile = await updateBDLeaderPositionAlias(userId, {
                    commandId: makeCommandId("bd-leader-position-alias"),
                    positionAlias,
                    reason: "",
                });
                setProfileOverrides((current) => ({
                    ...current,
                    [String(userId)]: {
                        ...(current[String(userId)] || {}),
                        ...(profile || {}),
                        positionAlias: profile?.positionAlias ?? positionAlias,
                    },
                }));
                showToast("职位别名已保存", "success");
                return profile;
            } catch (err) {
                showToast(err.message || "保存职位别名失败", "error");
                throw err;
            }
        },
        [showToast],
    );

    const removeBDLeader = async (leader) => {
        const ok = await confirm({
            confirmText: "删除",
            message: `确认删除 BD Leader ${leader.displayUserId || leader.userId}？删除后该身份会从列表移除。`,
            title: "删除 BD Leader",
            tone: "danger",
        });
        if (!ok) {
            return;
        }

        await runAction(`bd-leader-delete-${leader.userId}`, "BD Leader 已删除", async () => {
            const data = await deleteBDLeader(leader.userId);
            await reload();
            return data;
        });
    };

    const openLeaderBDs = (leader) => {
        setSelectedLeader(leader);
        setActiveAction("leader-bds");
        void loadLeaderBDs(leader);
    };

    const openAddLeaderBD = (leader) => {
        setSelectedLeader(leader);
        setBDUserLookup(emptyLookup());
        setBDForm({
            ...emptyBDForm(),
            parentLeaderUserId: leader.displayUserId || String(leader.userId || ""),
        });
        setActiveAction("leader-add-bd");
    };

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

    const closeAction = () => {
        setActiveAction("");
        setBDUserLookup(emptyLookup());
        setLeaderBDsError("");
    };

    return {
        abilities,
        activeAction,
        bdForm,
        bdLeaderForm,
        bdUserLookup,
        changeParentLeaderFilter,
        changeRegionId,
        changeStatus,
        changeUserFilter,
        data: displayData,
        error,
        loading,
        loadingAction,
        loadingRegions,
        leaderBDs,
        leaderBDsError,
        leaderBDsLoading,
        page,
        parentLeaderFilter,
        profileType,
        regionId,
        regionOptions,
        reload,
        removeBDLeader,
        resetFilters,
        saveBDLeaderPositionAlias,
        closeAction,
        loadLeaderBDs: () => loadLeaderBDs(selectedLeader),
        openAddLeaderBD,
        openBDForm: () => setActiveAction("bd"),
        openBDLeaderForm: () => setActiveAction("bd-leader"),
        openLeaderBDs,
        selectedLeader,
        setBDForm,
        setBDLeaderForm,
        setPage,
        sortBy,
        sortDirection,
        status,
        submitBD,
        submitBDLeader,
        submitLeaderBD,
        changeSort,
        toggleBD,
        toggleBDLeader,
        userFilter,
    };
}

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

function pickUserMatch(items, keyword) {
    const normalized = String(keyword || "").trim();
    return (
        items.find(
            (item) => String(item.displayUserId || "") === normalized || String(item.userId || "") === normalized,
        ) ||
        items[0] ||
        null
    );
}
