import { FC, memo, useState } from 'react';

import DownloadIcon from '@material-hu/icons/material/Download';
import { IconTrash } from '@material-hu/icons/tabler';
import Box from '@material-hu/mui/Box';
import IconButton from '@material-hu/mui/IconButton';
import List from '@material-hu/mui/List';
import ListItem from '@material-hu/mui/ListItem';
import ListItemButton from '@material-hu/mui/ListItemButton';
import ListItemIcon from '@material-hu/mui/ListItemIcon';
import ListItemText from '@material-hu/mui/ListItemText';
import Typography from '@material-hu/mui/Typography';

import HuAvatar from '@material-hu/components/design-system/Avatar';

import { FileExtensions } from 'src/constants/filesPreview';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { Attachment } from 'src/types/attachments';
import { getFileExtension, getHuGoFileIcon } from 'src/utils/files';

import PdfViewer from 'src/components/attachment/PdfViewer';
import EllipsisTooltip from 'src/components/EllipsisTooltip';

export type AttachmentsFileListProps = {
  files: Attachment[];
  onDelete?: (file: Attachment, index: number) => void;
  enableOpenFile?: boolean;
  onDownload?: (file: Attachment) => void;
  disabled?: boolean;
};

export const AttachmentsFileList: FC<AttachmentsFileListProps> = memo(
  function AttachmentsFileList(props) {
    const {
      files,
      onDelete,
      enableOpenFile = false,
      onDownload = () => null,
      disabled,
    } = props;

    const HugoThemeProvider = useHuGoTheme();
    const [openPdfPreview, setOpenPdfPreview] = useState(false);
    const [pdfFile, setPdfFile] = useState<Attachment | null>(null);

    const handleDelete = (
      event: React.MouseEvent<HTMLButtonElement>,
      file: Attachment,
      index: number,
    ) => {
      if (!onDelete) return undefined;
      onDelete(file, index);
      event.stopPropagation();
    };

    const handleDownload = (
      event: React.MouseEvent<HTMLButtonElement>,
      file: Attachment,
    ) => {
      event.preventDefault();
      event.stopPropagation();
      window.open(file.url, '_blank', 'noopener,noreferrer');
      onDownload(file);
    };

    const handleClick = (file: Attachment) => {
      if (disabled) return;
      const extension = file.name?.split('.')[1] || '';
      if (extension === FileExtensions.PDF) {
        setPdfFile(file);
        setOpenPdfPreview(true);
      } else {
        window.open(file.url, '_blank', 'noopener,noreferrer');
        onDownload(file);
      }
    };

    return (
      <HugoThemeProvider>
        <List
          sx={{
            display: 'flex',
            overflow: 'auto',
            alignItems: 'center',
            gap: 1,
            width: '100%',
            pb: 1,
          }}
        >
          {files.map((file, index) => (
            <ListItem
              key={file.url}
              disablePadding
              sx={{
                border: 1,
                borderColor: 'divider',
                borderRadius: 2,
                width: '280px',
                minWidth: '280px',
              }}
            >
              <ListItemButton
                onClick={() => handleClick(file)}
                disabled={disabled}
                sx={{
                  display: 'flex',
                  gap: 1,
                  borderRadius: '16px',
                  p: 2,
                }}
              >
                <ListItemIcon sx={{ minWidth: 0 }}>
                  <HuAvatar
                    Icon={getHuGoFileIcon(file)}
                    color="primary"
                  />
                </ListItemIcon>
                <Box sx={{ flex: 1, flexGrow: 1, minWidth: 0 }}>
                  <ListItemText
                    primary={
                      <EllipsisTooltip title={file.name || ''}>
                        <Typography
                          variant="globalS"
                          fontWeight="fontWeightSemiBold"
                          sx={{
                            width: '100%',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap',
                            display: 'block',
                          }}
                        >
                          {file.name}
                        </Typography>
                      </EllipsisTooltip>
                    }
                    secondary={
                      <Typography
                        variant="globalXS"
                        color={theme => theme.palette.new.text.neutral.lighter}
                      >
                        {file.size} • {getFileExtension(file)}
                      </Typography>
                    }
                  />
                </Box>
                {enableOpenFile && !onDelete && (
                  <IconButton
                    onClick={event => handleDownload(event, file)}
                    disabled={disabled}
                  >
                    <DownloadIcon />
                  </IconButton>
                )}
                {onDelete && (
                  <IconButton
                    onClick={event => handleDelete(event, file, index)}
                    disabled={disabled}
                  >
                    <IconTrash />
                  </IconButton>
                )}
              </ListItemButton>
            </ListItem>
          ))}
        </List>
        {openPdfPreview && pdfFile && (
          <PdfViewer
            file={pdfFile}
            onClose={() => setOpenPdfPreview(false)}
            onDownload={onDownload}
          />
        )}
      </HugoThemeProvider>
    );
  },
);

export default AttachmentsFileList;
