import React, { useState } from 'react';
import { Flex } from 'antd';
import { FormattedMessage } from 'react-intl';
import { useSelector } from 'react-redux';
import {
  DataState,
  getBtnAvailability,
  LocationKey,
} from '@/domain/permissionMap';
import { RootState } from '@/states/store';
import { IconButton } from '@/components/IconButton';
import Icon from '@/components/Icon';

interface BusinessZoneProps {
  onMenuClick?: (key: string) => void;
}

function useItems(btnAvailability: Record<string, boolean>, productName: 'DROS' | 'VETDROS') {
  const isAnimalProduct = productName === 'VETDROS';
  return [
    {
      key: 'patient_management',
      label: (
        <FormattedMessage
          id={isAnimalProduct ? "animal.patient" : "patient"}
          defaultMessage={'语言包中没有定义patient的翻译文本'}
        />
      ),
      icon: 'Registration',
      disabled: !btnAvailability['patient_management'],
      children: [
        {
          key: 'register',
          disabled: !btnAvailability['register'],
          label: (
            <FormattedMessage
              id="register"
              defaultMessage={'语言包中没有定义patient的翻译文本'}
            />
          ),
          icon: 'Registration',
        },
        {
          key: 'worklist',
          disabled: !btnAvailability['worklist'],
          label: (
            <FormattedMessage
              id="tasklist"
              defaultMessage={'语言包中没有定义patient的翻译文本'}
            />
          ),
          icon: 'Worklist',
        },
        {
          key: 'historylist',
          disabled: !btnAvailability['historylist'],
          label: (
            <FormattedMessage
              id="historylist"
              defaultMessage={'语言包中没有定义patient的翻译文本'}
            />
          ),
          icon: 'Registration',
        },
        ...(isAnimalProduct ? [] : [{
          key: 'archivelist',
          disabled: !btnAvailability['archivelist'],
          label: (
            <FormattedMessage
              id="archivelist"
              defaultMessage={'语言包中没有定义patient的翻译文本'}
            />
          ),
          icon: 'Registration',
        }]),
        ...(isAnimalProduct ? [] : [{
          key: 'bin',
          disabled: !btnAvailability['bin'],
          label: (
            <FormattedMessage
              id="bin"
              defaultMessage={'语言包中没有定义patient的翻译文本'}
            />
          ),
        }]),
        {
          key: 'outputlist',
          disabled: !btnAvailability['outputlist'],
          label: (
            <FormattedMessage
              id="outputlist"
              defaultMessage={'语言包中没有定义patient的翻译文本'}
            />
          ),
          icon: 'Registration',
        },
      ],
    },
    // {
    //   key: 'emergency',
    //   icon: 'Emergency',
    //   label: '急诊',
    //   disabled: false,
    // },
    {
      key: 'exam',
      disabled:
        (console.log(`我要看看exam对应的值：${!btnAvailability['exam']}`),
        !btnAvailability['exam']),
      label: (
        <FormattedMessage
          id="exam"
          defaultMessage={'语言包中没有定义patient的翻译文本'}
        />
      ),
      icon: 'Exam',
    },
    {
      type: 'divider',
    },
    {
      key: 'process',
      disabled:
        (console.log(
          `我要看看[process]对应的值：${!btnAvailability['process']}`
        ),
        !btnAvailability['process']),
      label: (
        <FormattedMessage
          id="process"
          defaultMessage={'语言包中没有定义patient的翻译文本'}
        />
      ),
      icon: 'Process',
    },
    {
      key: 'print',
      disabled: !btnAvailability['print'],
      label: (
        <FormattedMessage
          id="print"
          defaultMessage={'语言包中没有定义patient的翻译文本'}
        />
      ),
      icon: 'Output',
    },
  ];
}

