import CloudSyncOutlined from "@mui/icons-material/CloudSyncOutlined";
import FileDownloadOutlined from "@mui/icons-material/FileDownloadOutlined";
import RefreshOutlined from "@mui/icons-material/RefreshOutlined";
import Button from "@mui/material/Button";
import MenuItem from "@mui/material/MenuItem";
import TextField from "@mui/material/TextField";
import { Fragment, useState } from "react";
import { AppIdentity } from "@/shared/ui/AppIdentity.jsx";
import {
    formatAmount,
    formatMicroMoney,
    formatTime,
    formatUsdMinor,
    rechargeSourceTone,
    rechargeTypeLabel,
} from "../format.js";

// 系统保存视图：财务高频筛选组合一键切换；与全局 rechargeType/paidState 联动。
const SAVED_VIEWS = [
    { key: "all", label: "全部", paidState: "", rechargeType: "" },
    { key: "google", label: "谷歌充值", paidState: "", rechargeType: "google_play_recharge" },
    { key: "third", label: "三方充值", paidState: "", rechargeType: "third_party" },
    { key: "seller", label: "币商充值", paidState: "", rechargeType: "coin_seller" },
    { key: "unsynced", label: "实付未同步", paidState: "unsynced", rechargeType: "" },
];

export function FinanceRechargeDetailList({
    apps,
    bills,
    currency,
    error,
    exporting,
    filters,
    googlePaidRefreshing,
    loading,
    onExport,
    onFiltersChange,
    onRefreshGooglePaid,
    onReload,
    regions,
    regionsByApp,
    summary,
}) {
    const [expandedId, setExpandedId] = useState("");
    const items = bills.items || [];
    const page = Number(bills.page || filters.page || 1);
    const pageSize = Number(bills.pageSize || 50);
    const total = Number(bills.total || 0);
    const hasNextPage = page * pageSize < total;
    const showCoins = currency === "coin";
    const regionNames = new Map(
        (regions || []).map((region) => [String(region.regionId), region.name || region.regionCode]),
    );
    const activeView =
        SAVED_VIEWS.find(
            (view) =>
                view.rechargeType === (filters.rechargeType || "") && view.paidState === (filters.paidState || ""),
        )?.key || "all";
    const pendingGoogleTxIds = items
        .filter((item) => item.rechargeType === "google_play_recharge" && !item.paidSyncedAtMs)
        .map((item) => item.transactionId)
        .filter(Boolean);
    const columnCount = showCoins ? 9 : 8;
    const selectedApp = (apps || []).find((app) => app.appCode === filters.appCode);

    const chips = [
        filters.appCode
            ? {
                  key: "appCode",
                  label: <AppIdentity app={selectedApp} appCode={filters.appCode} size="small" />,
                  reset: { appCode: "", regionId: "" },
              }
            : null,
        filters.regionId
            ? {
                  key: "regionId",
                  label: `区域：${regionNames.get(String(filters.regionId)) || filters.regionId}`,
                  reset: { regionId: "" },
              }
            : null,
        filters.timeRange?.startMs || filters.timeRange?.endMs
            ? {
                  key: "time",
                  label: `时间：${rangeLabel(filters.timeRange)}`,
                  reset: { timeRange: { endMs: "", startMs: "" } },
              }
            : null,
        filters.keyword ? { key: "keyword", label: `搜索：${filters.keyword}`, reset: { keyword: "" } } : null,
    ].filter(Boolean);

    return (
        <section className="finance-card finance-list">
            <div className="finance-views" role="tablist" aria-label="流水视图">
                {SAVED_VIEWS.map((view) => (
                    <button
                        aria-selected={activeView === view.key}
                        className={activeView === view.key ? "is-on" : ""}
                        key={view.key}
                        role="tab"
                        type="button"
                        onClick={() => onFiltersChange({ paidState: view.paidState, rechargeType: view.rechargeType })}
                    >
                        {view.label}
                        {activeView === view.key && !loading ? (
                            <span className="finance-views__cnt num">{formatAmount(total)}</span>
                        ) : null}
                    </button>
                ))}
            </div>

            <div className="finance-filterrow">
                {chips.map((chip) => (
                    <button
                        className="finance-fchip"
                        key={chip.key}
                        type="button"
                        onClick={() => onFiltersChange(chip.reset)}
                    >
                        {chip.label}
                        <span aria-hidden="true">×</span>
                    </button>
                ))}
                <TextField
                    className="finance-filterrow__region"
                    disabled={!filters.appCode}
                    label="区域"
                    select
                    size="small"
                    title={filters.appCode ? "" : "先选择 App"}
                    value={filters.regionId}
                    onChange={(event) => onFiltersChange({ regionId: event.target.value })}
                >
                    <MenuItem value="">全部区域</MenuItem>
                    {(regions || []).map((region) => (
                        <MenuItem key={region.regionId} value={String(region.regionId)}>
                            {region.name || region.regionCode || region.regionId}
                        </MenuItem>
                    ))}
                </TextField>
                <TextField
                    className="finance-filterrow__search"
                    label="订单搜索"
                    placeholder="交易号 / GPA单号 / 凭证号"
                    size="small"
                    value={filters.keyword}
                    onChange={(event) => onFiltersChange({ keyword: event.target.value })}
                />
                <span className="finance-filterrow__spacer" />
                <Button
                    disabled={googlePaidRefreshing || !filters.appCode || !pendingGoogleTxIds.length}
                    size="small"
                    startIcon={<CloudSyncOutlined fontSize="small" />}
                    title={filters.appCode ? "查询本页谷歌订单的用户实付币种和金额" : "先选择 App 后可查询"}
                    variant="outlined"
                    onClick={() => onRefreshGooglePaid(pendingGoogleTxIds)}
                >
                    {googlePaidRefreshing ? "查询中…" : "查询谷歌实付"}
                </Button>
                <Button
                    disabled={exporting || !filters.appCode}
                    size="small"
                    startIcon={<FileDownloadOutlined fontSize="small" />}
                    title={filters.appCode ? "按当前筛选导出全部明细（CSV）" : "先选择 App 后可导出"}
                    variant="contained"
                    onClick={onExport}
                >
                    {exporting ? "导出中…" : "导出报表"}
                </Button>
                <Button
                    size="small"
                    startIcon={<RefreshOutlined fontSize="small" />}
                    variant="outlined"
                    onClick={onReload}
                >
                    刷新
                </Button>
            </div>

            {error ? <div className="finance-error">{error}</div> : null}
            {loading && !items.length ? <div className="finance-skeleton" /> : null}
            {!loading || items.length ? (
                <div className="finance-tablewrap">
                    <table className="finance-flat-table finance-flat-table--bills">
                        <thead>
                            <tr>
                                <th>充值时间</th>
                                <th>APP</th>
                                <th>充值来源</th>
                                <th>充值订单号</th>
                                {showCoins ? <th className="r">充值金币</th> : null}
                                <th className="r">账单金额</th>
                                <th className="r">用户实付</th>
                                <th className="r">三方税率扣款</th>
                                <th>区域</th>
                            </tr>
                        </thead>
                        <tbody>
                            {items.length ? (
                                items.map((item) => {
                                    const rowId = item.id || item.transactionId;
                                    const expanded = expandedId === rowId;
                                    return (
                                        <Fragment key={rowId}>
                                            <tr
                                                className="finance-flat-table__row"
                                                onClick={() => setExpandedId(expanded ? "" : rowId)}
                                            >
                                                <td className="num">{formatTime(item.createdAtMs)}</td>
                                                <td>
                                                    <AppIdentity
                                                        app={(apps || []).find((app) => app.appCode === item.appCode)}
                                                        appCode={item.appCode}
                                                        size="small"
                                                    />
                                                </td>
                                                <td>
                                                    <span
                                                        className={`finance-badge finance-badge--${badgeTone(item.rechargeType)}`}
                                                    >
                                                        {rechargeTypeLabel(item.rechargeType)}
                                                    </span>
                                                </td>
                                                <td className="finance-order-cell">
                                                    <span className="finance-stack">
                                                        <span>{item.transactionId || "-"}</span>
                                                        <small>{secondaryOrderNo(item)}</small>
                                                    </span>
                                                </td>
                                                {showCoins ? (
                                                    <td className="r num">
                                                        <AmountText value={item.coinAmount}>
                                                            {coinText(item.coinAmount)}
                                                        </AmountText>
                                                    </td>
                                                ) : null}
                                                <td className="r num">
                                                    <AmountText value={item.usdMinorAmount}>
                                                        {billAmountText(item)}
                                                    </AmountText>
                                                </td>
                                                <td className="r num">
                                                    <AmountText value={item.userPaidAmountMicro}>
                                                        {userPaidText(item)}
                                                    </AmountText>
                                                </td>
                                                <td className="r num">{taxDeductionText(item)}</td>
                                                <td>{regionText(item, regionsByApp, apps, !filters.appCode)}</td>
                                            </tr>
                                            {expanded ? (
                                                <tr className="finance-detailrow">
                                                    <td colSpan={columnCount}>
                                                        <BillDetail
                                                            googlePaidRefreshing={googlePaidRefreshing}
                                                            item={item}
                                                            onRefreshGooglePaid={onRefreshGooglePaid}
                                                        />
                                                    </td>
                                                </tr>
                                            ) : null}
                                        </Fragment>
                                    );
                                })
                            ) : (
                                <tr>
                                    <td colSpan={columnCount} style={{ textAlign: "center" }}>
                                        当前筛选条件下没有账单
                                    </td>
                                </tr>
                            )}
                        </tbody>
                    </table>
                </div>
            ) : null}

            <div className="finance-pagination">
                <span className="finance-pagination__meta num">
                    共 {formatAmount(total)} 笔
                    {summary ? ` · 筛选合计 ${formatUsdMinor(summary.total?.usdMinorAmount || 0, "USD")}` : ""} · 第{" "}
                    {page} / {Math.max(1, Math.ceil(total / pageSize))} 页
                </span>
                <div className="finance-pagination__buttons">
                    <Button
                        disabled={page <= 1 || loading}
                        size="small"
                        variant="outlined"
                        onClick={() => onFiltersChange({ page: page - 1 })}
                    >
                        上一页
                    </Button>
                    <Button
                        disabled={!hasNextPage || loading}
                        size="small"
                        variant="outlined"
                        onClick={() => onFiltersChange({ page: page + 1 })}
                    >
                        下一页
                    </Button>
                </div>
            </div>
        </section>
    );
}

