import { useEffect, useMemo, useState } from "react";
import { useCountryOptions } from "@/features/host-org/hooks/useCountryOptions.js";
import { listGifts } from "@/features/resources/api";
import {
    createRobotRoom,
    getHumanRoomRobotConfig,
    listAvailableRoomRobots,
    listRobotRooms,
    startRobotRoom,
    stopRobotRoom,
    updateHumanRoomRobotConfig,
} from "@/features/rooms/api";
import { useRoomAbilities } from "@/features/rooms/permissions.js";
import { humanRoomRobotConfigSchema, robotRoomCreateSchema } from "@/features/rooms/schema";
import { parseForm } from "@/shared/forms/validation";
import { useRegionOptions } from "@/shared/hooks/useRegionOptions.js";
import { usePaginatedQuery } from "@/shared/hooks/usePaginatedQuery.js";
import { useToast } from "@/shared/ui/ToastProvider.jsx";

const pageSize = 50;
const emptyData = { items: [], page: 1, pageSize, total: 0 };

function emptyForm() {
    return {
        candidateRobotUserIds: [],
        giftIds: [],
        luckyComboMax: "10000",
        luckyComboMin: "100",
        luckyGiftIds: [],
        luckyPauseMaxMs: "20000",
        luckyPauseMinMs: "5000",
        maxGiftSenders: "1",
        maxRobotCount: "8",
        minRobotCount: "6",
        normalGiftIntervalMs: "10000",
        ownerRobotUserId: "",
        robotReplaceMaxMs: "60000",
        robotReplaceMinMs: "0",
        robotStayMaxMs: "600000",
        robotStayMinMs: "180000",
        seatCount: "10",
        visibleRegionId: 0,
    };
}

function emptyHumanConfigForm() {
    return {
        candidateRoomMaxOnline: "5",
        countryLimitEnabled: false,
        countryRules: [],
        enabled: false,
        giftIds: [],
        luckyComboMax: "3",
        luckyComboMin: "1",
        luckyGiftIds: [],
        luckyPauseMaxMs: "20000",
        luckyPauseMinMs: "5000",
        maxGiftSenders: "1",
        normalGiftIntervalMaxMs: "20000",
        normalGiftIntervalMinMs: "1000",
        robotReplaceMaxMs: "180000",
        robotReplaceMinMs: "60000",
        robotStayMaxMs: "600000",
        robotStayMinMs: "60000",
        roomTargetMaxOnline: "10",
        roomTargetMinOnline: "8",
        superLuckyGiftIds: [],
    };
}

function emptyHumanCountryRule(countryOptions = [], existingRules = []) {
    return {
        allowedOwnerIds: "",
        countryCode: firstAvailableCountryCode(countryOptions, existingRules),
        maxRoomCount: "1",
    };
}

