import React, { useState } from 'react';
import { useModal } from '@refinedev/antd';
import { Button, ButtonProps, ModalProps, message } from 'antd';
import * as Icons from '@ant-design/icons';
import {
  useRouterContext,
  useTranslate,
  ResourceRouterParams,
  BaseKey,
  useLogList,
  ILog,
  ILogData,
  useResource,
} from '@refinedev/core';
import { ReactDiffViewerProps } from 'react-diff-viewer';
import { ModalDiffViewer } from '../modalDiffViewer';

export type LogButtonProps = ButtonProps & {
  recordItemId?: BaseKey;
  resourceName?: string;
  hideText?: boolean;
  reactDiffViewerProps?: ReactDiffViewerProps;
  modalProps?: ModalProps;
};

export const LogButton: React.FC<LogButtonProps> = ({
  resourceName: propResourceName,
  recordItemId,
  hideText = false,
  onClick,
  reactDiffViewerProps,
  modalProps: propModalProps,
  children,
  ...rest
}) => {
  const [selectedLog, setSelectedLog] = useState<ILog>();

  const translate = useTranslate();
  const { modalProps, show } = useModal();
  const [messageApi, contextHolder] = message.useMessage();

  const { useParams } = useRouterContext();
  const { id: idFromRoute } = useParams<ResourceRouterParams>();

  const resourceWithRoute = useResource();

  const resourceName =
    propResourceName ?? resourceWithRoute?.resource?.name ?? '';
  const id = recordItemId ?? idFromRoute;

  const logQueryResult = useLogList<ILogData>({
    resource: resourceName,
    meta: { id },
    queryOptions: {
      enabled: modalProps.open,
      onSuccess: (result) => {
        if (result?.length) {
          setSelectedLog(result[0]);
        } else {
          messageApi.open({
            type: 'warning',
            content: 'There is no history.',
          });
        }
      },
    },
  });

  return (
    <>
      <Button
        onClick={(e): void =>
          onClick
            ? onClick(e as React.MouseEvent<HTMLButtonElement, MouseEvent>)
            : show()
        }
        icon={<Icons.HistoryOutlined />}
        {...rest}
      >
        {!hideText && (children ?? translate('buttons.logs', 'History'))}
      </Button>
      {selectedLog ? (
        <ModalDiffViewer
          modalProps={{ ...modalProps, ...propModalProps }}
          showModal={show}
          selectedLog={selectedLog}
          setSelectedLog={setSelectedLog}
          logQueryResult={logQueryResult}
          reactDiffViewerProps={reactDiffViewerProps}
        />
      ) : (
        <>{contextHolder}</>
      )}
    </>
  );
};