// BillDetail 是行内展开的单笔明细：金额瀑布 + 单号集合 + 谷歌实付操作。
function BillDetail({ googlePaidRefreshing, item, onRefreshGooglePaid }) {
    const currencyCode = item.userPaidCurrencyCode || item.currencyCode || "USD";
    const paid = Number(item.userPaidAmountMicro) || 0;
    const fee = Number(item.providerFeeMicro) || 0;
    const tax = Number(item.providerTaxMicro) || 0;
    const net = Number(item.providerNetMicro) || 0;
    const isGoogle = item.rechargeType === "google_play_recharge";
    const unsynced = isGoogle && !item.paidSyncedAtMs;
    return (
        <div className="finance-detail">
            <div>
                <div className="finance-card__title" style={{ marginBottom: 10 }}>
                    金额拆解{paid ? ` · 实付币种 ${currencyCode}` : ""}
                </div>
                {paid && (fee || tax || net) ? (
                    <div className="finance-wfall">
                        <DetailWfallRow
                            amount={paid}
                            color="var(--fin-ink)"
                            currency={currencyCode}
                            label="用户实付"
                            max={paid}
                        />
                        {tax ? (
                            <DetailWfallRow
                                amount={-tax}
                                color="#C86A6A"
                                currency={currencyCode}
                                label="代缴税费"
                                max={paid}
                            />
                        ) : null}
                        {fee ? (
                            <DetailWfallRow
                                amount={-fee}
                                color="#E19B3C"
                                currency={currencyCode}
                                label="渠道服务费"
                                max={paid}
                            />
                        ) : null}
                        {net ? (
                            <DetailWfallRow
                                amount={net}
                                color="var(--fin-pos)"
                                currency={currencyCode}
                                label="开发者净收"
                                max={paid}
                            />
                        ) : null}
                    </div>
                ) : unsynced ? (
                    <p className="finance-hint">
                        实付明细未同步。
                        <Button
                            disabled={googlePaidRefreshing}
                            size="small"
                            style={{ marginLeft: 8 }}
                            variant="outlined"
                            onClick={(event) => {
                                event.stopPropagation();
                                onRefreshGooglePaid([item.transactionId]);
                            }}
                        >
                            同步这一笔
                        </Button>
                    </p>
                ) : (
                    <p className="finance-hint">
                        {paid ? `用户实付 ${formatMicroMoney(paid, currencyCode)} · ` : ""}
                        该渠道未提供扣费明细
                    </p>
                )}
            </div>
            <dl className="finance-kv">
                <dt>交易号</dt>
                <dd className="finance-order-cell">{item.transactionId || "-"}</dd>
                {item.commandId ? (
                    <>
                        <dt>业务单号</dt>
                        <dd className="finance-order-cell">{item.commandId}</dd>
                    </>
                ) : null}
                {item.externalRef ? (
                    <>
                        <dt>外部订单</dt>
                        <dd className="finance-order-cell">{item.externalRef}</dd>
                    </>
                ) : null}
                {item.user?.username || item.user?.userId ? (
                    <>
                        <dt>充值用户</dt>
                        <dd>
                            {item.user.username || "-"}
                            {item.user.userId ? ` · ID ${item.user.userId}` : ""}
                        </dd>
                    </>
                ) : null}
                {item.sellerUserId ? (
                    <>
                        <dt>币商 ID</dt>
                        <dd className="num">{item.sellerUserId}</dd>
                    </>
                ) : null}
                <dt>美金换算</dt>
                <dd className="num">{formatUsdMinor(item.usdMinorAmount, "USD")}</dd>
                {item.paidSyncedAtMs ? (
                    <>
                        <dt>实付同步于</dt>
                        <dd className="num">{formatTime(item.paidSyncedAtMs)}</dd>
                    </>
                ) : null}
            </dl>
        </div>
    );
}

