import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Button, Tooltip, message } from 'antd';
import { useIntl } from 'react-intl';
import { RootState, AppDispatch } from '../../../states/store';
import { deleteBodyPosition } from '../../../API/patient/viewActions';
import { copyPositionThunk } from '../../../states/exam/examWorksCacheSlice';
import {
  removeBodyPositionBySopInstanceUid,
  setByIndex,
} from '../../../states/exam/bodyPositionListSlice';
import Icon from '@/components/Icon';
import AppendViewModal from './AppendViewModal';

const BodyPositionActionButtons: React.FC = () => {
  const intl = useIntl();
  const dispatch = useDispatch<AppDispatch>();

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

  const [isAppendModalOpen, setIsAppendModalOpen] = useState(false);

  const addBodyPositionClick = (): void => {
    console.log('[BodyPositionActionButtons] Add button clicked');
    console.log(
      '[BodyPositionActionButtons] selectedBodyPosition:',
      selectedBodyPosition
    );
    if (!selectedBodyPosition) {
      message.warning('请先选择一个体位');
      return;
    }
    console.log('[BodyPositionActionButtons] Opening append modal');
    setIsAppendModalOpen(true);
  };

  const handleDelete = async () => {
    if (!selectedBodyPosition) {
      message.warning('请先选择一个体位');
      return;
    }

    // 检查体位数量，至少保留一个
    if (bodyPositions.length <= 1) {
      message.warning('至少需要保留一个体位，无法删除');
      return;
    }

    console.log(
      `选中的体位：${JSON.stringify(selectedBodyPosition)}`
    );
    if (selectedBodyPosition.sop_instance_uid) {
      try {
        await deleteBodyPosition(selectedBodyPosition.sop_instance_uid);
        dispatch(
          removeBodyPositionBySopInstanceUid(
            selectedBodyPosition.sop_instance_uid
          )
        );
        dispatch(setByIndex(0));
        message.success('体位删除成功');
      } catch (error) {
        console.error('Error deleting body position:', error);
        message.error('删除体位失败');
      }
    }
  };

  const handleCopy = () => {
    const instanceUid =
      selectedBodyPosition?.study_instance_uid ?? '';
    console.log('Copying position for instance UID:', instanceUid);
    console.log(
      `${JSON.stringify(selectedBodyPosition)}`
    );
    if (instanceUid) {
      dispatch(copyPositionThunk({ instanceUid }));
    } else {
      message.warning('无法获取体位信息');
    }
  };

  return (
    <>
      <div className="flex justify-center gap-2">
        <Tooltip title={intl.formatMessage({ id: 'exam.action.addMorePositions' })}>
          <Button
            style={{ width: '1.5rem', height: '1.5rem' }}
            icon={
              <Icon
                module="module-exam"
                name="btn_AppendView"
                userId="base"
                theme="default"
                size="2x"
                state="normal"
                style={{fontSize: '48px'}}
              />
            }
            onClick={addBodyPositionClick}
          />
        </Tooltip>

        <Tooltip title={intl.formatMessage({ id: 'exam.action.deletePosition' })}>
          <Button
            style={{ width: '1.5rem', height: '1.5rem' }}
            icon={
              <Icon
                module="module-exam"
                name="btn_DeleteView"
                userId="base"
                theme="default"
                size="2x"
                state="normal"
              />
            }
            onClick={handleDelete}
          />
        </Tooltip>

        <Tooltip title={intl.formatMessage({ id: 'exam.action.copyPosition' })}>
          <Button
            style={{ width: '1.5rem', height: '1.5rem' }}
            icon={
              <Icon
                module="module-exam"
                name="btn_Copy"
                userId="base"
                theme="default"
                size="2x"
                state="normal"
              />
            }
            onClick={handleCopy}
          />
        </Tooltip>
      </div>

      <AppendViewModal
        open={isAppendModalOpen}
        onCancel={() => setIsAppendModalOpen(false)}
        onSuccess={() => {
          setIsAppendModalOpen(false);
        }}
      />
    </>
  );
};

export default BodyPositionActionButtons;