export function useRobotRoomsPage() {
    const abilities = useRoomAbilities();
    const { countryOptions, loadingCountries } = useCountryOptions();
    const { loadingRegions, regionOptions } = useRegionOptions();
    const { showToast } = useToast();
    const [activeAction, setActiveAction] = useState("");
    const [availableRobotsState, setAvailableRobotsState] = useState({ error: "", loading: false, options: [] });
    const [form, setForm] = useState(emptyForm);
    const [giftOptionsState, setGiftOptionsState] = useState({ error: "", loading: false, options: [] });
    const [humanConfigState, setHumanConfigState] = useState({ config: null, error: "", loading: false });
    const [humanConfigForm, setHumanConfigForm] = useState(emptyHumanConfigForm);
    const [loadingAction, setLoadingAction] = useState("");
    const [page, setPage] = useState(1);
    const [status, setStatus] = useState("active");
    const filters = useMemo(() => ({ status }), [status]);
    const {
        data = emptyData,
        error,
        loading,
        reload,
    } = usePaginatedQuery({
        errorMessage: "加载机器人房间列表失败",
        fetcher: listRobotRooms,
        filters,
        page,
        pageSize,
        queryKey: ["robot-rooms", filters, page],
    });

    const loadAvailableRobots = async () => {
        setAvailableRobotsState((current) => ({ ...current, error: "", loading: true }));
        try {
            const options = await listAvailableRoomRobots();
            setAvailableRobotsState({ error: "", loading: false, options: options || [] });
        } catch (err) {
            setAvailableRobotsState({ error: err.message || "加载可用机器人失败", loading: false, options: [] });
        }
    };

    const loadGiftOptions = async () => {
        setGiftOptionsState((current) => ({ ...current, error: "", loading: true }));
        try {
            const result = await listGifts({ page: 1, page_size: 200, status: "active" });
            setGiftOptionsState({ error: "", loading: false, options: result?.items || [] });
        } catch (err) {
            setGiftOptionsState({ error: err.message || "加载礼物列表失败", loading: false, options: [] });
        }
    };

    const loadHumanConfig = async () => {
        setHumanConfigState((current) => ({ ...current, error: "", loading: true }));
        try {
            const config = await getHumanRoomRobotConfig();
            setHumanConfigState({ config, error: "", loading: false });
            setHumanConfigForm(humanConfigToForm(config));
        } catch (err) {
            setHumanConfigState({ config: null, error: err.message || "加载真人房间机器人配置失败", loading: false });
        }
    };

    useEffect(() => {
        loadHumanConfig();
    }, []);

    useEffect(() => {
        if (activeAction === "create") {
            loadAvailableRobots();
            loadGiftOptions();
        }
        if (activeAction === "human-config") {
            loadGiftOptions();
        }
    }, [activeAction]);

    useEffect(() => {
        if (activeAction !== "create") {
            return;
        }
        const ownerRobotUserId = String(form.ownerRobotUserId || "");
        const ids = availableRobotsState.options
            .map((item) => item.userId)
            .filter((userId) => userId && String(userId) !== ownerRobotUserId);
        setForm((current) => {
            const currentIds = (current.candidateRobotUserIds || []).map(String);
            if (currentIds.join(",") === ids.map(String).join(",")) {
                return current;
            }
            return { ...current, candidateRobotUserIds: ids };
        });
    }, [activeAction, availableRobotsState.options, form.ownerRobotUserId]);

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

    const resetFilters = () => {
        setStatus("active");
        setPage(1);
    };

    const openCreate = () => {
        setActiveAction("create");
        setForm(emptyForm());
        setAvailableRobotsState({ error: "", loading: false, options: [] });
        setGiftOptionsState({ error: "", loading: false, options: [] });
    };

    const openHumanConfig = () => {
        setActiveAction("human-config");
        setHumanConfigForm(humanConfigToForm(humanConfigState.config));
    };

    const openHumanCountryConfig = () => {
        const form = humanConfigToForm(humanConfigState.config);
        setActiveAction("human-config");
        setHumanConfigForm({
            ...form,
            countryLimitEnabled: true,
            countryRules: form.countryRules.length ? form.countryRules : [emptyHumanCountryRule(countryOptions)],
        });
    };

    const closeAction = () => {
        setActiveAction("");
    };

    const submitCreate = async (event) => {
        event.preventDefault();
        await runAction("create", "机器人房间已创建", async () => {
            const payload = parseForm(robotRoomCreateSchema, form);
            await createRobotRoom(payload);
            closeAction();
            await reload();
        });
    };

    const setRoomStatus = async (room) => {
        if (!room?.roomId || !abilities.canRobotUpdate) {
            return;
        }
        const nextActive = room.status !== "active";
        await runAction(`status-${room.roomId}`, nextActive ? "机器人房间已启动" : "机器人房间已停止", async () => {
            if (nextActive) {
                await startRobotRoom(room.roomId);
            } else {
                await stopRobotRoom(room.roomId);
            }
            await reload();
        });
    };

    const selectOwnerRobot = (robot) => {
        const ownerRobotUserId = robot?.userId || "";
        setForm((current) => ({
            ...current,
            ownerRobotUserId,
            candidateRobotUserIds: (current.candidateRobotUserIds || []).filter(
                (userId) => String(userId) !== String(ownerRobotUserId),
            ),
        }));
    };

    const selectGiftIds = (key, gifts) => {
        setForm((current) => ({ ...current, [key]: gifts.map(giftId).filter(Boolean) }));
    };

    const selectHumanGiftIds = (key, gifts) => {
        setHumanConfigForm((current) => ({ ...current, [key]: gifts.map(giftId).filter(Boolean) }));
    };

    const setHumanCountryLimitEnabled = (enabled) => {
        setHumanConfigForm((current) => ({
            ...current,
            countryLimitEnabled: enabled,
            countryRules:
                enabled && current.countryRules.length === 0
                    ? [emptyHumanCountryRule(countryOptions, current.countryRules)]
                    : current.countryRules,
        }));
    };

    const addHumanCountryRule = () => {
        setHumanConfigForm((current) => ({
            ...current,
            countryLimitEnabled: true,
            countryRules: [...current.countryRules, emptyHumanCountryRule(countryOptions, current.countryRules)],
        }));
    };

    const updateHumanCountryRule = (index, patch) => {
        setHumanConfigForm((current) => ({
            ...current,
            countryRules: current.countryRules.map((rule, currentIndex) =>
                currentIndex === index ? { ...rule, ...patch } : rule,
            ),
        }));
    };

    const removeHumanCountryRule = (index) => {
        setHumanConfigForm((current) => ({
            ...current,
            countryRules: current.countryRules.filter((_, currentIndex) => currentIndex !== index),
        }));
    };

    const submitHumanConfig = async (event) => {
        event.preventDefault();
        await runAction("human-config", "真人房间机器人配置已保存", async () => {
            const payload = parseForm(humanRoomRobotConfigSchema, humanConfigForm);
            const config = await updateHumanRoomRobotConfig(payload);
            setHumanConfigState({ config, error: "", loading: false });
            setHumanConfigForm(humanConfigToForm(config));
            closeAction();
        });
    };

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

    const selectedOwnerRobot = useMemo(
        () => availableRobotsState.options.find((item) => item.userId === String(form.ownerRobotUserId)) || null,
        [availableRobotsState.options, form.ownerRobotUserId],
    );
    const countryLabels = useMemo(
        () => Object.fromEntries(countryOptions.map((option) => [option.value, option.label])),
        [countryOptions],
    );
    const regionLabels = useMemo(
        () => Object.fromEntries(regionOptions.map((option) => [option.value, option.label])),
        [regionOptions],
    );
    const selectedGiftOptions = useMemo(() => {
        const selected = new Set((form.giftIds || []).map(String));
        return giftOptionsState.options.filter((item) => selected.has(giftId(item)));
    }, [form.giftIds, giftOptionsState.options]);
    const selectedLuckyGiftOptions = useMemo(() => {
        const selected = new Set((form.luckyGiftIds || []).map(String));
        return giftOptionsState.options.filter((item) => selected.has(giftId(item)));
    }, [form.luckyGiftIds, giftOptionsState.options]);
    const selectedHumanGiftOptions = useMemo(
        () => ({
            giftIds: giftOptionsState.options.filter((item) =>
                new Set((humanConfigForm.giftIds || []).map(String)).has(giftId(item)),
            ),
            luckyGiftIds: giftOptionsState.options.filter((item) =>
                new Set((humanConfigForm.luckyGiftIds || []).map(String)).has(giftId(item)),
            ),
            superLuckyGiftIds: giftOptionsState.options.filter((item) =>
                new Set((humanConfigForm.superLuckyGiftIds || []).map(String)).has(giftId(item)),
            ),
        }),
        [
            giftOptionsState.options,
            humanConfigForm.giftIds,
            humanConfigForm.luckyGiftIds,
            humanConfigForm.superLuckyGiftIds,
        ],
    );

    return {
        abilities,
        activeAction,
        availableRobotsError: availableRobotsState.error,
        availableRobotsLoading: availableRobotsState.loading,
        availableRobots: availableRobotsState.options,
        changeStatus,
        closeAction,
        countryOptions,
        data,
        error,
        form,
        giftOptions: giftOptionsState.options,
        giftOptionsError: giftOptionsState.error,
        giftOptionsLoading: giftOptionsState.loading,
        humanConfig: humanConfigState.config,
        humanConfigError: humanConfigState.error,
        humanConfigForm,
        humanConfigLoading: humanConfigState.loading,
        loading,
        loadingAction,
        loadingRobotLocationOptions: loadingCountries || loadingRegions,
        addHumanCountryRule,
        openCreate,
        openHumanCountryConfig,
        openHumanConfig,
        page,
        reload,
        resetFilters,
        selectGiftIds,
        selectHumanGiftIds,
        selectOwnerRobot,
        selectedGiftOptions,
        selectedLuckyGiftOptions,
        selectedHumanGiftOptions,
        selectedOwnerRobot,
        robotCountryLabels: countryLabels,
        robotRegionLabels: regionLabels,
        setForm,
        setHumanCountryLimitEnabled,
        setHumanConfigForm,
        setPage,
        setRoomStatus,
        status,
        submitCreate,
        submitHumanConfig,
        updateHumanCountryRule,
        removeHumanCountryRule,
    };
}

