import ContentCopyOutlined from "@mui/icons-material/ContentCopyOutlined";
import RefreshOutlined from "@mui/icons-material/RefreshOutlined";
import Button from "@mui/material/Button";
import IconButton from "@mui/material/IconButton";
import MenuItem from "@mui/material/MenuItem";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import TextField from "@mui/material/TextField";
import Tooltip from "@mui/material/Tooltip";
import { AppIdentity } from "@/shared/ui/AppIdentity.jsx";
import { useToast } from "@/shared/ui/ToastProvider.jsx";
import { formatAmount, formatTime, statusLabel } from "../format.js";

export function FinanceWithdrawalApplicationList({
  applications,
  canAudit,
  error,
  filters,
  loading,
  onAudit,
  onFiltersChange,
  onReload,
  options,
  reviewStage = "finance",
}) {
  const { showToast } = useToast();
  const isOperationsReview = reviewStage === "operations";
  const items = applications.items || [];
  const page = Number(applications.page || filters.page || 1);
  const pageSize = Number(applications.pageSize || 50);
  const total = Number(applications.total || 0);
  const hasNextPage = page * pageSize < total;
  const copyWithdrawalAddress = async (address) => {
    try {
      // 始终复制接口返回的完整地址；即使表格布局后续调整，也不能复制缩写后的展示值。
      await copyText(address);
      showToast("提现地址已复制", "success");
    } catch {
      showToast("复制失败，请手动选择地址复制", "error");
    }
  };

  return (
    <section className="finance-panel finance-list">
      <div className="finance-toolbar">
        <TextField
          label="APP"
          select
          value={filters.appCode}
          onChange={(event) => onFiltersChange({ appCode: event.target.value })}
        >
          <MenuItem value="">全部 APP</MenuItem>
          {options.apps.map((app) => (
            <MenuItem key={app.appCode} value={app.appCode}>
              <AppIdentity app={app} size="small" />
            </MenuItem>
          ))}
        </TextField>
        <TextField label="搜索" value={filters.keyword} onChange={(event) => onFiltersChange({ keyword: event.target.value })} />
        <Button 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 ? (
        <TableContainer className="finance-table-wrap">
          <Table className="finance-table" size="small" stickyHeader>
            <TableHead>
              <TableRow>
                <TableCell>APP</TableCell>
                <TableCell>来源单号</TableCell>
                <TableCell>用户ID</TableCell>
                <TableCell align="right">提现金额</TableCell>
                <TableCell>提现方式</TableCell>
                <TableCell>提现地址</TableCell>
                <TableCell className="finance-time-cell">申请时间</TableCell>
                {isOperationsReview ? (
                  <>
                    <TableCell>运营审核人</TableCell>
                    <TableCell className="finance-time-cell">运营审核时间</TableCell>
                    <TableCell>运营审核原因</TableCell>
                  </>
                ) : (
                  <>
                    <TableCell>运营审核</TableCell>
                    <TableCell>财务审核人</TableCell>
                    <TableCell className="finance-time-cell">财务审核时间</TableCell>
                    <TableCell>财务审核原因</TableCell>
                  </>
                )}
                <TableCell align="right">操作</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {items.length ? (
                items.map((item) => (
                  <TableRow key={item.id}>
                    <TableCell>
                      <AppIdentity
                        app={options.apps.find((app) => app.appCode === item.appCode)}
                        appCode={item.appCode}
                        appName={item.appName}
                        size="small"
                      />
                    </TableCell>
                    <TableCell>
                      <Stacked
                        primary={sourceSystemLabel(item.sourceSystem)}
                        secondary={item.sourceApplicationId || ""}
                      />
                    </TableCell>
                    <TableCell>{item.userId || "-"}</TableCell>
                    <TableCell align="right">$ {formatAmount(item.withdrawAmount)}</TableCell>
                    <TableCell>{item.withdrawMethod || "-"}</TableCell>
                    <TableCell>
                      {item.withdrawAddress ? (
                        <span className="finance-address-wrap">
                          <span className="finance-address" title={item.withdrawAddress}>{item.withdrawAddress}</span>
                          <Tooltip title="复制提现地址">
                            <IconButton
                              aria-label="复制提现地址"
                              size="small"
                              onClick={() => copyWithdrawalAddress(item.withdrawAddress)}
                            >
                              <ContentCopyOutlined fontSize="small" />
                            </IconButton>
                          </Tooltip>
                        </span>
                      ) : "-"}
                    </TableCell>
                    <TableCell className="finance-time-cell">{formatTime(item.createdAtMs)}</TableCell>
                    {isOperationsReview ? (
                      <>
                        <TableCell>
                          <Stacked
                            primary={item.operationsReviewerName || "-"}
                            secondary={item.operationsReviewerUserId || ""}
                          />
                        </TableCell>
                        <TableCell className="finance-time-cell">{formatTime(item.operationsReviewedAtMs)}</TableCell>
                        <TableCell>{item.operationsAuditRemark || "-"}</TableCell>
                      </>
                    ) : (
                      <>
                        <TableCell>
                          <ReviewContext application={item} />
                        </TableCell>
                        <TableCell>
                          <Stacked primary={item.approverName || "-"} secondary={item.approverUserId || ""} />
                        </TableCell>
                        <TableCell className="finance-time-cell">{formatTime(item.approvedAtMs)}</TableCell>
                        <TableCell>{item.auditRemark || "-"}</TableCell>
                      </>
                    )}
                    <TableCell align="right">
                      {(isOperationsReview ? item.operationsStatus : item.status) === "pending" && canAudit ? (
                        <span className="finance-row-actions">
                          <Button
                            size="small"
                            variant="contained"
                            onClick={() =>
                              onAudit({
                                ...item,
                                decision: "approved",
                                operation: isOperationsReview ? "用户提现运营审核" : "用户提现财务审核",
                                reviewStage,
                                targetUserId: item.userId,
                              })
                            }
                          >
                            通过
                          </Button>
                          <Button
                            color="error"
                            size="small"
                            variant="outlined"
                            onClick={() =>
                              onAudit({
                                ...item,
                                decision: "rejected",
                                operation: isOperationsReview ? "用户提现运营审核" : "用户提现财务审核",
                                reviewStage,
                                targetUserId: item.userId,
                              })
                            }
                          >
                            拒绝
                          </Button>
                        </span>
                      ) : isOperationsReview && item.operationsStatus === "rejecting" && canAudit ? (
                        <span className="finance-row-actions">
                          <span>{statusLabel(item.operationsStatus)}</span>
                          <Button
                            color="error"
                            size="small"
                            variant="outlined"
                            onClick={() =>
                              // rejecting 是已持久认领的拒绝方向，只允许继续调用拒绝接口完成外部补偿。
                              onAudit({
                                ...item,
                                decision: "rejected",
                                operation: "用户提现运营审核",
                                reviewStage,
                                targetUserId: item.userId,
                              })
                            }
                          >
                            重试拒绝
                          </Button>
                        </span>
                      ) : (
                        statusLabel(isOperationsReview ? item.operationsStatus : item.status)
                      )}
                    </TableCell>
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell align="center" colSpan={isOperationsReview ? 11 : 12}>
                    当前无数据
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
      ) : null}
      {total > pageSize ? (
        <div className="finance-pagination">
          <Button disabled={page <= 1 || loading} variant="outlined" onClick={() => onFiltersChange({ page: page - 1 })}>
            上一页
          </Button>
          <span>
            第 {page} 页 / 共 {total} 条
          </span>
          <Button disabled={!hasNextPage || loading} variant="outlined" onClick={() => onFiltersChange({ page: page + 1 })}>
            下一页
          </Button>
        </div>
      ) : null}
    </section>
  );
}

function sourceSystemLabel(value) {
  if (!value || value === "hyapp_wallet") {
    return "HY 钱包";
  }
  if (value === "likei") {
    return "Likei";
  }
  return value;
}

function ReviewContext({ application }) {
  return (
    <span className="finance-review-context">
      <Stacked
        primary={application.operationsReviewerName || statusLabel(application.operationsStatus)}
        secondary={application.operationsReviewerUserId || ""}
      />
      <small>{formatTime(application.operationsReviewedAtMs)}</small>
      <small title={application.operationsAuditRemark || ""}>{application.operationsAuditRemark || "-"}</small>
    </span>
  );
}

function Stacked({ primary, secondary }) {
  return (
    <span className="finance-stack">
      <span>{primary || "-"}</span>
      <small>{secondary || ""}</small>
    </span>
  );
}

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();
  const copied = document.execCommand("copy");
  input.remove();
  if (!copied) {
    throw new Error("copy failed");
  }
}
