import { useMemo, useState } from "react";
import { parseForm } from "@/shared/forms/validation";
import { usePaginatedQuery } from "@/shared/hooks/usePaginatedQuery.js";
import { useRegionOptions } from "@/shared/hooks/useRegionOptions.js";
import { useToast } from "@/shared/ui/ToastProvider.jsx";
import { emptyUserIdentityFilter, userIdentityFilterParams } from "@/shared/ui/userIdentityFilter.js";
import {
    createCoinSeller,
    creditCoinSellerStock,
    debitCoinSellerStock,
    getCoinSellerSalaryRates,
    listCoinSellers,
    listCoinSellerSubSellers,
    replaceCoinSellerSalaryRates,
    setCoinSellerStatus,
} from "@/features/host-org/api";
import { useCoinSellerAbilities } from "@/features/host-org/permissions.js";
import {
    coinSellerStatusSchema,
    coinSellerStockCreditSchema,
    coinSellerStockDebitSchema,
    createCoinSellerSchema,
} from "@/features/host-org/schema";

const pageSize = 50;
const emptyData = { items: [], page: 1, pageSize, total: 0 };
const emptyCreateForm = () => ({
    canManageSubCoinSellers: true,
    commandId: makeCommandId("coin-seller"),
    contact: "",
    reason: "",
    targetUserId: "",
});
const emptyEditForm = () => ({
    canManageSubCoinSellers: true,
    commandId: makeCommandId("coin-seller-status"),
    contact: "",
    reason: "",
    status: "active",
    targetUserId: "",
});
const emptyStockForm = () => ({
    coinAmount: "",
    commandId: makeCommandId("coin-seller-stock"),
    reason: "",
    rechargeAmount: "",
    type: "usdt_purchase",
});
const emptyStockDebitForm = () => ({
    coinAmount: "",
    commandId: makeCommandId("coin-seller-stock-debit"),
    reason: "",
    rechargeAmount: "",
});
const emptyRateTier = (index = 0) => ({
    coinPerUsd: "",
    enabled: true,
    maxUsd: "",
    minUsd: "",
    sortOrder: (index + 1) * 10,
});