function DetailWfallRow({ amount, color, currency, label, max }) {
    const negative = amount < 0;
    const width = max > 0 ? (Math.abs(amount) / max) * 100 : 0;
    return (
        <div className="finance-wfall__row">
            <span className="finance-wfall__label">{label}</span>
            <span className="finance-wfall__track">
                <i style={{ background: color, width: `${Math.min(100, width)}%` }} />
            </span>
            <span className={negative ? "finance-wfall__val num finance-amount--negative" : "finance-wfall__val num"}>
                {negative ? `− ${formatMicroMoney(-amount, currency)}` : formatMicroMoney(amount, currency)}
            </span>
        </div>
    );
}

function AmountText({ children, value }) {
    const negative = hasNumber(value) && Number(value) < 0;
    return <span className={negative ? "finance-amount finance-amount--negative" : "finance-amount"}>{children}</span>;
}

function badgeTone(rechargeType) {
    return rechargeSourceTone(rechargeType) === "google"
        ? "google"
        : rechargeSourceTone(rechargeType) === "coinseller"
          ? "coinseller"
          : "thirdparty";
}

function rangeLabel(timeRange) {
    const start = timeRange?.startMs ? formatTime(timeRange.startMs) : "…";
    const end = timeRange?.endMs ? formatTime(timeRange.endMs) : "…";
    return `${start} ~ ${end}`;
}