function humanConfigToForm(config = null) {
    const defaults = emptyHumanConfigForm();
    if (!config) {
        return defaults;
    }
    return {
        ...defaults,
        candidateRoomMaxOnline: String(config.candidateRoomMaxOnline ?? defaults.candidateRoomMaxOnline),
        countryLimitEnabled: Boolean(config.countryLimitEnabled),
        countryRules: (config.countryRules || []).map((rule) => ({
            allowedOwnerIds: (rule.allowedOwnerIds || []).map(String).join(","),
            countryCode: String(rule.countryCode || "").toUpperCase(),
            maxRoomCount: String(rule.maxRoomCount ?? "1"),
        })),
        enabled: Boolean(config.enabled),
        giftIds: (config.giftIds || []).map(String),
        luckyComboMax: String(config.luckyComboMax ?? defaults.luckyComboMax),
        luckyComboMin: String(config.luckyComboMin ?? defaults.luckyComboMin),
        luckyGiftIds: (config.luckyGiftIds || []).map(String),
        luckyPauseMaxMs: String(config.luckyPauseMaxMs ?? defaults.luckyPauseMaxMs),
        luckyPauseMinMs: String(config.luckyPauseMinMs ?? defaults.luckyPauseMinMs),
        maxGiftSenders: String(config.maxGiftSenders ?? defaults.maxGiftSenders),
        normalGiftIntervalMaxMs: String(
            config.normalGiftIntervalMaxMs ?? config.normalGiftIntervalMs ?? defaults.normalGiftIntervalMaxMs,
        ),
        normalGiftIntervalMinMs: String(
            config.normalGiftIntervalMinMs ?? config.normalGiftIntervalMs ?? defaults.normalGiftIntervalMinMs,
        ),
        robotReplaceMaxMs: String(config.robotReplaceMaxMs ?? defaults.robotReplaceMaxMs),
        robotReplaceMinMs: String(config.robotReplaceMinMs ?? defaults.robotReplaceMinMs),
        robotStayMaxMs: String(config.robotStayMaxMs ?? defaults.robotStayMaxMs),
        robotStayMinMs: String(config.robotStayMinMs ?? defaults.robotStayMinMs),
        roomTargetMaxOnline: String(
            config.roomTargetMaxOnline ?? config.roomFullStopOnline ?? defaults.roomTargetMaxOnline,
        ),
        roomTargetMinOnline: String(
            config.roomTargetMinOnline ?? config.roomFullStopOnline ?? defaults.roomTargetMinOnline,
        ),
        superLuckyGiftIds: (config.superLuckyGiftIds || []).map(String),
    };
}

