import RefreshOutlined from "@mui/icons-material/RefreshOutlined";
import Button from "@mui/material/Button";
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 { formatAmount, formatTime, statusLabel } from "../format.js";

export function FinanceWithdrawalApplicationList({ applications, canAudit, error, filters, loading, onAudit, onFiltersChange, onReload, options }) {
  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;

  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}>
              {app.appName || app.appCode}
            </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>用户ID</TableCell>
                <TableCell align="right">提现金额</TableCell>
                <TableCell>提现方式</TableCell>
                <TableCell>提现地址</TableCell>
                <TableCell className="finance-time-cell">申请时间</TableCell>
                <TableCell>审批人</TableCell>
                <TableCell className="finance-time-cell">审批时间</TableCell>
                <TableCell align="right">操作</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {items.length ? (
                items.map((item) => (
                  <TableRow key={item.id}>
                    <TableCell>{item.appName || item.appCode || "-"}</TableCell>
                    <TableCell>{item.userId || "-"}</TableCell>
                    <TableCell align="right">$ {formatAmount(item.withdrawAmount)}</TableCell>
                    <TableCell>{item.withdrawMethod || "-"}</TableCell>
                    <TableCell>
                      <span className="finance-address" title={item.withdrawAddress}>
                        {item.withdrawAddress || "-"}
                      </span>
                    </TableCell>
                    <TableCell className="finance-time-cell">{formatTime(item.createdAtMs)}</TableCell>
                    <TableCell>
                      <Stacked primary={item.approverName || "-"} secondary={item.approverUserId || ""} />
                    </TableCell>
                    <TableCell className="finance-time-cell">{formatTime(item.approvedAtMs)}</TableCell>
                    <TableCell align="right">
                      {item.status === "pending" && canAudit ? (
                        <span className="finance-row-actions">
                          <Button size="small" variant="contained" onClick={() => onAudit({ ...item, decision: "approved", operation: "用户提现", targetUserId: item.userId })}>
                            通过
                          </Button>
                          <Button color="error" size="small" variant="outlined" onClick={() => onAudit({ ...item, decision: "rejected", operation: "用户提现", targetUserId: item.userId })}>
                            拒绝
                          </Button>
                        </span>
                      ) : (
                        statusLabel(item.status)
                      )}
                    </TableCell>
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell align="center" colSpan={9}>
                    当前无数据
                  </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 Stacked({ primary, secondary }) {
  return (
    <span className="finance-stack">
      <span>{primary || "-"}</span>
      <small>{secondary || ""}</small>
    </span>
  );
}
