import { useTranslation } from 'react-i18next';

import FileItem from '@composed-components/files/FileItem';
import Button from '@design-system/Buttons/Button';
import CardContainer from '@design-system/CardContainer';
import Title from '@design-system/Title';
import { useAddAttachmentDrawer } from '@hooks/useAddAttachmentDrawer';
import { useEditAttachmentDrawer } from '@hooks/useEditAttachmentDrawer';
import { useSortAttachmentsDrawer } from '@hooks/useSortAttachmentsDrawer';
import Stack from '@mui/material/Stack';
import { type SortableAttachment } from '@src/types/attachments';
import { IconPlus } from '@tabler/icons-react';
import { sortPositioned } from '@utils/array';
import { downloadFile, downloadUrl } from '@utils/files';

import { type AttachmentsProps } from './types';

const Attachments = ({
  attachments,
  editing = false,
  onDownload = () => null,
  onEdit = () => null,
  onDelete = () => null,
  onAdd = () => null,
  onSort = () => null,
  upload = undefined,
  editRules,
  emptyDescription,
}: AttachmentsProps) => {
  const { t } = useTranslation();

  const { editAttachmentDrawer, showEditAttachmentDrawer } =
    useEditAttachmentDrawer(editRules);

  const { addAttachmentDrawer, showAddAttachmentDrawer } =
    useAddAttachmentDrawer(upload);

  const { sortAttachmentsDrawer, showSortAttachmentsDrawer } =
    useSortAttachmentsDrawer();

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

  const description = showEmpty ? emptyDescription : 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:edit'),
        onClick: () => handleEdit(attachment, index),
      },
      {
        title: t('general:delete'),
        onClick: () => handleDelete(attachment, index),
      },
    ];

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

  if (isEmpty && !showEmpty) return null;

  const sortedAttachments = sortPositioned(attachments) ?? [];

  return (
    <>
      {editAttachmentDrawer}
      {addAttachmentDrawer}
      {sortAttachmentsDrawer}
      <CardContainer
        sx={{
          width: '100%',
          '& > .MuiCardContent-root': {
            display: 'flex',
            flexDirection: 'column',
            gap: 1,
          },
        }}
      >
        <Stack
          sx={{
            flexDirection: 'row',
            justifyContent: 'space-between',
            gap: 1,
          }}
        >
          <Title
            variant="S"
            fontWeight="fontWeightSemiBold"
            title={t('general:attachments')}
            description={description}
          />
          {editing && (
            <Stack
              sx={{
                flexDirection: 'row',
                alignSelf: 'center',
                alignItems: 'center',
                justifyContent: 'center',
                gap: 2,
              }}
            >
              {attachments && attachments.length > 1 && (
                <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>
        {sortedAttachments.map((attachment, index) => (
          <FileItem
            key={attachment.id}
            file={attachment}
            actions={getActions(attachment, index)}
            sx={{ width: '100%' }}
          />
        ))}
      </CardContainer>
    </>
  );
};

export default Attachments;
