import { type SxProps, styled, type Theme } from '@material-hu/mui/styles';

import {
  CERTIFICATE_MULTILINE_FONT_SIZE,
  CERTIFICATE_MULTILINE_LINE_HEIGHT,
  CERTIFICATE_MULTILINE_PAD_X as PAD_X,
  CERTIFICATE_MULTILINE_PAD_Y as PAD_Y,
} from 'src/pages/dashboard/Learning/Settings/Certificates/Create/constants';

import { TOKEN_ATTR } from './utils';

const LINE_HEIGHT_PX = 16 * CERTIFICATE_MULTILINE_LINE_HEIGHT;

export const getContainerSx = (
  theme: Theme,
  borderColor: string,
  disabled: boolean,
): SxProps<Theme> => ({
  position: 'relative',
  borderRadius: 1,
  border: '1px solid',
  borderColor,
  bgcolor: disabled
    ? theme.palette.new.background.elements.disabled
    : theme.palette.new.background.elements.default,
  transition: 'border-color 0.2s ease',
});

type EditableAreaOwnerState = {
  disabled: boolean;
  showClear: boolean;
  minRows: number;
  maxRows?: number;
};

export const EditableArea = styled('div', {
  shouldForwardProp: prop => prop !== 'ownerState',
})<{ ownerState: EditableAreaOwnerState }>(({ theme, ownerState }) => ({
  outline: 'none',
  boxSizing: 'border-box',
  paddingLeft: PAD_X,
  paddingRight: ownerState.showClear ? 40 : PAD_X,
  paddingTop: PAD_Y,
  paddingBottom: PAD_Y,
  minHeight: ownerState.minRows * LINE_HEIGHT_PX + 2 * PAD_Y,
  maxHeight: ownerState.maxRows
    ? ownerState.maxRows * LINE_HEIGHT_PX + 2 * PAD_Y
    : undefined,
  overflowY: 'auto',
  whiteSpace: 'pre-wrap',
  wordBreak: 'break-word',
  fontSize: CERTIFICATE_MULTILINE_FONT_SIZE,
  fontFamily: theme.typography.fontFamily,
  lineHeight: CERTIFICATE_MULTILINE_LINE_HEIGHT,
  color: ownerState.disabled
    ? theme.palette.new.action.button.text.disabled.darker
    : theme.palette.new.text.neutral.default,
  cursor: ownerState.disabled ? 'not-allowed' : 'text',
  [`& [${TOKEN_ATTR}]`]: {
    display: 'inline-flex',
    alignItems: 'center',
    verticalAlign: 'middle',
    backgroundColor: theme.palette.new.background.elements.brand,
    color: theme.palette.new.text.neutral.brand,
    border: `1px solid ${theme.palette.new.border.neutral.brand}`,
    borderRadius: 6,
    padding: '1px 6px',
    margin: '3px 1px',
    fontSize: '0.85em',
    fontWeight: 600,
    whiteSpace: 'nowrap',
    userSelect: 'all',
  },
}));

export const Placeholder = styled('div')(({ theme }) => ({
  position: 'absolute',
  top: PAD_Y,
  left: PAD_X,
  right: PAD_X,
  pointerEvents: 'none',
  color: theme.palette.new.text.neutral.lighter,
  fontSize: CERTIFICATE_MULTILINE_FONT_SIZE,
  fontFamily: theme.typography.fontFamily,
  lineHeight: CERTIFICATE_MULTILINE_LINE_HEIGHT,
}));