function firstAvailableCountryCode(countryOptions = [], existingRules = []) {
    const used = new Set(existingRules.map((rule) => String(rule.countryCode || "").toUpperCase()).filter(Boolean));
    const option = countryOptions.find((country) => country.value && !used.has(String(country.value).toUpperCase()));
    return option?.value || "";
}

export function robotOptionLabel(robot) {
    if (!robot) {
        return "";
    }
    const user = robot.user || {};
    return [user.username, user.displayUserId, robot.userId].filter(Boolean).join(" / ");
}

export function robotLocationLabel(robot, countryLabels = {}, regionLabels = {}) {
    const user = robot?.user || {};
    const countryCode = String(user.countryCode || "")
        .trim()
        .toUpperCase();
    const regionId = user.visibleRegionId || "";
    const countryLabel = countryCode ? countryLabels[countryCode] || countryCode : "国家 -";
    const regionKey = regionId ? String(regionId) : "";
    const regionLabel = regionKey ? regionLabels[regionKey] || `区域 ${regionKey}` : "区域 -";
    return `${countryLabel} / ${regionLabel}`;
}

export function giftId(gift) {
    return String(gift?.giftId || "");
}

export function giftOptionLabel(gift) {
    if (!gift) {
        return "";
    }
    return [gift.name, gift.giftId].filter(Boolean).join(" / ");
}
