import React from 'react';
import { Button, Tooltip, Modal, message } from 'antd';
import { useDispatch, useSelector } from 'react-redux';
import {
  deleteWorkThunk,
  lockWorkInWorklistThunk,
} from '@/states/patient/worklist/slices/workSlice';
import { switchToSendPanel } from '@/states/patient/worklist/slices/historyPanelSwitchSlice';
import { FormattedMessage } from 'react-intl';
import { AppDispatch, RootState, useAppSelector } from '@/states/store';
import Icon from '@/components/Icon';
import DiagnosticReport from '../DiagnosticReport';
import { Popup } from 'antd-mobile';
import { setVisible } from '@/states/patient/DiagnosticReport/slice';
import EditTaskModal from './EditTaskModal';
import { openEditModal } from '@/states/patient/edit/editFormSlice';

interface ActionButtonProps {
  icon: React.ReactNode;
  tooltip: React.ReactNode;
  onClick?: () => void;
}

const ActionButton: React.FC<ActionButtonProps> = ({
  icon,
  tooltip,
  onClick,
}) => (
  <Tooltip title={tooltip}>
    <Button icon={icon} onClick={onClick} style={{ width: '2.5rem' }} />
  </Tooltip>
);

const ActionPanel: React.FC = () => {
  const dispatch = useDispatch<AppDispatch>();

  const workSelectedIds = useSelector(
    (state: RootState) => state.workSelection.selectedIds
  );
  const historySelectedIds = useSelector(
    (state: RootState) => state.historySelection.selectedIds
  );
  const visible = useSelector(
    (state: RootState) => state.diagnosticReport.visible
  );
  const themeType = useAppSelector((state) => state.theme.themeType);
  const currentKey = useSelector(
    (state: RootState) => state.BusinessFlow.currentKey
  );
  const workEntities = useSelector(
    (state: RootState) => state.workEntities.data
  );
  const workEntitiesFromHistory = useSelector(
    (state: RootState) => state.historyEntities.data
  );
  // 使用 worklist 或 history 的选中项，取决于哪个有值
  const selectedIds =
    workSelectedIds.length > 0 ? workSelectedIds : historySelectedIds;

  const handleDelete = () => {
    if (selectedIds.length === 0) {
      message.warning('请先选择要删除的项目');
      return;
    }

    Modal.confirm({
      title: '确认删除',
      content: `确定要删除选中的 ${selectedIds.length} 个项目吗？此操作不可撤销。`,
      okText: '确认删除',
      cancelText: '取消',
      okButtonProps: { danger: true },
      centered: true,
      onOk: () => {
        dispatch(deleteWorkThunk(selectedIds));
      },
    });
  };

  const handleSend = () => {
    dispatch(switchToSendPanel());
  };

  const handleShowReport = () => {
    dispatch(setVisible(true));
  };
  const getSelectedWorkIds = () => {
    const selectedIds =
      currentKey === 'worklist' ? workSelectedIds : historySelectedIds;
    return selectedIds;
  };

  const getWorksFromWorklistOrHistory = () => {
    return currentKey === 'worklist' ? workEntities : workEntitiesFromHistory;
  };
  const handleEdit = () => {
    const selectedIds = getSelectedWorkIds();

    if (selectedIds.length === 0) {
      message.warning('请先选择要编辑的任务');
      return;
    }

    if (selectedIds.length > 1) {
      message.warning('只能编辑一个任务');
      return;
    }

    const works = getWorksFromWorklistOrHistory();
    const task = works.find((item) => item.StudyID === selectedIds[0]);

    if (task) {
      // 通过 dispatch action 传递数据到 slice
      dispatch(openEditModal(task));
    }
  };

  const handleLock = () => {
    const selectedIds = getSelectedWorkIds();

    // 2. 检查是否有选中项
    if (selectedIds.length === 0) {
      message.warning('请先选择要锁定/解锁的项目');
      return;
    }
    // 3. 获取第一个选中项的锁定状态
    const works = getWorksFromWorklistOrHistory();
    const selectedItem = works.find((item) => item.StudyID === selectedIds[0]);
    if (!selectedItem) return;

    // 4. 根据当前状态切换
    const newLockState =
      selectedItem.StudyLock === 'Locked' ? 'Unlocked' : 'Locked';

    // 为每个选中项执行锁定/解锁操作
    selectedIds.forEach((studyId) => {
      console.log(
        `锁定，触发action ，目标 studyid是 ${studyId}，新状态是 ${newLockState}`
      );
      dispatch(lockWorkInWorklistThunk({ studyId, lock: newLockState }));
    });
  };

  return (
    <div className="flex flex-wrap gap-2 w-full">
      <ActionButton
        icon={
          <Icon
            module="module-patient"
            name="Delete"
            userId="base"
            theme="default"
            size="2x"
            state="normal"
          />
        }
        tooltip={
          <FormattedMessage
            id="actionPanel.deleteTask"
            defaultMessage="actionPanel.deleteTask"
          />
        }
        onClick={handleDelete}
      />
      <ActionButton
        icon={
          <Icon
            module="module-patient"
            name="EditPatient"
            userId="base"
            theme="default"
            size="2x"
            state="normal"
          />
        }
        tooltip={
          <FormattedMessage
            id="actionPanel.editPatient"
            defaultMessage="actionPanel.editPatient"
          />
        }
        onClick={handleEdit}
      />
      <ActionButton
        icon={
          <Icon
            module="module-patient"
            name="Protect"
            userId="base"
            theme="default"
            size="2x"
            state="normal"
          />
        }
        tooltip={
          <FormattedMessage
            id="actionPanel.lockTask"
            defaultMessage="actionPanel.lockTask"
          />
        }
        onClick={handleLock}
      />
      <ActionButton
        icon={
          <Icon
            module="module-patient"
            name="RIS"
            userId="base"
            theme="default"
            size="2x"
            state="normal"
          />
        }
        tooltip={
          <FormattedMessage
            id="actionPanel.risSync"
            defaultMessage="actionPanel.risSync"
          />
        }
      />
      <ActionButton
        icon={
          <Icon
            module="module-patient"
            name="ReRegister"
            userId="base"
            theme="default"
            size="2x"
            state="normal"
          />
        }
        tooltip={
          <FormattedMessage
            id="actionPanel.reRegister"
            defaultMessage="actionPanel.reRegister"
          />
        }
      />
      <ActionButton
        icon={
          <Icon
            module="module-patient"
            name="btn_SaveLocally"
            userId="base"
            theme="default"
            size="2x"
            state="normal"
          />
        }
        tooltip={
          <FormattedMessage
            id="actionPanel.saveLocal"
            defaultMessage="actionPanel.saveLocal"
          />
        }
      />
      <ActionButton
        icon={
          <Icon
            module="module-patient"
            name="btn_Import"
            userId="base"
            theme="default"
            size="2x"
            state="normal"
          />
        }
        tooltip={
          <FormattedMessage
            id="actionPanel.importXLS"
            defaultMessage="actionPanel.importXLS"
          />
        }
      />
      <ActionButton
        icon={
          <Icon
            module="module-patient"
            name="Sort"
            userId="base"
            theme="default"
            size="2x"
            state="normal"
          />
        }
        tooltip={
          <FormattedMessage
            id="actionPanel.sortList"
            defaultMessage="actionPanel.sortList"
          />
        }
      />
      <ActionButton
        icon={
          <Icon
            module="module-patient"
            name="CloudShare"
            userId="base"
            theme="default"
            size="2x"
            state="normal"
          />
        }
        tooltip={
          <FormattedMessage
            id="actionPanel.cloudShare"
            defaultMessage="actionPanel.cloudShare"
          />
        }
      />
      <ActionButton
        icon={
          <Icon
            module="module-patient"
            name="Swap"
            userId="base"
            theme="default"
            size="2x"
            state="normal"
          />
        }
        tooltip={
          <FormattedMessage
            id="actionPanel.imageExchange"
            defaultMessage="actionPanel.imageExchange"
          />
        }
      />
      <ActionButton
        icon={
          <Icon
            module="module-patient"
            name="QRCodePrint"
            userId="base"
            theme="default"
            size="2x"
            state="normal"
          />
        }
        tooltip={
          <FormattedMessage
            id="actionPanel.qrPrint"
            defaultMessage="actionPanel.qrPrint"
          />
        }
      />
      <ActionButton
        icon={
          <Icon
            module="module-patient"
            name="Send"
            userId="base"
            theme="default"
            size="2x"
            state="normal"
          />
        }
        tooltip={
          <FormattedMessage
            id="actionPanel.send"
            defaultMessage="actionPanel.send"
          />
        }
        onClick={handleSend}
      />
      <ActionButton
        icon={
          <Icon
            module="module-patient"
            name="Export"
            userId="base"
            theme="default"
            size="2x"
            state="normal"
          />
        }
        tooltip={
          <FormattedMessage
            id="actionPanel.export"
            defaultMessage="actionPanel.export"
          />
        }
      />
      <ActionButton
        icon={
          <Icon
            module="module-patient"
            name="Import"
            userId="base"
            theme="default"
            size="2x"
            state="normal"
          />
        }
        tooltip={
          <FormattedMessage
            id="actionPanel.import"
            defaultMessage="actionPanel.import"
          />
        }
      />
      <ActionButton
        icon={
          <Icon
            module="module-patient"
            name="report"
            userId="base"
            theme={themeType}
            size="2x"
            state="normal"
            width={40}
            height={40}
          />
        }
        tooltip={
          <FormattedMessage
            id="actionPanel.showReport"
            defaultMessage="actionPanel.showReport"
          />
        }
        onClick={handleShowReport}
      />
      <Popup
        visible={visible}
        onMaskClick={() => dispatch(setVisible(false))}
        position="right"
        bodyStyle={{ width: '100vw', height: '100vh' }}
      >
        <DiagnosticReport />
      </Popup>
      <EditTaskModal />
    </div>
  );
};

export default ActionPanel;
