import { useCallback, useEffect, 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 { getRoomConfig, updateRoomConfig } from "@/features/rooms/api";
import { useRoomAbilities } from "@/features/rooms/permissions.js";
import { roomConfigSchema } from "@/features/rooms/schema";

const fallbackCandidates = [10, 15, 20, 25, 30];
const emptyData = {
    allowedSeatCounts: fallbackCandidates,
    candidateSeatCounts: fallbackCandidates,
    defaultSeatCount: 15,
    updatedAtMs: 0,
};

export function useRoomConfigPage() {
    const abilities = useRoomAbilities();
    const { showToast } = useToast();
    const [form, setForm] = useState(emptyData);
    const [loadingAction, setLoadingAction] = useState("");
    const queryFn = useCallback(() => getRoomConfig(), []);
    const {
        data = emptyData,
        error,
        loading,
        reload,
    } = useAdminQuery(queryFn, {
        errorMessage: "加载房间配置失败",
        initialData: emptyData,
        queryKey: ["rooms", "config"],
    });

    useEffect(() => {
        if (!data) {
            return;
        }
        setForm({
            allowedSeatCounts: normalizeNumbers(data.allowedSeatCounts),
            candidateSeatCounts: normalizeNumbers(data.candidateSeatCounts),
            defaultSeatCount: Number(data.defaultSeatCount || 15),
            updatedAtMs: data.updatedAtMs || 0,
        });
    }, [data]);

    const allowedSet = useMemo(() => new Set(form.allowedSeatCounts), [form.allowedSeatCounts]);

    const toggleSeatCount = (seatCount) => {
        setForm((current) => {
            const currentAllowed = new Set(current.allowedSeatCounts);
            if (currentAllowed.has(seatCount)) {
                currentAllowed.delete(seatCount);
            } else {
                currentAllowed.add(seatCount);
            }
            const allowedSeatCounts = [...currentAllowed].sort((left, right) => left - right);
            const defaultSeatCount = allowedSeatCounts.includes(current.defaultSeatCount)
                ? current.defaultSeatCount
                : (allowedSeatCounts[0] ?? current.defaultSeatCount);
            return { ...current, allowedSeatCounts, defaultSeatCount };
        });
    };

    const changeDefaultSeatCount = (value) => {
        setForm((current) => ({ ...current, defaultSeatCount: Number(value) }));
    };

    const submitConfig = async (event) => {
        event.preventDefault();
        setLoadingAction("save");
        try {
            const payload = parseForm(roomConfigSchema, {
                allowedSeatCounts: form.allowedSeatCounts,
                defaultSeatCount: form.defaultSeatCount,
            });
            const saved = await updateRoomConfig(payload);
            setForm({
                allowedSeatCounts: normalizeNumbers(saved.allowedSeatCounts),
                candidateSeatCounts: normalizeNumbers(saved.candidateSeatCounts),
                defaultSeatCount: Number(saved.defaultSeatCount || 15),
                updatedAtMs: saved.updatedAtMs || 0,
            });
            await reload();
            showToast("房间配置已保存", "success");
        } catch (err) {
            showToast(err.message || "保存失败", "error");
        } finally {
            setLoadingAction("");
        }
    };

    return {
        abilities,
        allowedSet,
        changeDefaultSeatCount,
        data,
        error,
        form,
        loading,
        loadingAction,
        reload,
        submitConfig,
        toggleSeatCount,
    };
}

function normalizeNumbers(values) {
    return Array.isArray(values) ? values.map((value) => Number(value)).filter(Number.isFinite) : [];
}
