import { Button, Space, Table, Tag } from "antd";
import { useState } from "react";
import { resolveUploadFileId } from "~/utils/mockUpload";
import FilePreviewModal from "~/components/FilePreviewModal";

export default function MaterialStep({
  materials = [],
  disabled,
  onUpload,
  loading,
}) {
  const [preview, setPreview] = useState(null);

  return (
    <>
      <Table
        size="small"
        loading={loading}
        rowKey="id"
        pagination={false}
        scroll={{ x: 900 }}
        dataSource={materials}
        columns={[
          { title: "序号", dataIndex: "sortOrder", width: 60 },
          { title: "内容", dataIndex: "materialContent", width: 200, ellipsis: true },
          { title: "上传附件", dataIndex: "attachmentDesc", width: 100 },
          {
            title: "格式",
            dataIndex: "materialFormat",
            width: 70,
            render: (val) => (val ? <Tag>{val}</Tag> : "-"),
          },
          {
            title: "状态",
            dataIndex: "uploadStatusName",
            width: 90,
            render: (val, record) => (
              <Tag color={record.uploadStatusCode === 2 ? "success" : "warning"}>{val || "待上传"}</Tag>
            ),
          },
          {
            title: "操作",
            width: 120,
            render: (_, record) => (
              <Space size="small">
                {record.attachmentUrl ? (
                  <Button type="link" size="small" onClick={() => setPreview(record)}>预览</Button>
                ) : (
                  !disabled && (
                    <Button
                      type="link"
                      size="small"
                      onClick={() => onUpload?.(record, resolveUploadFileId([]))}
                    >
                      上传
                    </Button>
                  )
                )}
              </Space>
            ),
          },
          { title: "注释", dataIndex: "materialRemark", ellipsis: true },
        ]}
      />
      <FilePreviewModal
        open={!!preview}
        title="材料预览"
        fileName={preview?.materialContent}
        url={preview?.attachmentUrl}
        onCancel={() => setPreview(null)}
      />
    </>
  );
}
