import { useCallback, useMemo, useState } from "react";
import { parseForm } from "@/shared/forms/validation";
import { useAdminQuery } from "@/shared/hooks/useAdminQuery.js";
import { useToast } from "@/shared/ui/ToastProvider.jsx";
import { createTeam, listTeams, OPERATION_TEAM_ID, updateTeam } from "@/features/teams/api";
import { useTeamAbilities } from "@/features/teams/permissions.js";
import { teamFormSchema } from "@/features/teams/schema";

const emptyForm = { description: "", name: "", parentId: "", sort: 0 };

export function useTeamsPage() {
    const [query, setQuery] = useState("");
    const [drawerOpen, setDrawerOpen] = useState(false);
    const [editingTeam, setEditingTeam] = useState(null);
    const [form, setForm] = useState(emptyForm);
    const abilities = useTeamAbilities();
    const { showToast } = useToast();

    const queryFn = useCallback(() => listTeams(), []);
    const { data, error, loading, reload } = useAdminQuery(queryFn, {
        errorMessage: "加载团队失败",
        initialData: [],
        keepPreviousData: true,
        queryKey: ["teams"],
    });

    const allTeams = useMemo(() => flattenTeams(data), [data]);

    const teams = useMemo(() => {
        const keyword = query.trim().toLowerCase();
        const items = allTeams;
        if (!keyword) {
            return items;
        }
        return items.filter((team) =>
            [team.id, team.name, team.parentName, team.description].some((value) =>
                String(value || "")
                    .toLowerCase()
                    .includes(keyword),
            ),
        );
    }, [allTeams, query]);

    const parentOptions = useMemo(
        () => allTeams.filter((team) => !team.parentId && (!editingTeam || String(team.id) !== String(editingTeam.id))),
        [allTeams, editingTeam],
    );

    const openCreate = (parentTeam) => {
        setEditingTeam(null);
        setForm({ ...emptyForm, parentId: parentTeam?.id || "" });
        setDrawerOpen(true);
    };

    const openEdit = (team) => {
        setEditingTeam(team);
        setForm({
            description: team.description || "",
            name: team.name || "",
            parentId: team.parentId || "",
            sort: Number(team.sort || 0),
        });
        setDrawerOpen(true);
    };

    const closeDrawer = () => {
        setDrawerOpen(false);
    };

    const submit = async (event) => {
        event.preventDefault();
        try {
            const payload = parseForm(teamFormSchema, form);
            if (editingTeam) {
                await updateTeam(editingTeam.id, payload);
                showToast("团队已更新", "success");
            } else {
                await createTeam(payload);
                showToast("团队已创建", "success");
            }
            setDrawerOpen(false);
            reload();
        } catch (err) {
            showToast(err.message || "保存团队失败", "error");
        }
    };

    return {
        abilities,
        closeDrawer,
        drawerOpen,
        editingTeam,
        error,
        form,
        loading,
        openCreate,
        openEdit,
        operationTeamId: OPERATION_TEAM_ID,
        parentOptions,
        query,
        reload,
        setForm,
        setQuery,
        submit,
        teams,
    };
}

function flattenTeams(data) {
    const items = Array.isArray(data) ? data : [];
    const seen = new Set();
    const flattened = [];
    items.forEach((team) => {
        appendTeam(flattened, seen, team);
        (team.children || []).forEach((child) => {
            appendTeam(flattened, seen, {
                ...child,
                parentId: child.parentId ?? team.id,
                parentName: child.parentName || team.name,
            });
        });
    });
    return flattened;
}

function appendTeam(target, seen, team) {
    if (!team?.id || seen.has(String(team.id))) {
        return;
    }
    seen.add(String(team.id));
    target.push(team);
}
