import { AttachmentField } from '@/components/ra-fields';
import { LabeledInput } from '@/components/ra-inputs/LabeledInput';
import { styled } from '@mui/material/styles';
import React from 'react';
import { FileInputProps, FileInput as RaFileInput, useInput, useRecordContext } from 'react-admin';

function removeDeleteIfNecessary(disabled: boolean): any {
  if (disabled) {
    return {
      '& .RaFileInput-removeButton > .RaFileInputPreview-removeButton': {
        display: 'none',
        visiblity: 'hidden'
      },
      '& .RaFileInput-dropZone': {
        display: 'none',
        visiblity: 'hidden'
      }
    };
  }
  return {};
}

const StyledFileInput = styled(RaFileInput, { slot: 'root' })(
  ({ disabled, theme }: { disabled: boolean; theme: any }) => ({
    '& .previews': {},
    '& .previews>div': {
      marginTop: theme.spacing(1),
      padding: theme.spacing(1.5),
      border: `1px solid ${theme.palette.divider}`,
      borderRadius: theme.shape.borderRadius,
      '& button': {
        float: 'right',
        placeItems: 'flex-end',
        verticalAlign: 'middle'
      },
      '&:hover': {
        backgroundColor: theme.palette.action.hover
      },
      '& .MuiLink-root': {
        fontSize: theme.typography.body1.fontSize
      }
    },
    ...removeDeleteIfNecessary(disabled)
  })
);

/**
 * Allows you to define an input field inside which you can upload one or more files.
 *
 * @example
 * <AttachmentInput source="attachments" title="name" accept="image/*" multiple>
 */
function AttachmentInput({
  // @ts-ignore
  children = <AttachmentField title="name" source="path" />,
  multiple = false,
  disabled = false,
  type = 'attachment',
  ...props
}: AttachmentInputProps): JSX.Element {
  const record = useRecordContext(props);
  const property = props?.source;
  const entityId = record?.id;
  useInput({ source: `__${type}__${props?.source}`, defaultValue: props?.source });
  return (
    /** @ts-ignore */
    <LabeledInput {...props} disabled={disabled}>
      {/** @ts-ignore */}
      <StyledFileInput type={type} multiple={multiple} disabled={disabled}>
        {/* @ts-ignore */}
        {React.cloneElement(children, { entityId, property, ...children.props })}
      </StyledFileInput>
    </LabeledInput>
  );
}

type AttachmentInputProps = FileInputProps & {
  children?: React.ReactNode;
  disabled?: boolean;
  source?: string;
  type?: 'file' | 'image' | 'attachment';
};

export { AttachmentInput };
export type { AttachmentInputProps };
