import { Box, Divider, Stack } from '@mui/material';
import { UnLockedSvg } from '../common/icons/icons';
import { ROLES_ID_RUSSIAN_NAME, EDIT_ACCESS_RUSSIAN } from '../../constants/constants';

export const StageInfoForTooltip = ({ stageData = [] }) => {
  const accessData = stageData[0] || [];
  const stagesData = stageData[1] || [];

  const formatDateShort = (dateString) => {
    if (!dateString) return '';
    try {
      const date = new Date(dateString);
      const day = date.getDate();
      const year =
        date.getFullYear() < 2000
          ? date.getFullYear() == 1970
            ? 'тек.'
            : 'след.'
          : date.getFullYear();
      const month = date
        .toLocaleDateString('ru-RU', { month: 'short' })
        .replace('.', '');
      return `${day} ${month}. ${year}`;
    } catch {
      return '';
    }
  };

  // Получаем информацию об этапах
  const getStagesInfo = () => {
    if (!stagesData || stagesData.length === 0) {
      return [
        {
          name: 'Нет этапов',
          period: 'Этапы не назначены для этой колонки',
        },
      ];
    }

    return stagesData.map((stage) => {
      const stageName = stage?.name || 'Без названия';
      const startDate = formatDateShort(stage.period_start);
      const endDate = formatDateShort(stage.period_end);

      return {
        name: stageName,
        period: `(${startDate} – ${endDate})`,
        id: stage.id,
      };
    });
  };

  // Получаем информацию о доступах пользователей
  const getAccessInfo = () => {
    if (!accessData || accessData.length === 0) {
      return [
        {
          roleName: 'Нет данных',
          accessLevel: 'Не определено',
        },
      ];
    }

    return accessData.map((access) => ({
      roleName: ROLES_ID_RUSSIAN_NAME[access.role_id] || 'N/A',
      accessLevel: EDIT_ACCESS_RUSSIAN[access.edit_id] || 'N/A',
    }));
  };

  const stagesInfo = getStagesInfo();
  const accessInfo = getAccessInfo();

  return (
    <>
      {/* Информация об этапах */}
      {stagesData.length > 0 && (
        <>
          <Divider sx={{ marginTop: '0 !important' }} />
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: '0.375rem' }}>
            <Stack
              sx={{
                flexDirection: 'row',
                flexWrap: 'wrap',
                gap: 1,
              }}
            >
              {stagesInfo.map((stage, index) => (
                <Box
                  key={stage.id || index}
                  sx={{
                    display: 'flex',
                    flexDirection: 'row',
                    gap: '.5rem',
                  }}
                >
                  <Box
                    sx={{
                      fontWeight: '400',
                      fontSize: '0.88rem',
                      lineHeight: '143%',
                    }}
                  >
                    {stage.name}
                  </Box>
                  <Box
                    sx={{
                      fontWeight: '400',
                      fontSize: '0.88rem',
                      lineHeight: '143%',
                      color: '#4a5565',
                    }}
                  >
                    {stage.period}
                  </Box>
                </Box>
              ))}
            </Stack>
          </Box>
        </>
      )}

      {/* Доступы пользователей */}
      {accessData.length > 0 && (
        <>
          <Divider sx={{ marginTop: '0 !important' }} />
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: '.5rem' }}>
            <Box sx={{ display: 'flex', gap: '.5rem', alignItems: 'center' }}>
              <UnLockedSvg size=".875rem" />
              <Box
                sx={{
                  fontWeight: '400',
                  fontSize: '0.88rem',
                  lineHeight: '143%',
                  color: '#4a5565',
                }}
              >
                Доступ открыт только для:
              </Box>
            </Box>

            <Box
              sx={{
                display: 'flex',
                flexDirection: 'column',
                gap: '0.3rem',
                justifyContent: 'start',
              }}
            >
              {accessInfo.map((access, index) => (
                <Box
                  key={index}
                  sx={{
                    display: 'flex',
                    gap: '.5rem',
                    '& *': {
                      fontSize: '0.88rem !important',
                      color: '#4a5565',
                    },
                  }}
                >
                  <Box>{access.accessLevel}&nbsp;&nbsp;–</Box>
                  <Box sx={{ color: 'black' }}>{access.roleName}</Box>
                </Box>
              ))}
            </Box>
          </Box>
        </>
      )}
    </>
  );
};