import { useModal } from '@material-hu/hooks/useModal';
import Stack from '@material-hu/mui/Stack';
import { type FileAsset } from '@material-hu/types/attachments';

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

import { bytesToSize } from 'src/utils/filesUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import {
  MAX_FILE_SIZE_BYTES,
  MAX_FILE_SIZE_MB,
  MAX_FILES,
} from '../../../constants';
import {
  addApplicationFiles,
  deleteApplicationFile,
  uploadApplicationFile,
} from '../../../services';
import { type FileCardTypeWithId } from '../../../types';
import { useApplicationFiles } from '../hooks/useApplicationFiles';

import { DeleteFileModal } from './DeleteFileModal';

type AdditionalDocumentationProps = {
  files: FileAsset[];
  jobId: number;
  applicationId: number;
  scrollableRef?: React.RefObject<HTMLDivElement>;
};

export const AdditionalDocumentation = ({
  files,
  jobId,
  applicationId,
  scrollableRef,
}: AdditionalDocumentationProps) => {
  const { t } = useLokaliseTranslation(['ats', 'material_hu_only']);

  const {
    uploadedFiles,
    setUploadedFiles,
    onUpload,
    handleDropRejected,
    deleteFile,
    addFilesToBackend,
    isLoadingDeleteFile,
  } = useApplicationFiles({
    onUploadFileService: uploadApplicationFile,
    onDeleteFileService: (fileId: number) =>
      deleteApplicationFile({ jobId, applicationId, fileId }),
    onUploadFilesService: (fileIds: number[]) =>
      addApplicationFiles({ jobId, applicationId, fileIds }),
    applicationId,
    jobId,
    files,
    onDeleteSuccess: () => {
      handleCloseModal();
    },
  });

  const {
    modal: deleteFileModal,
    showModal: showDeleteFileModal,
    closeModal: closeDeleteFileModal,
  } = useModal<{ fileId: number }>(props => (
    <DeleteFileModal
      {...props}
      isLoading={isLoadingDeleteFile}
      onConfirm={({ fileId }) => {
        if (!fileId) return;
        deleteFile(fileId);
      }}
      onClose={handleCloseModal}
    />
  ));

  const handleCloseModal = () => {
    closeDeleteFileModal();
  };

  return (
    <>
      {deleteFileModal}
      <Stack
        sx={{
          backgroundColor: theme => theme.palette.new.background.elements.grey,
          borderRadius: theme => theme.shape.borderRadiusL,
          p: 2,
        }}
      >
        <Uploader
          {...{
            uploadFunction: onUpload,
            triggerOnChangeWhenUploading: true,
            maxFiles: MAX_FILES,
            label: t(
              'job_application.tabs.application.additional_documentation',
            ),
            acceptedTypes: [
              'pdf',
              'image',
              'msword',
              'compressed',
              'video',
              'xml',
            ],
            fileSizeLimit: MAX_FILE_SIZE_BYTES,
            description: t('common.files_allowed.all', {
              size: MAX_FILE_SIZE_MB,
            }),
            text: {
              title: t('material_hu_only:uploader.title'),
              description: t(
                'material_hu_only:uploader.allowed_with_max_files_and_formats_size_limit',
                {
                  count: MAX_FILES,
                  fileSizeLimit: bytesToSize(MAX_FILE_SIZE_BYTES),
                },
              ),
              uploadFile: t('general:upload_file'),
              maxFilesError: t('material_hu_only:uploader.max_files_error', {
                maxFiles: MAX_FILES,
              }),
              someFileNotUploaded: t(
                'material_hu_only:uploader.some_file_not_uploaded',
              ),
              fileNotUploaded: t('material_hu_only:uploader.file_not_uploaded'),
            },
            sx: {
              '& .MuiStack-root[role="presentation"]': {
                backgroundColor: theme =>
                  theme.palette.new.background.layout.tertiary,
              },
            },
            value: uploadedFiles,
            showUploadButtonOnMaxFiles: false,
            onDropRejected: handleDropRejected,
            fileCardProps: {
              onRemove: (file: FileCardTypeWithId) => {
                if (!file.id) return;
                showDeleteFileModal({ fileId: file.id });
              },
            },
            slotProps: {
              fileCard: {
                showDownloadButton: true,
                showRemoveUploadingButton: true,
              },
            },
            onChange: (newFiles: FileCardTypeWithId[]) => {
              if (newFiles.length < uploadedFiles.length) {
                // Removal — onRemove handles this via the confirmation modal
                return;
              }
              setUploadedFiles(newFiles);
              const stillUploading = newFiles.some(
                f => f.status === 'uploading',
              );
              if (!stillUploading) {
                addFilesToBackend(
                  newFiles
                    .map(file => file.id)
                    .filter(id => id !== undefined) as number[],
                );
                if (newFiles.length > 0 && scrollableRef?.current) {
                  scrollableRef.current.scrollTo({
                    top: scrollableRef.current.scrollHeight,
                    behavior: 'smooth',
                  });
                }
              }
            },
          }}
        />
      </Stack>
    </>
  );
};
