import { TextField } from '@mui/material';
import { get } from 'lodash';
import React, { useCallback, useEffect, useState } from 'react';
import { useDataProvider, useRecordContext, useResourceContext } from 'react-admin';

type RecordInputProps = {
  source: string;
  minWidth?: number;
  children?: React.ReactElement;
};

function RecordInput({ source, minWidth = 300, children }: RecordInputProps): JSX.Element {
  const resource = useResourceContext();
  const record = useRecordContext();
  const [value, setValue] = useState(get(record, source, ''));
  const [updating, setUpdating] = useState(false);
  const handleChange = useCallback((evt: any) => setValue(evt.target.value), []);
  const dataProvider = useDataProvider();

  const handleKeyPress = useCallback(
    (evt: any) => {
      if (evt.key !== 'Enter') {
        return;
      }
      setUpdating(true);
      dataProvider
        .update(resource, {
          id: record.id,
          data: {
            ...record,
            [source]: value,
            _changed: source
          },
          previousData: record
        })
        .then(() => setUpdating(false));
    },
    [value, dataProvider, resource, record, source]
  );
  const handleBlur = useCallback(() => {
    const currentValue = get(record, source);
    if (currentValue === value) {
      return;
    }
    setUpdating(true);
    dataProvider
      .update(resource, {
        id: record.id,
        data: {
          ...record,
          [source]: value,
          _changed: source
        },
        previousData: record
      })
      .then(() => setUpdating(false));
  }, [value, dataProvider, resource, source, record]);

  const handleRemoteChange = useCallback(
    (value: any) => {
      setUpdating(true);
      dataProvider
        .update(resource, {
          id: record.id,
          data: {
            ...record,
            [source]: value,
            _changed: source
          },
          previousData: record
        })
        .then(() => setUpdating(false));
    },
    [dataProvider, resource, source, record]
  );

  useEffect(() => setValue(get(record, source)), [record, source]);

  if (children) {
    return React.cloneElement(children, {
      ...children.props,
      source,
      value,
      onChange: handleRemoteChange
    });
  }

  return (
    <TextField
      value={value}
      disabled={updating}
      onChange={handleChange}
      onKeyPress={handleKeyPress}
      onBlur={handleBlur}
      style={{ minWidth, width: '100%' }}
      multiline
      // @ts-ignore
      InputProps={{ 'arial-label': 'naked' }}
      size="small"
    />
  );
}

export { RecordInput };
export type { RecordInputProps };
