import React from 'react';
import {
  Box,
  Typography,
  TextField,
} from '@mui/material';
import { Controller, useFormContext } from 'react-hook-form';
import { useTranslation } from 'react-i18next';

export interface MultilineTextFormFieldProps {
  name: string;
  label: string;
  helperText?: string;
  defaultValue?: string;
  disabled?: boolean;
  required?: boolean;
  fullWidth?: boolean;
  rows?: number;
  maxRows?: number;
  minRows?: number;
  placeholder?: string;
  size?: 'small' | 'medium';
  maxLength?: number;
}

export const MultilineTextFormField: React.FC<MultilineTextFormFieldProps> = ({
  name,
  label,
  helperText,
  defaultValue = '',
  disabled = false,
  required = false,
  fullWidth = true,
  rows = 4,
  maxRows,
  minRows,
  placeholder,
  size = 'medium',
  maxLength,
}) => {
  const { control } = useFormContext();
  const { t } = useTranslation();

  return (
    <Box>
      <Typography variant="subtitle1" gutterBottom>
        {required && <span style={{ color: 'red' }}>*</span>}
        {label}
      </Typography>
      <Controller
        name={name}
        control={control}
        defaultValue={defaultValue}
        rules={{
          required: required ? t('form.fieldRequired', { field: label }) : false,
          maxLength: maxLength ? {
            value: maxLength,
            message: t('form.maxLengthExceeded', { field: label, maxLength })
          } : undefined,
        }}
        render={({ field, fieldState: { error } }) => (
          <TextField
            {...field}
            multiline
            rows={rows}
            maxRows={maxRows}
            minRows={minRows}
            fullWidth={fullWidth}
            disabled={disabled}
            placeholder={placeholder}
            size={size}
            error={!!error}
            helperText={error?.message || helperText}
            inputProps={{
              maxLength: maxLength,
            }}
          />
        )}
      />
    </Box>
  );
};