import { useCallback, useEffect, useMemo, useState } from "react";
import { useAppScope } from "@/app/app-scope/AppScopeProvider.jsx";
import { createBanner, deleteBanner, listBanners, updateBanner } from "@/features/app-config/api";
import { useAppConfigAbilities } from "@/features/app-config/permissions.js";
import { appBannerSchema } from "@/features/app-config/schema";
import { useCountryOptions } from "@/features/host-org/hooks/useCountryOptions.js";
import { parseForm } from "@/shared/forms/validation";
import { useAdminQuery } from "@/shared/hooks/useAdminQuery.js";
import { useRegionOptions } from "@/shared/hooks/useRegionOptions.js";
import { useConfirm } from "@/shared/ui/ConfirmProvider.jsx";
import { useToast } from "@/shared/ui/ToastProvider.jsx";

const emptyData = { items: [], total: 0 };

const emptyForm = () => ({
    bannerType: "h5",
    countryCode: "",
    coverUrl: "",
    description: "",
    displayScopes: ["home"],
    endsAtMs: "",
    param: "",
    platform: "android",
    regionId: "",
    roomSmallImageUrl: "",
    sortOrder: "0",
    startsAtMs: "",
    status: "active",
});

export function useBannerConfigPage() {
    const { appCode } = useAppScope();
    const abilities = useAppConfigAbilities();
    const confirm = useConfirm();
    const { showToast } = useToast();
    const { countryOptions, loadingCountries } = useCountryOptions();
    const { loadingRegions, regionOptions } = useRegionOptions();
    const [keyword, setKeyword] = useState("");
    const [status, setStatus] = useState("");
    const [displayScope, setDisplayScope] = useState("");
    const [platform, setPlatform] = useState("");
    const [regionId, setRegionId] = useState("");
    const [countryCode, setCountryCode] = useState("");
    const [activeAction, setActiveAction] = useState("");
    const [editingItem, setEditingItem] = useState(null);
    const [form, setFormState] = useState(emptyForm);
    const [loadingAction, setLoadingAction] = useState("");

    const filters = useMemo(
        () => ({
            countryCode,
            displayScope,
            keyword,
            platform,
            regionId,
            status,
        }),
        [countryCode, displayScope, keyword, platform, regionId, status],
    );
    const queryFn = useCallback(() => listBanners(appCode, filters), [appCode, filters]);
    const {
        data = emptyData,
        error,
        loading,
        reload,
    } = useAdminQuery(queryFn, {
        enabled: Boolean(appCode),
        errorMessage: "加载 BANNER 配置失败",
        initialData: emptyData,
        queryKey: ["app-config", "banners", appCode, filters],
    });

    useEffect(() => {
        // 切换 App 后丢弃旧租户表单；已发出的请求仍携带旧 appCode，只会回写旧租户缓存键。
        setActiveAction("");
        setEditingItem(null);
        setFormState(emptyForm());
    }, [appCode]);

    const setForm = (patch) => {
        setFormState((current) => ({ ...current, ...patch }));
    };

    const openCreate = () => {
        setEditingItem(null);
        setFormState(emptyForm());
        setActiveAction("create");
    };

    const openEdit = (item) => {
        setEditingItem(item);
        setFormState(formFromBanner(item));
        setActiveAction("edit");
    };

    const closeDialog = () => {
        setActiveAction("");
        setEditingItem(null);
        setFormState(emptyForm());
    };

    const resetFilters = () => {
        setKeyword("");
        setStatus("");
        setDisplayScope("");
        setPlatform("");
        setRegionId("");
        setCountryCode("");
    };

    const submitBanner = async (event) => {
        event.preventDefault();
        const payload = parseForm(appBannerSchema, normalizeForm(form));
        const action = editingItem ? "edit" : "create";
        setLoadingAction(action);
        try {
            if (editingItem) {
                await updateBanner(appCode, editingItem.id, payload);
                showToast("BANNER 已更新", "success");
            } else {
                await createBanner(appCode, payload);
                showToast("BANNER 已新增", "success");
            }
            closeDialog();
            await reload();
        } catch (err) {
            showToast(err.message || "操作失败", "error");
        } finally {
            setLoadingAction("");
        }
    };

    const removeBanner = async (item) => {
        const ok = await confirm({
            confirmText: "删除",
            message: item.description || item.param || `BANNER ${item.id}`,
            title: "删除BANNER",
            tone: "danger",
        });
        if (!ok) {
            return;
        }
        setLoadingAction(`delete:${item.id}`);
        try {
            await deleteBanner(appCode, item.id);
            await reload();
            showToast("BANNER 已删除", "success");
        } catch (err) {
            showToast(err.message || "删除失败", "error");
        } finally {
            setLoadingAction("");
        }
    };

    return {
        abilities,
        activeAction,
        closeDialog,
        countryCode,
        countryOptions,
        data,
        displayScope,
        editingItem,
        error,
        form,
        keyword,
        loading,
        loadingAction,
        loadingCountries,
        loadingRegions,
        openCreate,
        openEdit,
        platform,
        regionId,
        regionOptions,
        reload,
        removeBanner,
        resetFilters,
        setCountryCode,
        setDisplayScope,
        setForm,
        setKeyword,
        setPlatform,
        setRegionId,
        setStatus,
        status,
        submitBanner,
    };
}

function normalizeForm(form) {
    const displayScopes = normalizeDisplayScopes(form.displayScopes || form.displayScope);
    return {
        ...form,
        countryCode: form.countryCode || "",
        displayScope: displayScopes[0] || "home",
        displayScopes,
        endsAtMs: form.endsAtMs || 0,
        regionId: form.regionId || 0,
        roomSmallImageUrl: displayScopes.includes("room") ? form.roomSmallImageUrl || "" : "",
        sortOrder: form.sortOrder || 0,
        startsAtMs: form.startsAtMs || 0,
    };
}

function formFromBanner(item) {
    return {
        bannerType: item.bannerType || "h5",
        countryCode: item.countryCode || "",
        coverUrl: item.coverUrl || "",
        description: item.description || "",
        displayScopes: normalizeDisplayScopes(item.displayScopes || item.displayScope),
        endsAtMs: item.endsAtMs || "",
        param: item.param || "",
        platform: item.platform || "android",
        regionId: item.regionId ? String(item.regionId) : "",
        roomSmallImageUrl: item.roomSmallImageUrl || "",
        sortOrder: String(item.sortOrder || 0),
        startsAtMs: item.startsAtMs || "",
        status: item.status || "active",
    };
}

function normalizeDisplayScopes(value) {
    const values = Array.isArray(value) ? value : String(value || "").split(",");
    const known = ["home", "room", "recharge", "me"];
    const seen = new Set(values.map((item) => String(item || "").trim()).filter(Boolean));
    const normalized = known.filter((scope) => seen.has(scope));
    return normalized.length ? normalized : ["home"];
}
