import * as React from 'react';
import clsx from 'clsx';

import MuiTextField from '@mui/material/TextField';
import type { OutlinedTextFieldProps as MuiTextFieldProps } from '@mui/material/TextField';

import { InputLabel } from '../input-label';
import { LabelWithHint } from '../label-with-hint';
import type { LabelWithHintProps } from '../label-with-hint';

export interface TextFieldClasses {
  /** Styles applied to the root element. */
  root: string;
  /** Styles applied to the input label. */
  inputLabel: string;
}

export interface TextFieldProps
  extends Omit<MuiTextFieldProps, 'classes' | 'hiddenLabel' | 'margin' | 'variant'> {
  /**
   * Props for the LabelWithHint component.
   */
  labelWithHintProps?: Omit<LabelWithHintProps, 'children' | 'required'>;
  /**
   * Override or extend the styles applied to the component.
   */
  classes?: Partial<TextFieldClasses>;
}

export const TextField = React.forwardRef(function (
  props: TextFieldProps,
  ref: React.Ref<HTMLDivElement>
) {
  const { label, required = false, labelWithHintProps, classes, className, ...otherProps } = props;

  const renderedTextField = (
    <MuiTextField
      ref={ref}
      hiddenLabel
      variant="outlined"
      className={clsx(classes?.root, className)}
      {...otherProps}
    />
  );

  return label ? (
    <InputLabel className={classes?.inputLabel}>
      <LabelWithHint required={required} {...labelWithHintProps}>
        {label}
      </LabelWithHint>
      {renderedTextField}
    </InputLabel>
  ) : (
    renderedTextField
  );
});
