import { useRef } from 'react';

import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import { type CertificateAdditionalFieldType } from 'src/pages/dashboard/Learning/Settings/Certificates/Create/constants';

import CertificateFieldVariablesMenu from './CertificateFieldVariablesMenu';
import CertificateMultilineWithTokenHighlight, {
  type CertificateMultilineHandle,
} from './CertificateMultilineWithTokenHighlight';

type CertificateVariableFieldInputProps = {
  label: string;
  id: string;
  name: string;
  placeholder: string;
  maxLength: number;
  minRows?: number;
  maxRows?: number;
  isOptionDisabled?: (type: CertificateAdditionalFieldType) => boolean;
};

const CertificateVariableFieldInput = ({
  label,
  id,
  name,
  placeholder,
  maxLength,
  minRows = 4,
  maxRows,
  isOptionDisabled,
}: CertificateVariableFieldInputProps) => {
  const inputRef = useRef<CertificateMultilineHandle | null>(null);

  return (
    <Stack sx={{ gap: 0.5, width: '100%' }}>
      <Stack
        sx={{
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
          gap: 1,
          flexWrap: { xs: 'wrap', sm: 'nowrap' },
          mb: 0.5,
        }}
      >
        <Typography
          component="label"
          variant="globalS"
          htmlFor={id}
          sx={{ fontWeight: 'fontWeightSemiBold', minWidth: 0, flex: 1 }}
        >
          {label}
        </Typography>
        <CertificateFieldVariablesMenu
          onInsert={token => inputRef.current?.insertToken(token)}
          isOptionDisabled={isOptionDisabled}
        />
      </Stack>
      <CertificateMultilineWithTokenHighlight
        ref={inputRef}
        name={name}
        id={id}
        placeholder={placeholder}
        maxLength={maxLength}
        minRows={minRows}
        maxRows={maxRows}
        hasCounter
      />
    </Stack>
  );
};

export default CertificateVariableFieldInput;
