import Button from "@mui/material/Button";
import Dialog from "@mui/material/Dialog";
import DialogActions from "@mui/material/DialogActions";
import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle";
import TextField from "@mui/material/TextField";
import { useEffect, useState } from "react";
import { UploadField } from "@/shared/ui/UploadField.jsx";
import { operationLabel } from "../format.js";

export function FinanceAuditDialog({ application, loading, onClose, onSubmit, open, operations, requireApprovalImage = false, requireRejectRemark = false }) {
  const [remark, setRemark] = useState("");
  const [auditImageUrl, setAuditImageUrl] = useState("");
  const decision = application?.decision || "approved";
  const needsImage = decision === "approved" && requireApprovalImage;
  const needsRejectRemark = decision === "rejected" && requireRejectRemark;
  const submitDisabled = loading || (needsImage && !auditImageUrl) || (needsRejectRemark && !remark.trim());

  useEffect(() => {
    if (open) {
      setRemark("");
      setAuditImageUrl("");
    }
  }, [open]);

  const submit = () => {
    onSubmit({ auditImageUrl, decision, remark });
  };

  return (
    <Dialog fullWidth maxWidth="sm" open={open} onClose={loading ? undefined : onClose}>
      <DialogTitle>{decision === "approved" ? "通过申请" : "拒绝申请"}</DialogTitle>
      <DialogContent className="finance-audit-dialog">
        <div className="finance-audit-summary">
          <span>{application?.appName || application?.appCode || "-"}</span>
          <strong>{operationLabel(application?.operation, operations)}</strong>
          <span>{application?.targetUserId || "-"}</span>
        </div>
        <TextField
          disabled={loading}
          label="审核备注"
          minRows={4}
          multiline
          value={remark}
          onChange={(event) => setRemark(event.target.value)}
        />
        {needsRejectRemark && !remark.trim() ? <span className="finance-audit-hint">拒绝时必须填写原因</span> : null}
        {needsImage ? (
          <UploadField
            disabled={loading}
            hideType
            kind="image"
            label="打款凭证图片"
            uploadKind="image"
            value={auditImageUrl}
            onChange={setAuditImageUrl}
          />
        ) : null}
      </DialogContent>
      <DialogActions>
        <Button disabled={loading} onClick={onClose}>
          取消
        </Button>
        <Button disabled={submitDisabled} variant="contained" onClick={submit}>
          确认
        </Button>
      </DialogActions>
    </Dialog>
  );
}
