import {
  Row,
  Col,
  Select,
  InputNumber,
  Button,
  Switch,
  Divider,
  Tooltip,
  message,
  Flex,
} from 'antd';
import ErrorMessage from '@/components/ErrorMessage';
import { patientSizes, PatientSize } from '../../states/patientSize';
import { WorkstationTypeLabels } from '../../states/workstation';
import { FormattedMessage } from 'react-intl';
import { useSelector, useDispatch, useStore } from 'react-redux';
import { deleteBodyPosition } from '../../API/patient/viewActions';
import { copyPositionThunk } from '../../states/exam/examWorksCacheSlice';
import {
  removeBodyPositionBySopInstanceUid,
  setByIndex,
} from '../../states/exam/bodyPositionListSlice';
import { RootState } from '../../states/store';
import {
  setAprConfig,
  setBodysize,
  setWorkstation,
  setIsAECEnabled,
  setCurrentExposureMode,
} from '../../states/exam/aprSlice';
import BodyPositionList from './components/BodyPositionList';
import BodyPositionDetail from './components/BodyPositionDetail';
import { AppDispatch } from '@/states/store';
import { useRef } from 'react';
import Icon from '@/components/Icon';
import ParaSettingCoordinator from '@/domain/exam/paraSettingCoordinator';
import { resetDevices } from '@/states/device/deviceSlice';

