import { IconPlus } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';

import HuFileItem from '@material-hu/components/composed-components/files/FileItem';
import Button from '@material-hu/components/design-system/Buttons/Button';
import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuTitle from '@material-hu/components/design-system/Title';

import {
  SortableAttachment,
  UpdateAttachmentData,
} from 'src/types/attachments';
import { downloadFile, downloadUrl } from 'src/utils/files';
import { useLokaliseTranslation } from 'src/utils/i18n';

import useAddAttachmentDrawer from '../hooks/useAddAttachmentDrawer';
import useEditAttachmentDrawer from '../hooks/useEditAttachmentDrawer';
import useSortAttachmentsDrawer from '../hooks/useSortAttachmentsDrawer';

export type AttachmentsProps = {
  attachments: SortableAttachment[];
  editing?: boolean;
  onDownload?: (attachment: SortableAttachment, index: number) => void;
  onEdit?: (
    attachment: SortableAttachment,
    index: number,
    values: UpdateAttachmentData,
  ) => void;
  onDelete?: (attachment: SortableAttachment, index: number) => void;
  onAdd?: (attachments: SortableAttachment[]) => void;
  onSort?: (attachments: SortableAttachment[]) => void;
};

const Attachments = ({
  attachments,
  editing = false,
  onDownload = () => null,
  onEdit = () => null,
  onDelete = () => null,
  onAdd = () => null,
  onSort = () => null,
}: AttachmentsProps) => {
  const { t } = useLokaliseTranslation('libraries');

  const { editAttachmentDrawer, showEditAttachmentDrawer } =
    useEditAttachmentDrawer();

  const { addAttachmentDrawer, showAddAttachmentDrawer } =
    useAddAttachmentDrawer();

  const { sortAttachmentsDrawer, showSortAttachmentsDrawer } =
    useSortAttachmentsDrawer();

  const isEmpty = !attachments?.length;
  const showEmpty = isEmpty && editing;

  const description = showEmpty
    ? t('library.attachment.upload.description')
    : undefined;

  const handleDownload = (attachment: SortableAttachment, index: number) => {
    const name = attachment.name || 'download';

    if (attachment.file) {
      downloadFile(attachment.file, name);
    } else {
      if (!attachment.url) return;
      downloadUrl(attachment.url, name);
    }

    onDownload(attachment, index);
  };

  const handleEdit = (attachment: SortableAttachment, index: number) => {
    showEditAttachmentDrawer({
      attachment,
      onConfirm: (_, values) => onEdit(attachment, index, values),
    });
  };

  const handleDelete = (attachment: SortableAttachment, index: number) => {
    onDelete(attachment, index);
  };

  const handleAdd = () => {
    showAddAttachmentDrawer({
      onConfirm: onAdd,
    });
  };

  const handleSort = () => {
    showSortAttachmentsDrawer({
      attachments,
      onConfirm: onSort,
    });
  };

  const getActions = (attachment: SortableAttachment, index: number) => {
    const baseActions = [
      {
        title: t('general:download'),
        onClick: () => handleDownload(attachment, index),
      },
    ];

    const editingActions = [
      {
        title: t('general:rename'),
        onClick: () => handleEdit(attachment, index),
      },
      {
        title: t('general:delete'),
        onClick: () => handleDelete(attachment, index),
      },
    ];

    return [...baseActions, ...(editing ? editingActions : [])];
  };

  if (isEmpty && !showEmpty) return null;

  return (
    <>
      {editAttachmentDrawer}
      {addAttachmentDrawer}
      {sortAttachmentsDrawer}
      <HuCardContainer
        sx={{
          width: '100%',
          '& > .MuiCardContent-root': {
            display: 'flex',
            flexDirection: 'column',
            gap: 1,
          },
        }}
      >
        <Stack
          sx={{
            flexDirection: 'row',
            justifyContent: 'space-between',
            gap: 1,
          }}
        >
          <HuTitle
            variant="M"
            fontWeight="fontWeightSemiBold"
            title={t('general:attachments')}
            description={description}
          />
          {editing && (
            <Stack
              sx={{
                flexDirection: 'row',
                alignSelf: 'center',
                alignItems: 'center',
                justifyContent: 'center',
                gap: 2,
              }}
            >
              {attachments && attachments.length > 0 && (
                <Button
                  variant="secondary"
                  onClick={handleSort}
                >
                  {t('general:reorder')}
                </Button>
              )}
              <Button
                variant="primary"
                onClick={handleAdd}
                startIcon={<IconPlus />}
                sx={{ textWrap: 'nowrap' }}
              >
                {t('general:attachment.add.title_other')}
              </Button>
            </Stack>
          )}
        </Stack>
        {attachments?.map((attachment, index) => (
          <HuFileItem
            key={attachment.id}
            file={attachment}
            actions={getActions(attachment, index)}
            sx={{
              width: '100%',
            }}
          />
        ))}
      </HuCardContainer>
    </>
  );
};

export default Attachments;
