import { type FC } from 'react';
import { useNavigate, useLocation, useParams } from 'react-router-dom';

import isNil from 'lodash-es/isNil';

import {
  IconDownload,
  IconFileTypePdf,
  IconFile,
  IconPhoto,
} from '@material-hu/icons/tabler';
import Divider from '@material-hu/mui/Divider';

import Button from '@material-hu/components/design-system/Buttons/Button';
import HuListItem from '@material-hu/components/design-system/List/components/ListItem';
import { type ListItemAvatarProps } from '@material-hu/components/design-system/List/components/ListItem/types';

import { logEvent } from 'src/config/logging';
import { useAuth } from 'src/contexts/JWTContext';
import SignDescription from 'src/pages/dashboard/documents/components/folder/SignDescription';
import useAskForPassword from 'src/pages/dashboard/documents/hooks/useAskForPassword';
import { documentsRoutes } from 'src/pages/dashboard/documents/routes';
import { EventName } from 'src/types/amplitude';
import { type Document, SignatureStatus } from 'src/types/documents';
import { type MeUser } from 'src/types/user';
import {
  getBlobCloudfrontDocument,
  getDateInSignDescription,
  isSecureFile,
} from 'src/utils/documents';
import { downloadBlob } from 'src/utils/files';
import { FileExtensions } from 'src/constants/filesPreview';
import { type LokaliseTFunction, useLokaliseTranslation } from 'src/utils/i18n';

import SignButton from '../signDocument/SignButton';
import { IMG_DOCUMENT_EXTENSIONS } from '../../constants';

export type DocumentItemProps = {
  document: Document;
  showDivider: boolean;
};

type DescriptionSignDocumentProps = {
  t: LokaliseTFunction;
  signatureDate: string | null;
  user: MeUser;
};

const descriptionSignDocument = {
  [SignatureStatus.SIGNED]: ({
    t,
    signatureDate,
    user,
  }: DescriptionSignDocumentProps) => (
    <SignDescription
      label={t(`DOCUMENT_STATUS_${SignatureStatus.SIGNED}`)}
      date={getDateInSignDescription(signatureDate, user, t) ?? undefined}
    />
  ),
  [SignatureStatus.SIGNED_IN_DISAGREEMENT]: ({
    t,
    signatureDate,
    user,
  }: DescriptionSignDocumentProps) => (
    <SignDescription
      label={t(`DOCUMENT_STATUS_${SignatureStatus.SIGNED_IN_DISAGREEMENT}`)}
      date={getDateInSignDescription(signatureDate, user, t) ?? undefined}
    />
  ),
  [SignatureStatus.SIGNED_IN_AGREEMENT]: ({
    t,
    signatureDate,
    user,
  }: DescriptionSignDocumentProps) => (
    <SignDescription
      label={t(`DOCUMENT_STATUS_${SignatureStatus.SIGNED_IN_AGREEMENT}`)}
      date={getDateInSignDescription(signatureDate, user, t) ?? undefined}
    />
  ),
};

const getFileAvatar = (extension: string): ListItemAvatarProps => {
  const fileType = extension.toLowerCase();
  if (fileType === FileExtensions.PDF)
    return { Icon: IconFileTypePdf, color: 'error' };
  if (IMG_DOCUMENT_EXTENSIONS.includes(fileType))
    return { Icon: IconPhoto, color: 'highlight' };
  return { Icon: IconFile, color: 'primary' };
};

export const DocumentItem: FC<DocumentItemProps> = props => {
  const { document, showDivider } = props;

  const { folderId } = useParams();
  const location = useLocation();
  const navigate = useNavigate();
  const { t } = useLokaliseTranslation('documents');
  const { user } = useAuth();

  const isPendingSignature =
    document.signatureStatus === SignatureStatus.PENDING;

  const goToFile = () => {
    navigate(documentsRoutes.folders.files.detail(folderId || '', document.id));
  };
  const handleItemClick = () => askForPassword(goToFile);

  const handleClick = async () => {
    logEvent(EventName.DOCUMENT_VIEW, {
      folderId: document.folderId,
      fileId: document.id,
    });

    if (isPendingSignature) {
      navigate(documentsRoutes.pending.files.detail(document.id), {
        state: { prevPath: location.pathname },
      });
    } else if (isSecureFile(document.source)) {
      const blobPromise = await getBlobCloudfrontDocument(document.source);
      blobPromise && downloadBlob(blobPromise, document.name);
    } else {
      window.open(document.source, '_blank', 'noreferrer');
    }
  };

  const handleOnSucess = () => {
    handleClick();
  };

  const { askForPassword, modal: passwordModal } = useAskForPassword({
    onSuccess: handleOnSucess,
  });

  const handleOnClickToAskPassword = () => askForPassword(() => handleClick());

  const addSecondaryText = () => {
    if (isNil(user) || isNil(document.signatureStatus)) return undefined;
    return descriptionSignDocument[
      document.signatureStatus as keyof typeof descriptionSignDocument
    ]?.({
      t,
      signatureDate: document.signatureDate,
      user,
    });
  };

  const handleSign = (e: React.MouseEvent<HTMLButtonElement>) => {
    e.stopPropagation();
    handleOnClickToAskPassword();
  };

  return (
    <>
      <HuListItem
        onClick={isPendingSignature ? undefined : handleItemClick}
        sx={{
          '> .MuiButtonBase-root:hover': { backgroundColor: 'transparent' },
          '> .MuiButtonBase-root .MuiTouchRipple-root': { display: 'none' },
        }}
        avatar={getFileAvatar(document.extension)}
        text={{ title: document.name, description: addSecondaryText() }}
        sideContent={
          <>
            {isPendingSignature && (
              <SignButton
                document={document}
                handleClick={handleSign}
              />
            )}
            {!isPendingSignature && (
              <Button
                variant="secondary"
                onClick={handleSign}
                startIcon={<IconDownload />}
              >
                {t('DOWNLOAD')}
              </Button>
            )}
          </>
        }
      />
      {showDivider && <Divider />}
      {passwordModal}
    </>
  );
};

export default DocumentItem;
