import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { useEffect } from 'react';
import {
  setBodyPositions,
  setSelectedBodyPosition,
  ExtendedBodyPosition,
} from '../../../states/exam/bodyPositionListSlice';
import { setBodyPositionDetail } from '../../../states/exam/bodyPositionDetailSlice';
import { RootState } from '../../../states/store';
import { Button, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import ImageViewer from './ImageViewer';
import { getViewIconUrl } from '../../../API/bodyPosition';
import { changeBodyPosition } from '@/API/exam/changeBodyPosition';
import { fetchViewDetail } from '@/API/patient/viewActions';

interface BodyPositionListProps {
  layout: 'horizontal' | 'vertical';
  showAddButton?: boolean;
}

const BodyPositionList: React.FC<BodyPositionListProps> = ({
  layout,
  showAddButton = true,
}) => {
  const dispatch = useDispatch();
  const handleImageClick = (bodyPosition: ExtendedBodyPosition) => {
    message.info(`Clicked on ${bodyPosition.view_name}`);
    dispatch(
      setBodyPositionDetail({
        view_name: bodyPosition.view_name,
        view_description: bodyPosition.view_description,
        view_icon_name: bodyPosition.view_icon_name,
        patient_name: bodyPosition.patient_name,
        patient_id: bodyPosition.patient_id,
        registration_number: bodyPosition.registration_number,
        study_description: bodyPosition.study_description,
        body_position_image: bodyPosition.view_big_icon_name,
        collimator_length: bodyPosition.collimator_length,
        collimator_width: bodyPosition.collimator_width,
        sid: bodyPosition.sid,
      })
    );
    changeBodyPosition(bodyPosition.sop_instance_uid)
      .then(() => {
        message.success(
          `'Body position changed successfully' ${bodyPosition.sop_instance_uid}`
        );
      })
      .catch((error) => {
        console.error('Error changing body position:', error);
        message.error('Failed to change body position');
      });
  };
  const bodyPositions = useSelector(
    (state: RootState) => state.bodyPositionList.bodyPositions
  );
  // const selectedBodyPosition = useSelector(
  //   (state: RootState) => state.bodyPositionList.selectedBodyPosition
  // );
  const works = useSelector((state: RootState) => state.examWorksCache.works);

  const addBodyPositionClick = () => {
    // dispatch(addBodyPosition({
    //   view_name: 'New View',
    //   view_description: 'Description of the new view',
    //   view_icon_name: 'icon-name'
    // }));
  };

  useEffect(() => {
    const fetchBodyPositions = async () => {
      // alert(
      //   `${works.length} works found == ${works[0].Views.length} views in the first work`
      // );
      console.log(`体位信息：${JSON.stringify(works)}`);
      const bodyPositions: ExtendedBodyPosition[] = await Promise.all(
        works.flatMap((work) =>
          work.Views.map(async (view) => {
            const viewDetail = await fetchViewDetail(view.view_id);
            return {
              ...viewDetail,
              // sop_instance_uid: view.sop_instance_uid,
              collimator_length:
                viewDetail.config_object.DX.CollimatorSizeLength || 0,
              collimator_width:
                viewDetail.config_object.DX.CollimatorSizeWidth || 0,
              sid: '', //todo 这里还缺少值的来源
              patient_name: work.PatientName,
              patient_id: work.PatientID,
              registration_number: work.AccessionNumber,
              study_description: work.StudyDescription,
              body_position_image: viewDetail.view_icon_name,
              work: work,
              study_instance_uid: work.StudyInstanceUID,
              sop_instance_uid: view.PrimarySopUID,
            };
          })
        )
      );
      dispatch(setBodyPositions(bodyPositions));
      //选中第一个
      if (bodyPositions.length > 0) {
        dispatch(setSelectedBodyPosition(bodyPositions[0]));
      }
    };

    fetchBodyPositions();
  }, [works, dispatch]);

  return (
    <div className={`body-position-list ${layout}`}>
      <div>{bodyPositions.length}</div>
      {bodyPositions.map((bodyPosition, index) => (
        // {/* @/src\pages\exam\components\BodyPositionList.tsx 向ImageViewer传递src属性值时，首先要使用@/src\API\bodyPosition.ts 提供的方法做一个拼接*/}
        <ImageViewer
          key={index}
          src={getViewIconUrl(bodyPosition.view_icon_name)}
          className="image-viewer-item"
          onClick={() => handleImageClick(bodyPosition)}
        />
      ))}
      {showAddButton && (
        <Button
          icon={<PlusOutlined />}
          onClick={addBodyPositionClick}
          className="add-button"
        />
      )}
    </div>
  );
};

export default BodyPositionList;
