import React from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Button, Tooltip, Modal, message } from 'antd';
import { ImageSelection } from './ImageSelection';
import { DiagnosticReportImageViewer } from './DiagnosticReportImageViewer';
import { useAppSelector, useAppDispatch } from '@/states/store';
import { removeImage } from '@/states/patient/DiagnosticReport/imageListSlice';
import {
  setCandidates,
  cancelSelection,
} from '@/states/patient/DiagnosticReport/imageSelectionSlice';
import { fetchTaskDetails } from '@/API/patient/workActions';
import { getExposedImageUrl } from '@/API/bodyPosition';
export const ImageList: React.FC = () => {
  const [isModalVisible, setIsModalVisible] = React.useState(false);
  const [isLoading, setIsLoading] = React.useState(false);
  const images = useAppSelector((s) => s.imageList.images);
  const studyId = useAppSelector((s) => s.baseInfo.studyId);
  const dispatch = useAppDispatch();

  // 获取候选图像数据
  const handleOpenModal = async () => {
    if (!studyId) {
      message.warning('未找到检查信息，请先选择患者');
      return;
    }

    setIsLoading(true);
    try {
      const studyDetails = await fetchTaskDetails(studyId);

      // 提取所有曝光图像的缩略图 URL
      const imageUrls: string[] = [];
      studyDetails.series.forEach((series) => {
        series.images.forEach((image) => {
          if (image.expose_status === 'Exposed') {
            const thumbnailUrl = getExposedImageUrl(image.sop_instance_uid);
            imageUrls.push(thumbnailUrl);
          }
        });
      });

      if (imageUrls.length === 0) {
        message.info('该检查暂无曝光图像');
        return;
      }

      dispatch(setCandidates(imageUrls));
      setIsModalVisible(true);
    } catch (error) {
      console.error('获取检查图像失败:', error);
      message.error('获取图像失败，请稍后重试');
    } finally {
      setIsLoading(false);
    }
  };

  // 关闭 Modal
  const handleModalClose = () => {
    setIsModalVisible(false);
    dispatch(cancelSelection());
  };

  return (
    <div>
      <div className="flex items-center gap-2 overflow-x-auto">
        <Tooltip title="添加图像">
          <Button
            className="w-24 h-24 border-2 border-dashed border-gray-300 rounded flex items-center justify-center cursor-pointer hover:border-blue-500"
            icon={<PlusOutlined className="text-gray-400" />}
            onClick={handleOpenModal}
            loading={isLoading}
          ></Button>
        </Tooltip>
        {images.map((src, idx) => (
          <DiagnosticReportImageViewer
            key={`${src}_${idx}`}
            src={src}
            onRemove={() => dispatch(removeImage(idx))}
          />
        ))}
      </div>
      <Modal
        title="选择图像"
        width={'49vw'}
        maskClosable={false}
        open={isModalVisible}
        onCancel={handleModalClose}
        footer={null}
      >
        <ImageSelection onClose={handleModalClose} />
      </Modal>
    </div>
  );
};
