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

import UploadButton from "~/components/UploadButton";
import OrgEquipmentSelectModal from "./OrgEquipmentSelectModal";

export default function EquipmentStep({
  equipmentList = [],
  disabled,
  onAdd,
  onRemove,
  onUploadCalibration,
}) {
  const [selectOpen, setSelectOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState("");
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const existingIds = equipmentList.map((item) =>
    String(item.sourceEquipmentId || ""),
  );

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

  const handleBatchRemove = () => {
    const records = selectedRowKeys
      .map((key) =>
        equipmentList.find(
          (item) => String(item.sourceEquipmentId || item.id) === key,
        ),
      )
      .filter(Boolean);
    if (records.length > 0) {
      onRemove?.(records);
    }
  };

  return (
    <>
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          marginBottom: 12,
        }}
      >
        <span style={{ fontWeight: 600 }}>申请单位装备清单</span>
        {!disabled && (
          <Space size="small">
            <Button size="small" onClick={() => setSelectOpen(true)}>
              添加设备
            </Button>
            {selectedRowKeys.length > 0 && (
              <Button danger size="small" onClick={handleBatchRemove}>
                批量移除
              </Button>
            )}
          </Space>
        )}
      </div>
      <Table
        size="small"
        rowKey={(record) => String(record.sourceEquipmentId || record.id)}
        pagination={false}
        dataSource={equipmentList || []}
        rowSelection={
          !disabled
            ? {
                selectedRowKeys,
                onChange: setSelectedRowKeys,
              }
            : undefined
        }
        columns={[
          { title: "序号", width: 60, render: (_, __, index) => index + 1 },
          { title: "装备名称", dataIndex: "deviceName", ellipsis: true },
          { title: "规格型号", dataIndex: "deviceModel", ellipsis: true },
          { title: "生产厂家", dataIndex: "manufacturer" },
          {
            title: "计量检定情况",
            width: 180,
            render: (_, record) => (
              <Space size="small">
                {record.calibrationReportUrl ? (
                  <Button
                    type="link"
                    size="small"
                    onClick={() => {
                      if (isImage(record.calibrationReportUrl)) {
                        setPreviewImage(record.calibrationReportUrl);
                      } else {
                        window.open(record.calibrationReportUrl);
                      }
                    }}
                  >
                    预览
                  </Button>
                ) : (
                  !disabled && (
                    <UploadButton
                      uploadProps={{
                        accept:
                          ".pdf,.doc,.docx,.xls,.xlsx,.png,.jpg,.jpeg,.gif,.bmp,.webp",
                      }}
                      onSuccess={(data) => onUploadCalibration?.(record, data)}
                      buttonProps={{ children: "上传报告" }}
                    />
                  )
                )}
              </Space>
            ),
          },
          {
            title: "操作",
            width: 100,
            render: (_, record) =>
              !disabled && (
                <Button
                  type="link"
                  size="small"
                  danger
                  onClick={() => onRemove?.(record)}
                >
                  移除
                </Button>
              ),
          },
        ]}
      />
      <OrgEquipmentSelectModal
        open={selectOpen}
        existingIds={existingIds}
        onCancel={() => setSelectOpen(false)}
        onConfirm={(ids, rows) => {
          onAdd?.(ids, rows);
          setSelectOpen(false);
        }}
      />
      {previewImage && (
        <Image
          style={{ display: "none" }}
          preview={{
            visible: !!previewImage,
            src: previewImage,
            onVisibleChange: (visible) => {
              if (!visible) setPreviewImage("");
            },
          }}
        />
      )}
    </>
  );
}
