import React, { useState, useMemo } from 'react';
import { Box, Button, Typography, Stack } from '@mui/material';
import { ExpandLess } from '@mui/icons-material';
import useAbbreviation from './hooks/useAbbreviation';

const GroupDeps = ({ items, itemsPerRow, type }) => {
  const { createAbbreviation, shouldAbbreviate } = useAbbreviation();
  const [showAll, setShowAll] = useState(false);
  // Разбиваем элементы на строки по 5
  const chunkArray = (array, chunkSize) => {
    const chunks = [];
    for (let i = 0; i < array.length; i += chunkSize) {
      chunks.push(array.slice(i, i + chunkSize));
    }
    return chunks;
  };

  const visibleItems = showAll ? items : items.slice(0, itemsPerRow);
  const itemRows = chunkArray(visibleItems, itemsPerRow);
  const hasMore = items.length > visibleItems.length;

  return (
    <Stack>
      <Typography fontSize={'0.875rem'}>{type}</Typography>
      <Box
        sx={{
          display: 'flex',
          flexDirection: 'row',
          gap: '.5rem',
          alignItems: 'end',
        }}
      >
        <Box
          sx={{
            display: 'flex',
            flexDirection: 'column',
            gap: '.5rem',
            height: 'max-content',
          }}
        >
          <Box
            sx={{
              border: '1px solid #d1d5db',
              borderRadius: '0.5rem',
              padding: '0.375rem 0.5rem',
              width: 'max-content',
              maxWidth: '100%',
              display: 'flex',
              flexDirection: 'column',
              gap: '.25rem',
              boxSizing: 'border-box',
            }}
          >
            {itemRows.map((row, rowIndex) => (
              <Box
                key={rowIndex}
                sx={{
                  display: 'flex',
                  flexDirection: 'row',
                  gap: '.25rem',
                  flexWrap: 'wrap',
                }}
              >
                {row.map((item, itemIndex) => {
                  const needsAbbreviation = shouldAbbreviate(item.title);
                  const displayText = needsAbbreviation
                    ? createAbbreviation(item.title)
                    : item.title;

                  return (
                    <Box
                      key={`${rowIndex}-${itemIndex}`}
                      sx={{
                        boxSizing: 'border-box',
                        border: '1px solid #d1d5dc',
                        borderRadius: '0.38rem',
                        padding: '0.13rem 0.5rem',
                        backgroundColor: '#f3f4f6',
                        color: '#364153',
                        position: 'relative',
                        fontSize: '.75rem',
                        height: '1.4rem',
                        cursor: needsAbbreviation ? 'help' : 'default',
                        '&:hover': {
                          backgroundColor: needsAbbreviation
                            ? '#e5e7eb'
                            : '#f3f4f6',
                        },
                      }}
                      title={needsAbbreviation ? item.title : ''}
                    >
                      {displayText}
                    </Box>
                  );
                })}
              </Box>
            ))}
          </Box>

          <Box
            sx={{
              display: 'flex',
              alignItems: 'center',
              gap: '1rem',
              color: '#364153',
            }}
          ></Box>
        </Box>{' '}
        {hasMore && !showAll && (
          <Box
            sx={{
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              gap: '0.25rem',
              paddingBottom: '1rem',
              '&:hover': {
                textDecoration: 'underline',
              },
              color: '#364153',
            }}
            onClick={() => setShowAll(true)}
            title={`Показать все (всего ${items.length} подразделений)`}
          >
            ...еще {items.length - visibleItems.length}
          </Box>
        )}
        {showAll && items.length > itemsPerRow && (
          <Box
            sx={{
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              gap: '0.25rem',
              paddingBottom: '1rem',
              color: '#364153',
              '&:hover': {
                textDecoration: 'underline',
              },
            }}
            onClick={() => setShowAll(false)}
            title="Показать меньше"
          >
            <ExpandLess />
            Свернуть
          </Box>
        )}
      </Box>
    </Stack>
  );
};

export default GroupDeps;