const BusinessZone: React.FC<BusinessZoneProps> = ({ onMenuClick }) => {
  // eslint-disable-next-line
  const currentKey = useSelector((state: RootState) => state.BusinessFlow.currentKey);
  const productName = useSelector((state: RootState) => state.product.productName);
  console.log('Current Business Flow Key:', currentKey);
  const dataState: DataState = useSelector((state: RootState) => {
    if (currentKey === 'worklist') {
      return {
        hasSelection: state.workSelection.selectedIds.length > 0,
        hasExposedImage:
          state.bodyPositionList.exposureStatus === 'Half Exposed' ||
          state.bodyPositionList.exposureStatus === 'Fully Exposed',
      };
    } else if (currentKey === 'historylist') {
      return {
        hasSelection: state.historySelection.selectedIds.length > 0,
        hasExposedImage:
          state.bodyPositionList.exposureStatus === 'Half Exposed' ||
          state.bodyPositionList.exposureStatus === 'Fully Exposed',
      };
    } else if (currentKey === 'exam') {
      return {
        // hasSelection: state.historySelection.selectedIds.length > 0,
        hasExposedImage:
          state.bodyPositionList.exposureStatus === 'Half Exposed' ||
          state.bodyPositionList.exposureStatus === 'Fully Exposed',
      };
    } else {
      return {};
    }
  });
  const btnAvailability = getBtnAvailability(
    currentKey as LocationKey,
    dataState
  );
  console.log('Button Availability:', btnAvailability);
  const items = useItems(btnAvailability, productName);

  // const [visibleItems, setVisibleItems] = useState(items);
  const [floatingMenuVisible, setFloatingMenuVisible] = useState(true);
  // const businessZoneRef = useRef<HTMLDivElement>(null);

  // useEffect(() => {
  //   const handleResize = () => {
  //     if (businessZoneRef.current) {
  //       const businessZoneHeight = businessZoneRef.current.offsetHeight;
  //       const windowHeight = window.innerHeight;
  //       const systemZoneHeight = 100; // Assuming SystemZone height is fixed

  //       if (businessZoneHeight + systemZoneHeight > windowHeight) {
  //         const visibleCount = Math.floor(
  //           (windowHeight - systemZoneHeight) / 50
  //         ); // Assuming each button height is 50px
  //         setVisibleItems(items.slice(0, visibleCount));
  //       } else {
  //         setVisibleItems(items);
  //       }
  //     }
  //   };

  //   window.addEventListener('resize', handleResize);
  //   handleResize(); // Initial check

  //   return () => {
  //     window.removeEventListener('resize', handleResize);
  //   };
  // }, [items]);

  const handlePatientManagementClick = () => {
    setFloatingMenuVisible(!floatingMenuVisible);
  };

  const buttonClassNameGenerator = (
    itemkey: string,
    currentkey: string
  ): string => {
    const originalName =
      'w-full max-w-full whitespace-nowrap overflow-hidden text-ellipsis min-w-0 truncate';
    if (itemkey === currentkey) {
      return originalName + ' border border-red-500 ';
    }
    return originalName;
  };

  useSelector((state: RootState) => state.permission.triggerPermissionCalc);

  return (
    // <div

    //   className="grid grid-rows-[1fr]  flex-grow h-0 overflow-y-auto"
    // >

    <Flex vertical className=" min-h-0 overflow-y-auto flex-grow px-1">
      {items.map((item) =>
        item.type === 'divider' ? (
          <hr
            key="divider"
            style={{
              width: '100%',
              borderTop: '1px solid #f0f0f0',
              margin: '8px 0',
            }}
          />
        ) : (
          <>
            <IconButton
              data-testid={item.key}
              onClick={
                item.key === 'patient_management'
                  ? handlePatientManagementClick
                  : () => onMenuClick?.(item.key ?? 'error')
              }
              iconSize={56}
              iconPlace="left"
              icon={
                <Icon
                  module="module-common"
                  name={item.icon ?? ''}
                  userId="user-A"
                  theme="default"
                  size="2x"
                  state="normal"
                />
              }
              style={{
                //flex: 1,
                minWidth: 0,
                overflow: 'hidden', // 超出隐藏
                textOverflow: 'ellipsis', // 超出用省略号
                whiteSpace: 'nowrap', // 不换行
                padding: '0px',
                minHeight: '1.5rem',
              }}
              className={buttonClassNameGenerator(
                item.key as string,
                currentKey
              )}
              disabled={item.disabled}
            >
              <span
                style={{
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  display: 'block', // 或 inline-block
                  flex: 1, // 占据剩余空间并允许收缩
                  minWidth: 0, // 再次确保可以收缩
                }}
              >
                {item.label}
              </span>
            </IconButton>

            {item.key === 'patient_management' && floatingMenuVisible && (
              <Flex vertical className="px-1">
                {item.children?.map((child) => (
                  <IconButton
                    data-testid={child.key}
                    iconSize={56}
                    icon={
                      <Icon
                        module="module-common"
                        name={item.icon ?? ''}
                        userId="user-A"
                        theme="default"
                        size="2x"
                        state="normal"
                      />
                    }
                    key={child.key}
                    onClick={() => onMenuClick?.(child.key)}
                    className={buttonClassNameGenerator(
                      child.key as string,
                      currentKey
                    )}
                    style={{
                      //flex: 1,
                      minWidth: 0,
                      overflow: 'hidden', // 超出隐藏
                      textOverflow: 'ellipsis', // 超出用省略号
                      whiteSpace: 'nowrap', // 不换行
                      padding: '0px',
                    }}
                    disabled={item.disabled}
                  >
                    <span
                      style={{
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap',
                        display: 'block', // 或 inline-block
                        flex: 1, // 占据剩余空间并允许收缩
                        minWidth: 0, // 再次确保可以收缩
                      }}
                    >
                      {child.label}
                    </span>
                  </IconButton>
                ))}
              </Flex>
            )}
          </>
        )
      )}
    </Flex>

    // </div>
  );
};

export default BusinessZone;
