import React, { useState } from 'react';
import { Button, Flex, Divider } from 'antd';
import { useIntl } from 'react-intl';
import '@/themes/truncateText.css';
import { useDispatch } from 'react-redux';
import { setAction } from '@/states/view/functionAreaSlice';
import { switchToMeasurementPanel, switchToMorePanel, switchToAdvancedProcessingPanel, switchToRectCropPanel, switchToMarkPanel } from '@/states/panelSwitchSliceForView';
import Icon from '@/components/Icon';
import { showNotImplemented } from '@/utils/notificationHelper';
import { useAppSelector } from '@/states/store';
import { useButtonAvailability } from '@/utils/useButtonAvailability';
import { theme } from 'antd';
const { useToken } = theme;

// 有状态按钮列表 - 这些按钮代表持续的状态，不应在执行后清理action
const STATEFUL_BUTTON_ACTIONS = new Set([
  'Adjust Brightness and Contrast',
  'Magnifier',
]);

const FunctionButton = ({
  title,
  action,
  iconName,
}: {
  title: string;
  action: string;
  iconName: string;
}) => {
  const intl = useIntl();
  const dispatch = useDispatch();
  const themeType = useAppSelector((state) => state.theme.themeType);
  const activeTools = useAppSelector((state) => state.functionArea.activeTools);
  const { disabled } = useButtonAvailability(action);
  // 对于有状态按钮，基于工具激活状态；对于无状态按钮，基于action
  const isActive = STATEFUL_BUTTON_ACTIONS.has(action)
    ? activeTools[action] || false
    : false; // 无状态按钮不显示激活状态
  const [isHovered, setIsHovered] = useState(false);
  const colorPrimary = useToken().token.colorPrimary;

  // 根据状态计算Icon的样式
  const getIconStyle = () => {
    const baseStyle = {
      /*控制svg图标的大小，暂时使用这种fontSize方式 */
      fontSize: '48px',
    };
    if (disabled) {
      return { ...baseStyle, opacity: 0.4, filter: 'grayscale(1)' };
    }
    if (isActive) {
      return { ...baseStyle, color: colorPrimary };
    }
    if (isHovered) {
      return { ...baseStyle }; 
    }
    return { ...baseStyle }; // 默认颜色
  };

  const handleButtonClick = () => {
    if (disabled) {
      return;
    }

    if (action === 'Delete Digital Mask' ||
      action === 'Crop Selected Area' ||
      ['Image Comparison', 'Zoom Image', 'Reset Cursor', 'Pan', 'Snapshot',
      ].includes(action)
    ) {
      showNotImplemented('');
      return;
    }

    if (action === 'Image Measurement') {
      // 切换到测量面板
      dispatch(switchToMeasurementPanel());
    } else if (action === 'Rectangle Crop') {
      // 切换到矩形裁剪面板
      dispatch(switchToRectCropPanel());
    } else if (action === 'More') {
      // 切换到更多功能面板
      dispatch(switchToMorePanel());
    } else if (action === 'Advanced Processing') {
      // 切换到高级图像处理面板
      dispatch(switchToAdvancedProcessingPanel());
    } else if (action === 'AddMark') {
      // 切换到标记面板
      dispatch(switchToMarkPanel());
    } else {
      // 其他功能按钮保持原有逻辑
      dispatch(setAction(action));
    }
  };

  return (
    <Button
      onClick={handleButtonClick}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
      disabled={disabled}
      icon={
        <Icon
          module="module-process"
          name={iconName}
          userId="base"
          theme="default"
          size="2x"
          state="normal"
          style={getIconStyle()}
          className={`text-[${useToken().token.colorPrimary}] `}
        />
      }
      style={{
        width: '1.5rem',
        height: '1.5rem',
        padding: 0, // 关键
        border: isHovered ? `1px solid ${colorPrimary}` : '1px solid transparent',
        //backgroundColor: isHovered ? `${colorPrimary}` : 'transparent',
        //minWidth: 44,            // 保险
        //overflow: 'hidden',      // 超出的文字裁掉
      }}
      title={disabled ? `${title}${intl.formatMessage({ id: 'functionArea.disabledTooltipSuffix' })}` : title}
      className="truncate-text"
    >
      {/* {title} */}
    </Button>
  );
};

