import * as React from 'react';
import { Box, Typography } from '@mui/material';
import { FieldComponentProps } from '../../types/overrides';

export interface ObjectFieldProps extends FieldComponentProps {
  renderField: (props: FieldComponentProps) => React.ReactNode;
}

export default function ObjectField({ name, field, value, onChange, disabled, baseUrl, uploadFile, uploading, relationDataMap, renderField }: ObjectFieldProps) {
  if (!field.schema) return null;

  return (
    <Box sx={{ ml: 2, mt: 2, p: 2, borderLeft: '2px solid #e0e0e0' }}>
      <Typography variant="subtitle2" color="primary" gutterBottom>
        {field.label}
      </Typography>
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
        {Object.entries(field.schema).map(([subKey, subField]) =>
          React.cloneElement(
            renderField({
              name: `${name}.${subKey}`,
              field: subField,
              value: value?.[subKey],
              onChange: (newVal: any) => {
                const updated = { ...(value || {}), [subKey]: newVal };
                onChange(updated);
              },
              disabled,
              baseUrl,
              uploadFile,
              uploading,
              relationDataMap,
            }) as React.ReactElement,
            { key: subKey }
          )
        )}


      </Box>
    </Box>
  );
}
