import KeyboardArrowDownOutlined from "@mui/icons-material/KeyboardArrowDownOutlined";
import KeyboardArrowRightOutlined from "@mui/icons-material/KeyboardArrowRightOutlined";
import SettingsOutlined from "@mui/icons-material/SettingsOutlined";
import SyncOutlined from "@mui/icons-material/SyncOutlined";
import InputAdornment from "@mui/material/InputAdornment";
import TextField from "@mui/material/TextField";
import { useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { useThirdPartyPaymentPage } from "@/features/payment/hooks/useThirdPartyPaymentPage.js";
import { AdminFormDialog } from "@/shared/ui/AdminFormDialog.jsx";
import { AdminListBody, AdminListPage, AdminListToolbar } from "@/shared/ui/AdminListLayout.jsx";
import { AdminSwitch } from "@/shared/ui/AdminSwitch.jsx";
import { Button } from "@/shared/ui/Button.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import styles from "@/features/payment/payment.module.css";

export function ThirdPartyPaymentPage() {
    return <ThirdPartyPaymentContent showProductButton />;
}

export function ThirdPartyPaymentContent({ embedded = false, showProductButton = false }) {
    const page = useThirdPartyPaymentPage();
    const navigate = useNavigate();
    // 国家分组只影响展示密度，不改变后端返回的可开关粒度；每个 method 仍独立保存状态和汇率。
    const groupedMethods = useMemo(() => groupMethods(page.activeChannel?.methods || []), [page.activeChannel]);

    const content = (
        <>
            <AdminListToolbar
                actions={
                    <div className={styles.toolbarActions}>
                        <Button
                            disabled={!page.abilities.canUpdateThirdParty || page.loadingAction === "sync-rates"}
                            startIcon={<SyncOutlined fontSize="small" />}
                            onClick={page.openSyncRateDialog}
                        >
                            支付汇率全球同步
                        </Button>
                        {showProductButton ? (
                            <Button
                                startIcon={<SettingsOutlined fontSize="small" />}
                                variant="primary"
                                onClick={() => navigate("/payment/recharge-products")}
                            >
                                支付内购商品
                            </Button>
                        ) : null}
                    </div>
                }
            />
            <DataState error={page.error} loading={page.loading} onRetry={page.reload}>
                <AdminListBody>
                    <div className={styles.thirdPartyLayout}>
                        <div className={styles.channelList}>
                            {page.channels.map((channel) => (
                                <div
                                    key={channel.providerCode}
                                    className={[
                                        styles.channelRow,
                                        page.activeChannel?.providerCode === channel.providerCode
                                            ? styles.channelRowActive
                                            : "",
                                    ]
                                        .filter(Boolean)
                                        .join(" ")}
                                >
                                    <button
                                        className={styles.channelSelectButton}
                                        type="button"
                                        onClick={() => page.toggleChannel(channel.providerCode)}
                                    >
                                        <span className={styles.channelExpandIcon}>
                                            {page.expandedChannel === channel.providerCode ? (
                                                <KeyboardArrowDownOutlined fontSize="small" />
                                            ) : (
                                                <KeyboardArrowRightOutlined fontSize="small" />
                                            )}
                                        </span>
                                        <span className={styles.channelText}>
                                            <span>{channel.providerName || channel.providerCode}</span>
                                            <span>{channel.providerCode}</span>
                                        </span>
                                    </button>
                                    {channel.providerCode === "v5pay" ? (
                                        <Button
                                            disabled={
                                                !page.abilities.canUpdateThirdParty ||
                                                page.loadingAction === `sync-methods:${channel.providerCode}`
                                            }
                                            startIcon={<SyncOutlined fontSize="small" />}
                                            onClick={() => page.syncPaymentMethods(channel)}
                                        >
                                            {page.loadingAction === `sync-methods:${channel.providerCode}`
                                                ? "同步中"
                                                : "同步支付方式"}
                                        </Button>
                                    ) : null}
                                </div>
                            ))}
                        </div>

                        <div className={styles.methodPanel}>
                            {page.activeChannel ? (
                                groupedMethods.map((group) => (
                                    <section key={group.key} className={styles.methodGroup}>
                                        <div className={styles.methodGroupHeader}>
                                            <span>{group.title}</span>
                                            <span>{group.methods.length} 个支付方式</span>
                                        </div>
                                        <div className={styles.methodTable}>
                                            <div className={styles.methodHeader}>
                                                <span>支付方式</span>
                                                <span>类型</span>
                                                <span>币种</span>
                                                <span>USD 到本币汇率</span>
                                                <span>状态</span>
                                            </div>
                                            {group.methods.map((method) => (
                                                <div key={method.methodId} className={styles.methodRow}>
                                                    <span className={styles.methodIdentity}>
                                                        <MethodLogo method={method} />
                                                        <span className={styles.methodName}>
                                                            <strong>{method.methodName || method.payWay || "-"}</strong>
                                                            <small>{method.payWay || "-"}</small>
                                                        </span>
                                                    </span>
                                                    <span>{method.payType || "-"}</span>
                                                    <span>{method.currencyCode || "-"}</span>
                                                    <span className={styles.rateEditor}>
                                                        <TextField
                                                            disabled={!page.abilities.canUpdateThirdParty}
                                                            size="small"
                                                            slotProps={{ htmlInput: { inputMode: "decimal" } }}
                                                            value={page.rateDrafts[String(method.methodId)] ?? ""}
                                                            onChange={(event) =>
                                                                page.setRateDraft(method.methodId, event.target.value)
                                                            }
                                                        />
                                                        <Button
                                                            disabled={
                                                                !page.abilities.canUpdateThirdParty ||
                                                                page.loadingAction === `rate:${method.methodId}`
                                                            }
                                                            onClick={() => page.saveRate(method)}
                                                        >
                                                            保存
                                                        </Button>
                                                    </span>
                                                    <span>
                                                        <AdminSwitch
                                                            checked={method.status === "active"}
                                                            checkedLabel="开"
                                                            disabled={
                                                                !page.abilities.canUpdateThirdParty ||
                                                                page.loadingAction === `status:${method.methodId}`
                                                            }
                                                            inputProps={{
                                                                "aria-label":
                                                                    method.status === "active"
                                                                        ? "关闭支付方式"
                                                                        : "打开支付方式",
                                                            }}
                                                            uncheckedLabel="关"
                                                            onChange={(event) =>
                                                                page.toggleMethod(method, event.target.checked)
                                                            }
                                                        />
                                                    </span>
                                                </div>
                                            ))}
                                        </div>
                                    </section>
                                ))
                            ) : (
                                <div className={styles.emptyMethods}>当前无第三方支付渠道</div>
                            )}
                        </div>
                    </div>
                </AdminListBody>
            </DataState>
            <AdminFormDialog
                loading={page.loadingAction === "sync-rates"}
                open={page.syncRateDialogOpen}
                size="narrow"
                submitLabel="确定"
                title="同步支付汇率"
                onClose={page.closeSyncRateDialog}
                onSubmit={page.submitSyncRates}
            >
                <TextField
                    autoFocus
                    disabled={page.loadingAction === "sync-rates" || !page.abilities.canUpdateThirdParty}
                    fullWidth
                    label="汇率上浮比例"
                    required
                    slotProps={{
                        htmlInput: { inputMode: "decimal", max: 100, min: 0, step: "0.1" },
                        input: {
                            endAdornment: <InputAdornment position="end">%</InputAdornment>,
                        },
                    }}
                    value={page.syncRateForm.markupPercent}
                    onChange={(event) => page.setSyncRateMarkupPercent(event.target.value)}
                />
            </AdminFormDialog>
        </>
    );

    if (embedded) {
        return <div className={styles.paymentEmbedded}>{content}</div>;
    }

    return <AdminListPage>{content}</AdminListPage>;
}

function MethodLogo({ method }) {
    const label = String(method.methodName || method.payType || method.payWay || "Pay")
        .slice(0, 2)
        .toUpperCase();
    if (method.logoUrl) {
        return <img alt="" className={styles.methodLogo} src={method.logoUrl} />;
    }
    return <span className={styles.methodLogoFallback}>{label}</span>;
}

function groupMethods(methods) {
    // GLOBAL 是三方支付的跨国家方式，放在最前面，国家方式再按标题排序，方便运营先处理全局支付。
    const groups = new Map();
    methods.forEach((method) => {
        const countryCode = method.countryCode || "GLOBAL";
        const countryName = countryCode === "GLOBAL" ? "全球方式" : method.countryName || countryCode;
        if (!groups.has(countryCode)) {
            groups.set(countryCode, {
                key: countryCode,
                methods: [],
                title: `${countryName} / ${countryCode}`,
            });
        }
        groups.get(countryCode).methods.push(method);
    });
    return Array.from(groups.values()).sort((left, right) => {
        if (left.key === "GLOBAL") {
            return -1;
        }
        if (right.key === "GLOBAL") {
            return 1;
        }
        return left.title.localeCompare(right.title);
    });
}