const ContentAreaLarge = () => {
  const dispatch = useDispatch<AppDispatch>();
  const isResetting = useSelector(
    (state: RootState) => state.device.status === 'loading'
  );
  const store = useStore<RootState>();
  const aprConfig = useSelector((state: RootState) => state.apr.aprConfig);
  const bodysize = useSelector((state: RootState) => state.apr.bodysize);
  const workstation = useSelector((state: RootState) => state.apr.workstation);
  const isAECEnabled = useSelector(
    (state: RootState) => state.apr.isAECEnabled
  );
  const currentExposureMode = useSelector(
    (state: RootState) => state.apr.currentExposureMode
  );
  const productName = useSelector(
    (state: RootState) => state.product.productName
  );

  const handleBodysizeChange = (key: string) => {
    const value = patientSizes[key as PatientSize]; // 获取对应的显示文本
    console.log('体型 key:', key); // 例如: 'small'
    console.log('体型 value:', value); // 例如: 'Small'

    dispatch(setBodysize(key));
  };

  const handleWorkstationChange = (value: string) => {
    dispatch(setWorkstation(value));
  };

  const handleAECChange = (checked: boolean) => {
    dispatch(setIsAECEnabled(checked));
  };

  const handleExposureModeChange = (value: string) => {
    dispatch(setCurrentExposureMode(value));
  };

  const handleResetParameters = async () => {
    try {
      await dispatch(resetDevices());
    } catch (error) {
      console.error('Error resetting devices:', error);
    }
  };

  // 1. 正常在顶层用 useSelector 订阅
  const selectedBodyPosition = useSelector(
    (state: RootState) => state.bodyPositionList.selectedBodyPosition
  );

  // 2. 用 ref 保存最新值（每次渲染都会更新）
  const positionRef = useRef(selectedBodyPosition);
  positionRef.current = selectedBodyPosition;

  return (
    <Row className="w-full p-1" style={{ height: '100%', display: 'flex' }}>
      <Col span={20} style={{ display: 'flex', flexDirection: 'column' }}>
        <Row gutter={16} style={{ flex: 1, minHeight: 0, display: 'flex' }}>
          <Col span={4} className="flex flex-col">
            <BodyPositionList layout="vertical"></BodyPositionList>
          </Col>
          <Col span={20}>
            <BodyPositionDetail />
          </Col>
        </Row>
      </Col>
      <Col
        span={4}
        style={{ height: '100%', overflowY: 'auto', flexShrink: 0 }}
      >
        <Row gutter={16} align="middle">
          <Col span={productName === 'DROS' ? 9 : 24}>
            <Select
              placeholder="选择体型"
              style={{ width: '100%', marginBottom: 8 }}
              value={bodysize}
              onChange={handleBodysizeChange}
            >
              {Object.entries(patientSizes).map(
                ([key, value]: [string, string]) => (
                  <Select.Option key={key} value={key}>
                    <FormattedMessage id={value} />
                  </Select.Option>
                )
              )}
            </Select>
          </Col>
          {productName === 'DROS' && (
            <Col span={15}>
              <Select
                placeholder="选择工作位"
                style={{ width: '100%', marginBottom: 8 }}
                value={workstation}
                onChange={handleWorkstationChange}
              >
                {Object.entries(WorkstationTypeLabels).map(
                  ([key, value]: [string, string]) => (
                    <Select.Option key={key} value={value}>
                      <FormattedMessage
                        id={`workstation.${key.toLowerCase()}`}
                      />
                    </Select.Option>
                  )
                )}
              </Select>
            </Col>
          )}
        </Row>
        <div>
          <div>
            <label
              style={{ display: 'block', marginBottom: 4, fontSize: '12px' }}
            >
              mA
            </label>
            <InputNumber
              placeholder="mA"
              style={{ width: '100%', marginBottom: 8 }}
              value={aprConfig.mA ?? undefined}
              onChange={(value) =>
                dispatch(setAprConfig({ ...aprConfig, mA: value ?? 0 }))
              }
              onStep={(value, info) => {
                if (info.type === 'up') {
                  ParaSettingCoordinator.increaseMA();
                } else {
                  ParaSettingCoordinator.decreaseMA();
                }
              }}
            />
          </div>
          <div>
            <label
              style={{ display: 'block', marginBottom: 4, fontSize: '12px' }}
            >
              ms
            </label>
            <InputNumber
              placeholder="ms"
              style={{ width: '100%', marginBottom: 8 }}
              value={aprConfig.ms ?? undefined}
              onChange={(value) =>
                dispatch(setAprConfig({ ...aprConfig, ms: value ?? 0 }))
              }
              onStep={(value, info) => {
                if (info.type === 'up') {
                  ParaSettingCoordinator.increaseMS();
                } else {
                  ParaSettingCoordinator.decreaseMS();
                }
              }}
            />
          </div>
          <div>
            <label
              style={{ display: 'block', marginBottom: 4, fontSize: '12px' }}
            >
              mAs
            </label>
            <InputNumber
              placeholder="mAs"
              style={{ width: '100%', marginBottom: 8 }}
              value={aprConfig.mAs ?? undefined}
              onChange={(value) =>
                dispatch(setAprConfig({ ...aprConfig, mAs: value ?? 0 }))
              }
              onStep={(value, info) => {
                if (info.type === 'up') {
                  ParaSettingCoordinator.increaseMAS();
                } else {
                  ParaSettingCoordinator.decreaseMAS();
                }
              }}
            />
          </div>
          <div>
            <label
              style={{ display: 'block', marginBottom: 4, fontSize: '12px' }}
            >
              KV
            </label>
            <InputNumber
              placeholder="KV"
              style={{ width: '100%', marginBottom: 8 }}
              value={aprConfig.kV ?? undefined}
              // onChange={(value) =>
              //   dispatch(setAprConfig({ ...aprConfig, kV: value ?? 0 }))
              // }

              onStep={(value, info) => {
                if (info.type === 'up') {
                  ParaSettingCoordinator.increaseKV();
                } else {
                  ParaSettingCoordinator.decreaseKV();
                }
              }}
            />
          </div>
          {/* <div>
            <label
              style={{ display: 'block', marginBottom: 4, fontSize: '12px' }}
            >
              density
            </label>
            <InputNumber
              placeholder="density"
              style={{ width: '100%', marginBottom: 8 }}
              value={aprConfig.AECDensity ?? undefined}
              onChange={(value) =>
                dispatch(setAprConfig({ ...aprConfig, AECDensity: value ?? 0 }))
              }
              onStep={(value, info) => {
                if (info.type === 'up') {
                  ParaSettingCoordinator.increaseDensity();
                } else {
                  ParaSettingCoordinator.decreaseDensity();
                }
              }}
            />
          </div> */}
        </div>
        <div>
          <label
            style={{ display: 'block', marginBottom: 4, fontSize: '12px' }}
          >
            曝光模式
          </label>
          <Select
            placeholder="选择曝光模式"
            value={currentExposureMode}
            onChange={handleExposureModeChange}
            style={{ width: '100%', marginBottom: 8 }}
          >
            <Select.Option value="mAs">mAs</Select.Option>
            <Select.Option value="time">time</Select.Option>
          </Select>
        </div>
        <div>
          <label
            style={{ display: 'block', marginBottom: 4, fontSize: '12px' }}
          >
            AEC
          </label>
          <Switch
            checkedChildren="开启AEC"
            unCheckedChildren="关闭AEC"
            checked={isAECEnabled}
            onChange={handleAECChange}
            style={{ marginBottom: 8 }}
          />
        </div>
        <Flex align="center" justify="start" gap="middle" wrap>
          <Button
            style={{ width: '1.5rem', height: '1.5rem' }}
            icon={
              <Icon
                module="module-exam"
                name="btn_ResetGenerator"
                userId="base"
                theme="default"
                size="2x"
                state="normal"
              />
            }
            title="重置参数"
            onClick={handleResetParameters}
            disabled={isResetting}
          />
        </Flex>
        <Divider />
        <Flex wrap gap="small">
          <Tooltip title="删除选择的体位">
            <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={async () => {
                const state = store.getState().bodyPositionList;
                const selectedBodyPosition = state.selectedBodyPosition;
                const bodyPositions = state.bodyPositions;

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

                console.log(
                  `选中的体位：${JSON.stringify(selectedBodyPosition)}`
                );
                if (
                  selectedBodyPosition &&
                  selectedBodyPosition.sop_instance_uid
                ) {
                  try {
                    await deleteBodyPosition(
                      selectedBodyPosition.sop_instance_uid
                    );
                    dispatch(
                      removeBodyPositionBySopInstanceUid(
                        selectedBodyPosition.sop_instance_uid
                      )
                    );
                    dispatch(setByIndex(0));
                  } catch (error) {
                    console.error('Error deleting body position:', error);
                    message.error('Failed to delete body position');
                  }
                }
              }}
            />
          </Tooltip>

          <Tooltip title="复制选择的体位">
            <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={() => {
                const instanceUid =
                  store.getState().bodyPositionList.selectedBodyPosition
                    ?.study_instance_uid ?? '';
                console.log('Copying position for instance UID:', instanceUid);
                console.log(
                  `${store.getState().bodyPositionList.selectedBodyPosition}`
                );
                dispatch(copyPositionThunk({ instanceUid }));
              }}
            />
          </Tooltip>

          <Tooltip title="保存参数">
            <Button
              style={{ width: '1.5rem', height: '1.5rem' }}
              icon={
                <Icon
                  module="module-exam"
                  name="btn_Save"
                  userId="base"
                  theme="default"
                  size="2x"
                  state="normal"
                />
              }
            />
          </Tooltip>

          <Tooltip title="打开/关闭摄像头">
            <Button
              style={{ width: '1.5rem', height: '1.5rem' }}
              icon={
                <Icon
                  module="module-exam"
                  name="btn_OpenCamera"
                  userId="base"
                  theme="default"
                  size="2x"
                  state="normal"
                />
              }
            />
          </Tooltip>

          <Tooltip title="拒绝">
            <Button
              style={{ width: '1.5rem', height: '1.5rem' }}
              icon={
                <Icon
                  module="module-exam"
                  name="btn_RejectImage"
                  userId="base"
                  theme="default"
                  size="2x"
                  state="normal"
                />
              }
            />
          </Tooltip>
        </Flex>
        <ErrorMessage />
      </Col>
    </Row>
  );
};

export default ContentAreaLarge;