export function useHostCoinSellersPage() {
    const abilities = useCoinSellerAbilities();
    const { showToast } = useToast();
    const { loadingRegions, regionOptions } = useRegionOptions();
    const [userFilter, setUserFilter] = useState(emptyUserIdentityFilter);
    const [status, setStatus] = useState("");
    const [regionId, setRegionId] = useState("");
    const [sortBy, setSortBy] = useState("");
    const [sortDirection, setSortDirection] = useState("");
    const [page, setPage] = useState(1);
    const [activeAction, setActiveAction] = useState("");
    const [createForm, setCreateForm] = useState(emptyCreateForm);
    const [editForm, setEditForm] = useState(emptyEditForm);
    const [stockForm, setStockForm] = useState(emptyStockForm);
    const [stockDebitForm, setStockDebitForm] = useState(emptyStockDebitForm);
    const [rateRegionId, setRateRegionId] = useState("");
    const [rateTiers, setRateTiers] = useState([]);
    const [loadingRates, setLoadingRates] = useState(false);
    const [selectedSeller, setSelectedSeller] = useState(null);
    const [loadingAction, setLoadingAction] = useState("");
    const [loadingSubSellers, setLoadingSubSellers] = useState(false);
    const [subSellerData, setSubSellerData] = useState(emptyData);
    const [subSellerPage, setSubSellerPageState] = useState(1);
    const [contactSavingIds, setContactSavingIds] = useState({});
    const [sellerRowPatches, setSellerRowPatches] = useState({});
    const filters = useMemo(
        () => ({
            region_id: regionId,
            sort_by: sortBy,
            sort_direction: sortDirection,
            status,
            ...userIdentityFilterParams(userFilter),
        }),
        [regionId, sortBy, sortDirection, status, userFilter],
    );
    const {
        data: queryData = emptyData,
        error,
        loading,
        reload,
    } = usePaginatedQuery({
        errorMessage: "加载币商列表失败",
        fetcher: listCoinSellers,
        filters,
        page,
        pageSize,
        queryKey: ["host-org", "coin-sellers", filters, page],
    });
    const data = useMemo(() => {
        const sourceItems = Array.isArray(queryData.items) ? queryData.items : [];
        return {
            ...queryData,
            items: sourceItems.map((seller) => ({
                ...seller,
                ...(sellerRowPatches[seller.userId] || {}),
            })),
        };
    }, [queryData, sellerRowPatches]);

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

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

    const changeRegionId = (value) => {
        setRegionId(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("");
        setSortBy("");
        setSortDirection("");
        setPage(1);
    };

    const openCreateSeller = () => {
        setCreateForm(emptyCreateForm());
        setSelectedSeller(null);
        setActiveAction("create");
    };

    const openEditSeller = (seller) => {
        if (!seller?.userId) {
            return;
        }
        setSelectedSeller(seller);
        setEditForm({
            canManageSubCoinSellers: seller.canManageSubCoinSellers === true,
            commandId: makeCommandId("coin-seller-status"),
            contact: seller.contact || "",
            reason: "update coin seller contact",
            status: seller.status || "active",
            targetUserId: seller.userId,
        });
        setActiveAction("edit");
    };

    const openStockCredit = (seller) => {
        if (!seller?.userId || !abilities.canStockCredit) {
            return;
        }
        setSelectedSeller(seller);
        setStockForm(emptyStockForm());
        setActiveAction("stock");
    };

    const openStockDebit = (seller) => {
        if (!seller?.userId || !abilities.canStockCredit) {
            return;
        }
        setSelectedSeller(seller);
        setStockDebitForm(emptyStockDebitForm());
        setActiveAction("stock-debit");
    };

    const openSellerLedger = (seller) => {
        if (!seller?.userId || !abilities.canLedger) {
            return;
        }
        setSelectedSeller(seller);
        setActiveAction("ledger");
    };

    const openSubSellerList = async (seller) => {
        if (!seller?.userId || !abilities.canView) {
            return;
        }
        setSelectedSeller(seller);
        setActiveAction("sub-sellers");
        await loadSubSellers(seller.userId, 1);
    };

    const openRateSettings = async () => {
        if (!abilities.canExchangeRate) {
            return;
        }
        const nextRegionId = rateRegionId || regionId || regionOptions[0]?.value || "";
        setRateRegionId(nextRegionId);
        setActiveAction("rates");
        if (nextRegionId) {
            await loadRateTiers(nextRegionId);
        } else {
            setRateTiers([]);
        }
    };

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

    const loadSubSellers = async (sellerUserId = selectedSeller?.userId, nextPage = subSellerPage) => {
        if (!sellerUserId) {
            setSubSellerData(emptyData);
            return;
        }
        setLoadingSubSellers(true);
        try {
            const nextData = await listCoinSellerSubSellers(sellerUserId, {
                page: nextPage,
                page_size: pageSize,
            });
            setSubSellerData(nextData || emptyData);
            setSubSellerPageState(nextPage);
        } catch (err) {
            setSubSellerData(emptyData);
            showToast(err.message || "加载子币商列表失败", "error");
        } finally {
            setLoadingSubSellers(false);
        }
    };

    const setSubSellerPage = async (nextPage) => {
        await loadSubSellers(selectedSeller?.userId, nextPage);
    };

    const changeRateRegionId = async (value) => {
        setRateRegionId(value);
        if (value) {
            await loadRateTiers(value);
        } else {
            setRateTiers([]);
        }
    };

    const loadRateTiers = async (targetRegionId = rateRegionId) => {
        if (!targetRegionId) {
            return;
        }
        setLoadingRates(true);
        try {
            const data = await getCoinSellerSalaryRates(targetRegionId);
            const next = (data?.tiers || []).map((tier, index) => ({
                coinPerUsd: String(tier.coinPerUsd || ""),
                enabled: tier.status ? tier.status === "active" : tier.enabled !== false,
                maxUsd: tier.maxUsd || centsToUSD(tier.maxUsdMinor),
                minUsd: tier.minUsd || centsToUSD(tier.minUsdMinor),
                sortOrder: tier.sortOrder || (index + 1) * 10,
            }));
            setRateTiers(next.length ? next : [emptyRateTier(0)]);
        } catch (err) {
            setRateTiers([emptyRateTier(0)]);
            showToast(err.message || "加载兑换比例失败", "error");
        } finally {
            setLoadingRates(false);
        }
    };

    const addRateTier = () => {
        setRateTiers((items) => [...items, emptyRateTier(items.length)]);
    };

    const removeRateTier = (index) => {
        setRateTiers((items) => items.filter((_, itemIndex) => itemIndex !== index));
    };

    const updateRateTier = (index, patch) => {
        setRateTiers((items) => items.map((item, itemIndex) => (itemIndex === index ? { ...item, ...patch } : item)));
    };

    const submitCreateSeller = async (event) => {
        event.preventDefault();
        await runAction("coin-seller-create", "币商已添加", async () => {
            const payload = parseForm(createCoinSellerSchema, createForm);
            await createCoinSeller(payload);
            setCreateForm(emptyCreateForm());
            closeAction();
            await reload();
        });
    };

    const submitEditSeller = async (event) => {
        event.preventDefault();
        await runAction(
            `coin-seller-edit-${editForm.targetUserId || selectedSeller?.userId || ""}`,
            "币商已更新",
            async () => {
                // 编辑接口复用 status 命令，提交时带上权限字段，避免只改联系方式时把子币商权限丢给后端默认值处理。
                const payload = parseForm(coinSellerStatusSchema, editForm);
                const { targetUserId, ...body } = payload;
                await setCoinSellerStatus(targetUserId, body);
                setEditForm(emptyEditForm());
                closeAction();
                await reload();
            },
        );
    };

    const saveSellerContact = async (seller, rawContact) => {
        if (!abilities.canUpdate || !seller?.userId) {
            return false;
        }
        const contact = String(rawContact ?? "").trim();
        if (contact === String(seller.contact || "").trim()) {
            return true;
        }
        const sellerID = seller.userId;
        setContactSavingIds((current) => ({ ...current, [sellerID]: true }));
        try {
            // 联系方式行内保存同样走状态接口，显式保留当前权限位，避免局部保存覆盖行级权限。
            await setCoinSellerStatus(sellerID, {
                canManageSubCoinSellers: seller.canManageSubCoinSellers === true,
                commandId: makeCommandId("coin-seller-contact"),
                contact,
                reason: "update coin seller contact",
                status: seller.status || "active",
            });
            setSellerRowPatches((current) => ({
                ...current,
                [sellerID]: {
                    ...(current[sellerID] || {}),
                    contact,
                },
            }));
            showToast("联系方式已保存", "success");
            return true;
        } catch (err) {
            showToast(err.message || "保存联系方式失败", "error");
            return false;
        } finally {
            setContactSavingIds((current) => {
                const next = { ...current };
                delete next[sellerID];
                return next;
            });
        }
    };

    const toggleSubCoinSellerPermission = async (seller, nextEnabled = !seller?.canManageSubCoinSellers) => {
        if (!abilities.canUpdate || !seller?.userId) {
            return;
        }
        if ((seller.canManageSubCoinSellers === true) === nextEnabled) {
            return;
        }
        await runAction(
            `coin-seller-sub-permission-${seller.userId}`,
            nextEnabled ? "子币商权限已开启" : "子币商权限已关闭",
            async () => {
                // 子权限开关复用币商状态接口，必须保留 status/contact，防止权限更新被解释成状态重置。
                await setCoinSellerStatus(seller.userId, {
                    canManageSubCoinSellers: nextEnabled,
                    commandId: makeCommandId("coin-seller-sub-permission"),
                    contact: seller.contact || "",
                    reason: "update coin seller sub permission",
                    status: seller.status || "active",
                });
                setSellerRowPatches((current) => ({
                    ...current,
                    [seller.userId]: {
                        ...(current[seller.userId] || {}),
                        canManageSubCoinSellers: nextEnabled,
                    },
                }));
                await reload();
            },
        );
    };

    const submitStockCredit = async (event) => {
        event.preventDefault();
        if (!selectedSeller?.userId) {
            return;
        }
        await runAction(`coin-seller-stock-${selectedSeller.userId}`, "币商库存已入账", async () => {
            const payload = parseForm(coinSellerStockCreditSchema, stockForm);
            await creditCoinSellerStock(selectedSeller.userId, payload);
            setStockForm(emptyStockForm());
            closeAction();
            await reload();
        });
    };

    const submitStockDebit = async (event) => {
        event.preventDefault();
        if (!selectedSeller?.userId) {
            return;
        }
        await runAction(`coin-seller-stock-debit-${selectedSeller.userId}`, "币商金币已扣除", async () => {
            const payload = parseForm(coinSellerStockDebitSchema, stockDebitForm);
            await debitCoinSellerStock(selectedSeller.userId, payload);
            setStockDebitForm(emptyStockDebitForm());
            closeAction();
            await reload();
        });
    };

    const submitRateSettings = async (event) => {
        event.preventDefault();
        if (!rateRegionId) {
            showToast("请选择区域", "error");
            return;
        }
        await runAction("coin-seller-rates", "兑换比例已保存", async () => {
            const payload = {
                tiers: rateTiers
                    .filter((tier) => tier.minUsd || tier.maxUsd || tier.coinPerUsd)
                    .map((tier, index) => ({
                        coinPerUsd: Number(tier.coinPerUsd),
                        enabled: tier.enabled !== false,
                        maxUsd: String(tier.maxUsd || "").trim(),
                        minUsd: String(tier.minUsd || "").trim(),
                        sortOrder: Number(tier.sortOrder || (index + 1) * 10),
                    })),
            };
            await replaceCoinSellerSalaryRates(rateRegionId, payload);
            await loadRateTiers(rateRegionId);
        });
    };

    const toggleSeller = async (seller, nextEnabled = seller.status !== "active") => {
        if (!abilities.canUpdate || !seller?.userId) {
            return;
        }
        const nextStatus = nextEnabled ? "active" : "disabled";
        if (seller.status === nextStatus) {
            return;
        }
        await runAction(`coin-seller-status-${seller.userId}`, nextEnabled ? "币商已启用" : "币商已停用", async () => {
            // 状态开关只改变启停状态，显式保留权限位，避免后端按缺省值改写子币商授权。
            await setCoinSellerStatus(seller.userId, {
                canManageSubCoinSellers: seller.canManageSubCoinSellers === true,
                commandId: makeCommandId("coin-seller-status"),
                reason: "",
                status: nextStatus,
            });
            await reload();
        });
    };

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

    return {
        abilities,
        activeAction,
        changeRegionId,
        changeSort,
        changeStatus,
        changeUserFilter,
        closeAction,
        contactSavingIds,
        createForm,
        data,
        editForm,
        error,
        loading,
        loadingAction,
        loadingSubSellers,
        loadingRates,
        loadingRegions,
        openRateSettings,
        openCreateSeller,
        openEditSeller,
        openSellerLedger,
        openStockCredit,
        openStockDebit,
        openSubSellerList,
        page,
        regionId,
        regionOptions,
        rateRegionId,
        rateTiers,
        reload,
        addRateTier,
        changeRateRegionId,
        removeRateTier,
        resetFilters,
        saveSellerContact,
        selectedSeller,
        setCreateForm,
        setEditForm,
        setPage,
        setStockForm,
        setStockDebitForm,
        setSubSellerPage,
        status,
        stockDebitForm,
        stockForm,
        subSellerData,
        subSellerPage,
        sortBy,
        sortDirection,
        submitRateSettings,
        submitCreateSeller,
        submitEditSeller,
        submitStockCredit,
        submitStockDebit,
        toggleSubCoinSellerPermission,
        toggleSeller,
        updateRateTier,
        userFilter,
    };
}

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

function centsToUSD(value) {
    const amount = Number(value || 0);
    if (!Number.isFinite(amount) || amount <= 0) {
        return "";
    }
    return `${Math.trunc(amount / 100)}.${String(Math.abs(amount % 100)).padStart(2, "0")}`;
}
