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

const DepartmentCell = ({ values, user, onEdit }) => {
  const items = useMemo(
    () => (Array.isArray(values) ? values : []),
    [values],
  );
  const itemsPerRow = 5;

  const handleEditClick = () => {
    if (onEdit) {
      onEdit(user);
    }
  };

  // Разделяем подразделения на SSP и не SSP
  const { sspItems, rfItems } = useMemo(() => {
    const ssp = items.filter((item) => item.is_ssp === true);
    const nonSsp = items.filter((item) => item.is_ssp === false);
    return { sspItems: ssp, rfItems: nonSsp };
  }, [items]);

  return (
    <>
      {items.length === 0 ? (
        <Button
          variant="outlined"
          size="small"
          onClick={handleEditClick}
          sx={{
            color: '#2d3748',
            border: '1px solid #d1d5dc',
            borderRadius: '0.5rem',
            padding: '0.5rem 0',
            width: '5.63rem',
            maxWidth: '5.63rem',
          }}
        >
          <span
            style={{
              padding: '0',
              color: ' #4a5565',
              fontSize: '0.88rem',
            }}
          >
            Выбрать
          </span>
        </Button>
      ) : (
        <>
          <Stack spacing={'.5rem'}>
            {rfItems.length > 0 && (
              <GroupDeps
                itemsPerRow={itemsPerRow}
                items={rfItems}
                type={'РФ'}
              />
            )}
            {sspItems.length > 0 && (
              <GroupDeps
                itemsPerRow={itemsPerRow}
                items={sspItems}
                type={'ССП'}
              />
            )}
          </Stack>
        </>
      )}
    </>
  );
};

export default DepartmentCell;