const FunctionArea = () => {
  const intl = useIntl();

  return (
    <Flex wrap gap="small" align="center" justify="start" className="p-1">
      <FunctionButton title={intl.formatMessage({ id: "functionArea.addLMark" })} action="Add L Mark" iconName="LMark" />
      <FunctionButton title={intl.formatMessage({ id: "functionArea.addRMark" })} action="Add R Mark" iconName="RMark" />
      <FunctionButton title={intl.formatMessage({ id: "functionArea.addMark" })} action="AddMark" iconName="AddMark" />
      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.deleteSelectedMark" })}
        action="Delete Selected Mark"
        iconName="EraseMark"
      />
      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.horizontalFlip" })}
        action="Horizontal Flip"
        iconName="HReverse"
      />
      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.verticalFlip" })}
        action="Vertical Flip"
        iconName="VReverse"
      />
      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.rotateCounterclockwise90" })}
        action="Rotate Counterclockwise 90"
        iconName="RotateL90"
      />
      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.rotateClockwise90" })}
        action="Rotate Clockwise 90"
        iconName="RotateR90"
      />
      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.rotateAnyAngle" })}
        action="Rotate Any Angle"
        iconName="RotateAnyDegree"
      />
      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.cropSelectedArea" })}
        action="Crop Selected Area"
        iconName="Crop"
      />
      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.deleteDigitalMask" })}
        action="Delete Digital Mask"
        iconName="btn_RemoveCrop"
      />
      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.adjustBrightnessAndContrast" })}
        action="Adjust Brightness and Contrast"
        iconName="btn_BrightnessContrast"
      />
      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.addMask" })}
        action="Add Mask"
        iconName="AddMask"
      />
      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.deleteMask" })}
        action="Delete Mask"
        iconName="DeleteMask"
      />
      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.imageComparison" })}
        action="Image Comparison"
        iconName="btn_Compare"
      />
      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.invertContrast" })}
        action="Invert Contrast"
        iconName="btn_ReverseColour"
      />
      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.1x1Layout" })}
        action="1x1 Layout"
        iconName="1x1_normal"
      />
      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.1x2Layout" })}
        action="1x2 Layout"
        iconName="1x2_normal"
      />
      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.2x2Layout" })}
        action="2x2 Layout"
        iconName="2x1_normal"
      />
      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.4x4Layout" })}
        action="4x4 Layout"
        iconName="2x2_normal"
      />
      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.magnifier" })}
        action="Magnifier"
        iconName="Magnifier"
      />
      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.fitSize" })}
        action="Fit Size"
        iconName="FitInWindow"
      />
      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.originalSize" })}
        action="Original Size"
        iconName="1by1_normal"
      />
      <FunctionButton title={intl.formatMessage({ id: "functionArea.zoomImage" })} action="Zoom Image" iconName="Zoom" />
      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.resetCursor" })}
        action="Reset Cursor"
        iconName="btn_pointer"
      />
      <FunctionButton title={intl.formatMessage({ id: "functionArea.pan" })} action="Pan" iconName="Pan" />
      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.invertImage" })}
        action="Invert Image"
        iconName="Invert"
      />
      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.resetImage" })}
        action="Reset Image"
        iconName="Reset"
      />
      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.snapshot" })}
        action="Snapshot"
        iconName="imgsnapshot"
      />
      <Divider type="horizontal" style={{ height: 'auto', margin: '8px' }} />
      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.advancedProcessing" })}
        action="Advanced Processing"
        iconName="btn_Imageprocess"
      />

      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.imageMeasurement" })}
        action="Image Measurement"
        iconName="btn_Measurements"
      />
      <FunctionButton
        title={intl.formatMessage({ id: "functionArea.rectangleCrop" })}
        action="Rectangle Crop"
        iconName="rectangle-crop"
      />
      <FunctionButton title={intl.formatMessage({ id: "functionArea.more" })} action="More" iconName="btn_OtherSetting" />
    </Flex>
  );
};

export default FunctionArea;