function appName(appCode, apps) {
    return (apps || []).find((app) => app.appCode === appCode)?.appName || appCode || "-";
}

// regionText 解析区域列：全部 App 视图下带上 App 前缀（如 “Lalu-南亚区”），单 App 视图只显示区域名。
function regionText(item, regionsByApp, apps, withAppPrefix) {
    const regionId = item.targetRegionId || item.sellerRegionId;
    if (!regionId) {
        return "—";
    }
    const appRegions = (regionsByApp || {})[item.appCode] || [];
    const name = appRegions.find((region) => String(region.regionId) === String(regionId))?.name || `区域 ${regionId}`;
    return withAppPrefix ? `${appName(item.appCode, apps)}-${name}` : name;
}

function secondaryOrderNo(item) {
    return [item.commandId, item.externalRef].filter(Boolean).join(" / ");
}

function coinText(value) {
    const text = formatAmount(value);
    return text === "-" ? "-" : `${text} 金币`;
}

function billAmountText(item) {
    // 账单金额是平台统一核算的 USDT 口径；currencyCode/providerAmountMinor 属于用户向三方渠道实付的本地币种，不能混到本列。
    return formatUsdMinor(item.usdMinorAmount, "USDT");
}

function userPaidText(item) {
    if (item.userPaidText) {
        return item.userPaidText;
    }
    if (hasNonZeroNumber(item.userPaidAmountMicro) && item.userPaidCurrencyCode) {
        return formatMicroMoney(item.userPaidAmountMicro, item.userPaidCurrencyCode);
    }
    if (isGoogleBill(item) && !item.paidSyncedAtMs) {
        return "未同步";
    }
    if (hasPositiveNumber(item.userPaidAmountMinor)) {
        return formatUsdMinor(item.userPaidAmountMinor, item.userPaidCurrencyCode || item.currencyCode || "USD");
    }
    return "-";
}

function taxDeductionText(item) {
    const currency = item.userPaidCurrencyCode || item.currencyCode || "USD";
    const fee = hasPositiveNumber(item.providerFeeMicro) ? item.providerFeeMicro : 0;
    const tax = hasPositiveNumber(item.providerTaxMicro) ? item.providerTaxMicro : 0;
    const deduction = fee + tax;
    if (deduction > 0) {
        const parts = [formatMicroMoney(deduction, currency)];
        if (hasPositiveNumber(item.userPaidAmountMicro)) {
            const percent = (deduction / item.userPaidAmountMicro) * 100;
            parts.push(`${percent.toLocaleString("zh-CN", { maximumFractionDigits: 2 })}%`);
        }
        return parts.join(" / ");
    }
    if (item.taxDeductionText) {
        return item.taxDeductionText;
    }
    if (isGoogleBill(item) && !item.paidSyncedAtMs) {
        return "未同步";
    }
    return "-";
}

function isGoogleBill(item) {
    return item.rechargeType === "google_play_recharge" || item.providerCode === "google_play";
}

function hasNumber(value) {
    if (value === null || value === undefined || value === "") {
        return false;
    }
    return Number.isFinite(Number(value));
}

function hasPositiveNumber(value) {
    return hasNumber(value) && Number(value) > 0;
}

function hasNonZeroNumber(value) {
    return hasNumber(value) && Number(value) !== 0;
}
