import ContentCopyOutlined from "@mui/icons-material/ContentCopyOutlined";
import OpenInNewOutlined from "@mui/icons-material/OpenInNewOutlined";
import RestartAltOutlined from "@mui/icons-material/RestartAltOutlined";
import VerifiedOutlined from "@mui/icons-material/VerifiedOutlined";
import { useMemo, useState } from "react";
import { useTemporaryPaymentLinksPage, temporaryStatusLabel } from "@/features/payment/hooks/useTemporaryPaymentLinksPage.js";
import styles from "@/features/payment/payment.module.css";
import {
    AdminActionIconButton,
    AdminListBody,
    AdminListPage,
    AdminListToolbar,
    AdminRowActions,
} from "@/shared/ui/AdminListLayout.jsx";
import { Button } from "@/shared/ui/Button.jsx";
import { DataState } from "@/shared/ui/DataState.jsx";
import { DataTable } from "@/shared/ui/DataTable.jsx";
import { StatusSelect } from "@/shared/ui/StatusSelect.jsx";
import { createOptionsColumnFilter, createTextColumnFilter } from "@/shared/ui/tableFilters.js";
import { formatMillis } from "@/shared/utils/time.js";

const statusOptions = [
    ["", "全部状态"],
    ["pending", "待支付"],
    ["redirected", "已生成链接"],
    ["paid", "已支付"],
    ["failed", "失败"],
];

const providerOptions = [
    ["", "全部渠道"],
    ["mifapay", "MiFaPay"],
    ["v5pay", "V5Pay"],
];

export function TemporaryPaymentLinksPage() {
    const page = useTemporaryPaymentLinksPage();
    const items = page.data?.items || [];
    const total = page.data?.total || 0;
    const columns = useMemo(() => temporaryPaymentLinkColumns(page), [page]);

    return (
        <AdminListPage>
            <AdminListToolbar
                actions={
                    <Button startIcon={<RestartAltOutlined fontSize="small" />} onClick={page.resetFilters}>
                        重置筛选
                    </Button>
                }
                filters={
                    <>
                        <StatusSelect
                            label="支付渠道"
                            options={providerOptions}
                            value={page.providerCode}
                            onChange={page.setProviderCode}
                        />
                        <StatusSelect
                            label="支付状态"
                            options={statusOptions}
                            value={page.status}
                            onChange={page.setStatus}
                        />
                    </>
                }
            />
            <DataState error={page.error} loading={page.loading} onRetry={page.reload}>
                <AdminListBody>
                    <DataTable
                        columns={columns}
                        emptyLabel="当前无数据"
                        items={items}
                        minWidth="1420px"
                        pagination={
                            total > 0
                                ? {
                                      page: page.page,
                                      pageSize: page.data?.pageSize || page.pageSize,
                                      total,
                                      onPageChange: page.setPage,
                                  }
                                : undefined
                        }
                        rowKey={(item) => item.orderId}
                    />
                </AdminListBody>
            </DataState>
        </AdminListPage>
    );
}

