import { useState, useRef, useEffect } from 'react';
import { Box, Chip, Divider, alpha, Stack } from '@mui/material';
import { StageInfoForTooltip } from '../../../Stages/StageInfoForTooltip';

export const TooltipBox = ({
  left,
  translateY,
  formula,
  type = 'string',
  stageData = [],
  blocked = false,
  editor = null,
}) => {
  const [flipPosition, setFlipPosition] = useState(false);
  const [width, setWidth] = useState(false);
  const tooltipRef = useRef(null);

  useEffect(() => {
    const checkIfNeedsFlip = () => {
      if (!tooltipRef.current) return;

      const tooltipRect = tooltipRef.current.getBoundingClientRect();
      const actualWidth = tooltipRef.current.clientWidth;
      const viewportWidth = window.innerWidth;

      // Если тултип выходит за правый край экрана
      if (tooltipRect.right > viewportWidth - 10) {
        // 10px отступ
        setFlipPosition(true);
        setWidth(actualWidth);
      } else {
        setFlipPosition(false);
      }
    };

    // Проверяем после отрисовки
    setTimeout(checkIfNeedsFlip, 0);
    window.addEventListener('resize', checkIfNeedsFlip);

    return () => {
      window.removeEventListener('resize', checkIfNeedsFlip);
    };
  }, [left, translateY]);

  const getTypeDisplayName = (type) => {
    const typeMap = {
      formula: 'Формула',
      numeric: 'Число',
      text: 'Текст',
    };
    return typeMap[type] || 'Другое';
  };

  const getTypeColors = (chipType, theme) => {
    const typeColors = {
      formula: {
        bg: alpha(theme.palette.primary.main, 0.1),
        color: theme.palette.primary.main,
        border: alpha(theme.palette.primary.main, 0.3),
      },
      number: {
        bg: alpha(theme.palette.success.main, 0.1),
        color: theme.palette.success.main,
        border: alpha(theme.palette.success.main, 0.3),
      },
      string: {
        bg: alpha(theme.palette.warning.main, 0.1),
        color: theme.palette.warning.dark,
        border: alpha(theme.palette.warning.main, 0.3),
      },
      numeric: {
        bg: alpha(theme.palette.success.main, 0.1),
        color: theme.palette.success.main,
        border: alpha(theme.palette.success.main, 0.3),
      },
      text: {
        bg: alpha(theme.palette.warning.main, 0.1),
        color: theme.palette.warning.dark,
        border: alpha(theme.palette.warning.main, 0.3),
      },
      default: {
        bg: theme.palette.grey[100],
        color: theme.palette.grey[700],
        border: theme.palette.divider,
      },
    };

    return typeColors[chipType] || typeColors.default;
  };

  const getStatusColors = (theme, danger, warning) => ({
    backgroundColor: danger
      ? alpha(theme.palette.error.main, 0.1)
      : warning
        ? alpha(theme.palette.warning.main, 0.1)
        : alpha(theme.palette.success.main, 0.1),
    color: danger
      ? theme.palette.error.main
      : warning
        ? theme.palette.warning.color
        : theme.palette.success.main,
    border: `1px solid ${
      danger
        ? alpha(theme.palette.error.main, 0.3)
        : warning
          ? alpha(theme.palette.warning.main, 0.3)
          : alpha(theme.palette.success.main, 0.3)
    }`,
  });

  const isBlocked = blocked;

  return (
    <Box
      ref={tooltipRef}
      sx={(theme) => ({
        position: 'absolute',
        left: `${left}px`,
        transform: `translateY(${translateY}px)`,
        top: '3rem',
        border: `1px solid ${theme.palette.divider}`,
        borderRadius: '1rem',
        padding: '1.25rem',
        width: '22rem',
        boxShadow: theme.shadows[2],
        zIndex: theme.zIndex.tooltip,
        display: 'flex',
        flexDirection: 'column',
        gap: '1rem',
        background: 'white',
        alignContent: 'center',
        ...(flipPosition && {
          left: left - width + 110,
        }),
      })}
    >
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: '0.375rem' }}>
        <Box
          sx={(theme) => ({
            color: theme.palette.text.primary,
            fontWeight: 600,
            fontSize: '0.813rem',
            lineHeight: 1.2,
          })}
        >
          Свойства ячейки
        </Box>
        <Stack sx={{ flexDirection: 'row', gap: 0.5, flexWrap: 'wrap' }}>
          <Chip
            label={getTypeDisplayName(type)}
            size="small"
            sx={(theme) => {
              const colors = getTypeColors(type, theme);
              return {
                backgroundColor: colors.bg,
                color: colors.color,
                border: `1px solid ${colors.border}`,
                borderRadius: theme.shape.borderRadius,
                height: '1.5rem',
                fontSize: '0.688rem',
                fontWeight: 500,
                '& .MuiChip-label': {
                  paddingLeft: theme.spacing(0.5),
                  paddingRight: theme.spacing(0.5),
                  paddingTop: 0,
                  paddingBottom: 0,
                },
              };
            }}
          />
          <Chip
            label={isBlocked ? 'Заблокирована' : 'Редактируемая'}
            size="small"
            sx={(theme) => ({
              ...getStatusColors(theme, isBlocked, false),
              borderRadius: theme.shape.borderRadius,
              height: '1.5rem',
              fontSize: '0.688rem',
              fontWeight: 500,
              width: 'max-content',
              '& .MuiChip-label': {
                paddingLeft: theme.spacing(0.5),
                paddingRight: theme.spacing(0.5),
                paddingTop: 0,
                paddingBottom: 0,
              },
            })}
          />
        </Stack>
        {editor && (
          <Chip
            label={'Редактируется другим пользователем'}
            size="small"
            sx={(theme) => ({
              ...getStatusColors(theme, false, true),
              borderRadius: theme.shape.borderRadius,
              height: '1.5rem',
              fontSize: '0.688rem',
              fontWeight: 500,
              width: 'max-content',
              '& .MuiChip-label': {
                paddingLeft: theme.spacing(0.5),
                paddingRight: theme.spacing(0.5),
                paddingTop: 0,
                paddingBottom: 0,
              },
            })}
          />
        )}
      </Box>

      {/* Формула */}
      {formula && (
        <>
          <Divider sx={{ marginTop: '0 !important' }} />
          <Stack
            sx={{
              flexDirection: 'row',
              flexWrap: 'wrap',
              gap: '.5rem',
              margin: '0 !important',
            }}
          >
            <Box
              component="span"
              sx={{
                fontWeight: '400',
                fontSize: '0.88rem',
                lineHeight: '143%',
                color: '#4a5565',
              }}
            >
              Формула&nbsp;&nbsp;–
            </Box>
            <Box
              component="span"
              sx={{
                fontWeight: '400',
                fontSize: '0.88rem',
                lineHeight: '143%',
                margin: '0 !important',
              }}
            >
              {formula}
            </Box>
          </Stack>
        </>
      )}

      {stageData.length > 0 && (
        <>
          <StageInfoForTooltip stageData={stageData} />
        </>
      )}
    </Box>
  );
};