import { Button, Image, Space, Table, Tag, Upload } from "antd";
import { useState } from "react";

export default function MaterialStep({
  materials = [],
  disabled,
  onUpload,
  loading,
}) {
  const [previewImage, setPreviewImage] = useState("");

  const isImage = (url) => /\.(png|jpe?g|gif|bmp|webp|svg)(\?.*)?$/i.test(url || "");

  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={() => {
                      if (isImage(record.attachmentUrl)) {
                        setPreviewImage(record.attachmentUrl);
                      } else {
                        window.open(record.attachmentUrl);
                      }
                    }}
                  >
                    预览
                  </Button>
                ) : (
                  !disabled && (
                    <Upload
                      showUploadList={false}
                      action={`${window.process.env.app.API_HOST}/safety-eval/file/upload`}
                      onChange={(info) => {
                        if (info.file.status === "done") {
                          const url = info.file.response?.data?.url;
                          if (url) {
                            onUpload?.(record, url);
                          }
                        }
                      }}
                    >
                      <Button type="link" size="small">上传</Button>
                    </Upload>
                  )
                )}
              </Space>
            ),
          },
          { title: "注释", dataIndex: "materialRemark", ellipsis: true },
        ]}
      />
      <Image
        style={{ display: "none" }}
        preview={{
          visible: !!previewImage,
          src: previewImage,
          onVisibleChange: (visible) => {
            if (!visible) setPreviewImage("");
          },
        }}
      />
    </>
  );
}
