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

import ArrowBackIcon from '@material-hu/icons/material/ArrowBack';
import DownloadIcon from '@material-hu/icons/material/Download';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';
import { type FileAsset } from '@material-hu/types/attachments';

import fileIcon from 'src/assets/images/fileIcon.webp';
import useAskForPassword from 'src/pages/dashboard/documents/hooks/useAskForPassword';
import { documentsSkeletonRoutes } from 'src/pages/dashboard/documents/routes';
import { type Attachment } from 'src/types/attachments';
import { type File } from 'src/types/files';
import { downloadUrl, getFileIcon } from 'src/utils/files';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { ToolButton } from 'src/components/attachment/preview';

export type HeaderFile = Partial<Attachment> & Partial<File>;

export type HeaderProps = {
  file: HeaderFile;
  fileSource: string;
  isPost?: boolean;
  downloadFile?: boolean;
  onClose: () => void;
  onDownload?: (file: HeaderFile) => void;
  allowDownload?: boolean;
};
const PATH = documentsSkeletonRoutes.documents();

export const Header: FC<HeaderProps> = props => {
  const {
    file,
    fileSource,
    onClose,
    isPost = false,
    downloadFile = false,
    onDownload = () => null,
    allowDownload = true,
  } = props;

  const handleOnSucess = () => {
    onDownload(file);
    window.open(fileSource, '_blank', 'noopener,noreferrer');
  };

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

  const { t } = useLokaliseTranslation('files');
  const location = useLocation();

  const isDocumentPath = !!matchPath(
    {
      path: PATH,
      end: false,
    },
    location.pathname,
  );

  const { name, type } = file;

  const handleClickWithAskForPassword = (
    event: React.MouseEvent<HTMLAnchorElement>,
  ) => {
    if (isDocumentPath) {
      askForPassword(() => handleClick(event));
      return;
    }
    handleClick(event);
  };

  const handleClick = (event: React.MouseEvent<HTMLAnchorElement>) => {
    event.preventDefault();
    event.stopPropagation();

    onDownload(file);

    if (isPost || downloadFile) {
      downloadUrl(fileSource, file.name || 'image');
    } else {
      window.open(fileSource, '_blank', 'noopener,noreferrer');
    }
  };

  return (
    <>
      <Stack
        sx={{
          flexDirection: 'row',
          width: '100%',
          height: '50px',
          position: 'fixed',
          top: 0,
          left: '12px',
          background:
            'linear-gradient(to bottom,rgba(0,0,0,.65) 0%,transparent 100%)',
          justifyContent: 'space-between',
          zIndex: 1,
        }}
      >
        <Stack sx={{ flexDirection: 'row', alignItems: 'center' }}>
          <ToolButton
            title={t('close')}
            ToolIcon={ArrowBackIcon}
            onClick={onClose}
          />
          {!isPost && (
            <Stack sx={{ flexDirection: 'row', alignItems: 'center', ml: 3 }}>
              <img
                src={
                  type === 'FOLDER'
                    ? fileIcon
                    : getFileIcon(file as Attachment | FileAsset, true)
                }
                alt=""
                width="20"
              />
              <Typography sx={{ color: '#ffffff', ml: 1, fontWeight: 500 }}>
                {name}
              </Typography>
            </Stack>
          )}
        </Stack>
        {allowDownload && (
          <Stack sx={{ flexDirection: 'row', rigth: '24px', px: 2, py: 1 }}>
            <ToolButton
              title={t('download')}
              ToolIcon={DownloadIcon}
              onClick={handleClickWithAskForPassword}
            />
          </Stack>
        )}
      </Stack>
      {passwordModal}
    </>
  );
};

export default Header;
