import { FC } from 'react';
import { useNavigate } from 'react-router-dom';

import Divider from '@material-hu/mui/Divider';

import useTheme from '@material-hu/mui/styles/useTheme';

import { fileToIconV2 } from '@material-hu/components/composed-components/files/FileIcon/utils';
import HuListItem from '@material-hu/components/design-system/List/components/ListItem';

import useDocument from 'src/hooks/queryHooks/document';
import useAskForPassword from 'src/pages/dashboard/documents/hooks/useAskForPassword';
import { documentsRoutes } from 'src/pages/dashboard/documents/routes';
import { Document } from 'src/types/documents';

import Badge from 'src/components/Badge';

import SignButton from '../signDocument/SignButton';

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

export const PendingItem: FC<PendingItemProps> = props => {
  const { document, showDivider } = props;
  const navigate = useNavigate();
  const theme = useTheme();

  const handleOnSucess = () => {
    navigate(documentsRoutes.pending.files.detail(document.id));
  };
  const { askForPassword, modal: passwordModal } = useAskForPassword({
    onSuccess: handleOnSucess,
  });

  const { data = { data: { name: '', newDocuments: 0 } } } = useDocument(
    document.folderId,
    !!document?.folderId,
  );

  const handleClick = () => {
    askForPassword(() =>
      navigate(documentsRoutes.pending.files.detail(document.id)),
    );
  };

  const folder = data?.data;
  const icon = fileToIconV2(document, theme);

  return (
    <>
      <HuListItem
        avatar={icon}
        text={{ title: document?.name, description: folder.name }}
        sideContent={
          <>
            {folder?.newDocuments > 0 && <Badge count={folder?.newDocuments} />}
            <SignButton
              document={document}
              handleClick={handleClick}
            />
          </>
        }
        sx={{
          '& .MuiAvatar-root': {
            ...icon.colorsSX,
          },
          '& .MuiListItem-root': {
            py: 1.5,
            px: 0,
          },
        }}
      />
      {showDivider && <Divider />}
      {passwordModal}
    </>
  );
};

export default PendingItem;
