import { BaseAttachmentField, BaseAttachmentFieldProps } from '@/components/ra-fields/BaseAttachmentField';
import { Box, Typography } from '@mui/material';
import dayjs from 'dayjs';
import { get } from 'lodash';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useDataProvider, useNotify, useRecordContext, useResourceContext, useTranslate } from 'react-admin';

function AttachmentField({
  entityId: _entityId,
  property,
  disabled,
  showUser = false,
  userResource = 'entities/user',
  resource: _resource,
  ...props
}: AttachmentFieldProps): JSX.Element {
  const [user, setUser] = useState<any>(null);
  const record = useRecordContext(props);
  const dataProvider = useDataProvider();
  const resource = useResourceContext();
  const notify = useNotify();
  const handleClick = useCallback(
    async (e: any) => {
      e.preventDefault();
      e.stopPropagation();
      notify('ra.notification.download', { type: 'info' });

      const item = get(record, props?.source);
      const entity = (_resource || resource).replace('entities/', '');
      const entityId = _entityId || record?.id;
      const attachment = await dataProvider.getFile(
        `/attachments/${entity}/${entityId}/${property || props?.source}/${item?.id || record?.id}`
      );
      const link = document.createElement('a');
      link.href = attachment;
      link.download = get(record, props?.title || props?.source);
      link.click();
    },
    [dataProvider, record, _entityId, resource, _resource, property, props?.source, props?.title, notify]
  );
  const _record = useMemo(
    () => ({
      ...record,
      [props?.source]: record?.src || get(record, props?.source),
      [props?.title]: record?.title || get(record, props?.title || props?.source)
    }),
    [record, props?.source, props?.title]
  );
  const translate = useTranslate();
  useEffect(() => {
    if (!record || !record?.userId || showUser === false) return;
    dataProvider
      .getOne(userResource, { id: record?.userId })
      .then(({ data }) => setUser(data))
      .catch(() => setUser(null));
  }, [record, dataProvider, userResource, showUser]);

  return (
    <BaseAttachmentField
      {...props}
      disabled={disabled}
      record={_record}
      onClick={handleClick}
      title={
        <Box sx={{ cursor: 'pointer' }}>
          <Typography variant="subtitle1">{get(_record, props?.title || props?.source)}</Typography>
          <Typography variant="caption" color="secondary">
            {get(_record, 'sizeDescription')}
            {showUser && user ? ` | ` : null}
            {showUser && user
              ? translate('ra.attachment.info', {
                  user: user?.name,
                  created: dayjs(_record?.createdAt).format('DD/MM/YYYY HH:mm')
                })
              : null}
          </Typography>
        </Box>
      }
    />
  );
}

type AttachmentFieldProps = BaseAttachmentFieldProps & {
  title: string;
  entityId?: string;
  property?: string;
  disabled?: boolean;
  /**
   * Allows you to define the base resource to use, for REST calls, to retrieve user data associated with the single attachment.
   * If not specified, the default value is 'entities/user'.
   */
  userResource?: string;
  /**
   * If true, the user data associated with the single attachment will be displayed.
   */
  showUser?: boolean;
  /**
   * When the AttachmentInput is used inside a nested form, you can specify the root resource to use for the REST calls.
   * If not specified, the default value is the current resource passed by context.
   */
  resource?: string;
};

export { AttachmentField };
export type { AttachmentFieldProps };