function temporaryPaymentLinkColumns(page) {
    return [
        {
            key: "orderId",
            label: "订单号",
            width: "minmax(160px, 0.8fr)",
            filter: createTextColumnFilter({
                placeholder: "搜索订单号、三方单号",
                value: page.keyword,
                onChange: page.setKeyword,
            }),
            render: (item) => (
                <Stack primary={<CopyableText label="复制订单号" value={item.orderId} />} secondary={item.appCode ? `App: ${item.appCode}` : "-"} />
            ),
        },
        {
            key: "provider",
            label: "支付方式",
            width: "minmax(170px, 0.85fr)",
            filter: createOptionsColumnFilter({
                options: providerOptions,
                placeholder: "搜索支付渠道",
                value: page.providerCode,
                onChange: page.setProviderCode,
            }),
            render: (item) => (
                <Stack
                    primary={providerLabel(item.providerCode)}
                    secondary={[item.payWay, item.payType].filter(Boolean).join(" / ") || "-"}
                />
            ),
        },
        {
            key: "amount",
            label: "收款金额",
            width: "minmax(140px, 0.65fr)",
            render: (item) => <Stack primary={formatMoney(item.usdMinorAmount, "USD")} secondary="仅收款，不发金币" />,
        },
        {
            key: "providerAmount",
            label: "三方金额",
            width: "minmax(130px, 0.6fr)",
            render: (item) => formatMoney(item.providerAmountMinor, item.currencyCode),
        },
        {
            key: "payUrl",
            label: "支付链接",
            width: "minmax(260px, 1.2fr)",
            render: (item) => <PaymentLink value={item.payUrl} />,
        },
        {
            key: "providerOrderId",
            label: "三方订单",
            width: "minmax(160px, 0.75fr)",
            render: (item) => <CopyableText label="复制三方订单" value={item.providerOrderId} />,
        },
        {
            key: "status",
            label: "支付状态",
            width: "minmax(110px, 0.55fr)",
            filter: createOptionsColumnFilter({
                options: statusOptions,
                placeholder: "搜索状态",
                value: page.status,
                onChange: page.setStatus,
            }),
            render: (item) => <StatusBadge status={item.status} />,
        },
        {
            key: "time",
            label: "创建时间",
            width: "minmax(160px, 0.75fr)",
            render: (item) => <Stack primary={formatMillis(item.createdAtMs)} secondary={formatMillis(item.updatedAtMs)} />,
        },
        {
            key: "actions",
            label: "操作",
            width: "128px",
            fixed: "right",
            resizable: false,
            render: (item) => (
                <AdminRowActions>
                    <AdminActionIconButton
                        disabled={!page.abilities.canViewTemporaryLink || page.loadingAction === `verify:${item.orderId}`}
                        label="验证支付"
                        tooltip="验证支付"
                        onClick={() => page.verifyOrder(item.orderId)}
                    >
                        <VerifiedOutlined fontSize="small" />
                    </AdminActionIconButton>
                    <AdminActionIconButton
                        disabled={!item.payUrl}
                        label="打开链接"
                        tooltip="打开链接"
                        onClick={() => openLink(item.payUrl)}
                    >
                        <OpenInNewOutlined fontSize="small" />
                    </AdminActionIconButton>
                </AdminRowActions>
            ),
        },
    ];
}

function PaymentLink({ value }) {
    if (!value) {
        return "-";
    }
    return (
        <span className={styles.temporaryLinkCell}>
            <span title={value}>{value}</span>
            <CopyButton label="复制支付链接" value={value} />
        </span>
    );
}

function CopyableText({ label, value }) {
    if (!value) {
        return "-";
    }
    return (
        <span className={styles.copyableText}>
            <span title={String(value)}>{value}</span>
            <CopyButton label={label} value={value} />
        </span>
    );
}

function CopyButton({ label, value }) {
    const [copied, setCopied] = useState(false);
    const copyValue = async () => {
        await copyText(String(value || ""));
        setCopied(true);
        window.setTimeout(() => setCopied(false), 1200);
    };
    return (
        <span className={styles.copyWrap}>
            <AdminActionIconButton disabled={!value} label={label} tooltip={copied ? "已复制" : label} onClick={copyValue}>
                <ContentCopyOutlined fontSize="small" />
            </AdminActionIconButton>
        </span>
    );
}

function StatusBadge({ status }) {
    const tone =
        status === "paid" || status === "credited" ? "succeeded" : status === "failed" ? "danger" : "stopped";
    return (
        <span className={`status-badge status-badge--${tone}`}>
            <span className="status-point" />
            {temporaryStatusLabel(status)}
        </span>
    );
}

function Stack({ primary, secondary }) {
    return (
        <div className="cell-stack">
            <span>{primary || "-"}</span>
            <span className="muted">{secondary || "-"}</span>
        </div>
    );
}

function providerLabel(value) {
    return providerOptions.find(([optionValue]) => optionValue === value)?.[1] || value || "-";
}

function formatMoney(value, currency = "USD") {
    if (!(value === 0 || value)) {
        return "-";
    }
    return `${currency || "USD"} ${(Number(value) / 100).toLocaleString("zh-CN", {
        maximumFractionDigits: 2,
        minimumFractionDigits: 2,
    })}`;
}

function openLink(value) {
    if (!value) {
        return;
    }
    window.open(value, "_blank", "noopener,noreferrer");
}

async function copyText(value) {
    if (navigator.clipboard?.writeText) {
        try {
            await navigator.clipboard.writeText(value);
            return;
        } catch {
            // 后台可能运行在非安全上下文，Clipboard API 被浏览器拒绝时退回同步复制。
        }
    }

    const input = document.createElement("textarea");
    input.value = value;
    input.setAttribute("readonly", "");
    input.style.position = "fixed";
    input.style.opacity = "0";
    document.body.appendChild(input);
    input.select();
    document.execCommand("copy");
    input.remove();
}
