import React from 'react';
import { TextField, Box, Typography } from '@mui/material';
import { useFormContext, Controller } from 'react-hook-form';
import { type IFormLayoutType } from './index';

export interface TextFormFieldProps extends IFormLayoutType {
  name: string;
  label: string;
  placeholder?: string;
  defaultValue?: string;
  required?: boolean;
  disabled?: boolean;
  helperText?: string;
  type?: 'text' | 'email' | 'password' | 'url' | 'tel';
}

export function TextFormField({
  name,
  label,
  placeholder,
  defaultValue = '',
  required = false,
  disabled = false,
  layout = 'vertical',
  helperText,
  type = 'text',
}: TextFormFieldProps) {
  const { control, formState: { errors } } = useFormContext();
  const error = errors[name];
  const isHorizontal = layout === 'horizontal';

  const textField = (
    <Controller
      name={name}
      control={control}
      defaultValue={defaultValue}
      render={({ field }) => (
        <TextField
          {...field}
          type={type}
          label={isHorizontal ? undefined : label}
          placeholder={placeholder}
          required={required}
          disabled={disabled}
          error={!!error}
          helperText={error?.message as string || helperText}
          fullWidth
          variant="outlined"
        />
      )}
    />
  );

  if (isHorizontal) {
    return (
      <Box sx={{ display: 'flex', alignItems: 'center' }}>
        <Typography variant="subtitle1" sx={{ minWidth: 120, pt: 1 }}>
          {label}
          {required && <span style={{ color: 'red' }}>*</span>}
        </Typography>
        <Box sx={{ flex: 1 }}>
          {textField}
        </Box>
      </Box>
    );
  }

  return textField;
}