import React, { useEffect } from 'react';
import { Modal, Row, Col, message, Button, Space } from 'antd';
import { useSelector, useDispatch } from 'react-redux';
import { RootState, AppDispatch } from '@/states/store';
import {
  clearSelectedViews,
  setModalOpen,
  appendViewsThunk,
  setCurrentBodyPart,
} from '@/states/exam/appendViewSlice';
import BodyPositionFilter from '@/pages/patient/components/bodyPositionFilter';
import RegisterAvailableList from '@/pages/patient/components/register.available.list';
import SelectedProtocolList from '@/pages/patient/components/register.selected.view.list';

interface AppendViewModalProps {
  open: boolean;
  onCancel: () => void;
  work?: any; // 可选的检查信息，用于worklist页面调用
  studyId?: string; // 可选的study ID，用于worklist页面调用
  currentWork?: any; // 可选的当前工作信息，用于worklist页面调用
  onSuccess?: () => void; // 可选的成功回调，用于追加成功后执行额外操作
}

const AppendViewModal: React.FC<AppendViewModalProps> = ({
  open,
  onCancel,
  work,
  studyId,
  currentWork,
  onSuccess,
}) => {
  console.log('[AppendViewModal] Rendering with open:', open);
  const dispatch = useDispatch<AppDispatch>();

  const selectedViews = useSelector(
    (state: RootState) => state.viewSelection.selectedViews
  );

  const selectedBodyPosition = useSelector(
    (state: RootState) => state.bodyPositionList.selectedBodyPosition
  );

  useEffect(() => {
    console.log(
      '[AppendViewModal] useEffect triggered, open:',
      open,
      'selectedBodyPosition:',
      selectedBodyPosition,
      'work:',
      work
    );
    if (open) {
      if (selectedBodyPosition) {
        // 正常检查页面：使用selectedBodyPosition
        const bodyPartId = selectedBodyPosition.body_part_id;
        dispatch(setCurrentBodyPart(bodyPartId));
      } else if (work) {
        // worklist页面：使用传入的work信息
        // 对于RIS数据，我们可能需要从其他地方获取bodyPart信息
        // 暂时设置为空，后面可以根据需要调整
        dispatch(setCurrentBodyPart(null));
      }
    }
  }, [open, selectedBodyPosition, work, dispatch]);

  const handleConfirm = async (): Promise<void> => {
    if (selectedViews.length === 0) {
      message.warning('请至少选择一个体位');
      return;
    }

    // 确定study_id和currentWork
    let finalStudyId: string;
    let finalCurrentWork: any;

    if (selectedBodyPosition) {
      // 正常检查页面：使用selectedBodyPosition
      finalStudyId = selectedBodyPosition.work.StudyID;
      finalCurrentWork = selectedBodyPosition.work;
    } else if (studyId && currentWork) {
      // worklist页面：使用传入的参数
      finalStudyId = studyId;
      finalCurrentWork = currentWork;
    } else {
      message.error('未找到当前检查信息');
      return;
    }
console.log(`[AppendViewModal] Appending views to Study ID: ${finalStudyId} 传递来的studyId：${studyId}`, selectedViews);
    try {
      await dispatch(
        appendViewsThunk({
          study_id: finalStudyId,
          views: selectedViews,
          currentWork: finalCurrentWork,
        })
      ).unwrap();

      message.success(`成功追加 ${selectedViews.length} 个体位`);
      //dispatch(setModalOpen(false));
      //onCancel();

      // 调用成功回调
      if (onSuccess) {
        onSuccess();
      }
    } catch (error) {
      message.error('追加体位失败');
      console.error('[AppendViewModal] Error appending views:', error);
    }
  };

  const handleCancel = (): void => {
    dispatch(clearSelectedViews());
    dispatch(setCurrentBodyPart(null));
    onCancel();
  };

  return (
    <Modal
      title="追加体位"
      open={open}
      onCancel={handleCancel}
      width="90%"
      style={{ top: 20 }}
      footer={
        <Space>
          <Button onClick={handleCancel}>取消</Button>
          <Button
            type="primary"
            onClick={handleConfirm}
            disabled={selectedViews.length === 0}
          >
            确认追加 {selectedViews.length > 0 && `(${selectedViews.length})`}
          </Button>
        </Space>
      }
    >
      <Row style={{ height: '70vh' }}>
        {/* 中间：体型结构区域 */}
        <Col
          span={8}
          style={{ height: '100%', borderRight: '1px solid #f0f0f0' }}
        >
          <BodyPositionFilter />
        </Col>

        {/* 右侧：待选择 + 已选择 */}
        <Col span={16} style={{ height: '100%' }}>
          <Row style={{ height: '100%' }}>
            <Col span={24} style={{ height: '50%' }}>
              <RegisterAvailableList />
            </Col>
            <Col span={24} style={{ height: '50%' }}>
              <SelectedProtocolList />
            </Col>
          </Row>
        </Col>
      </Row>
    </Modal>
  );
};

export default AppendViewModal;
