// resources/assets/ts/ContactsPage/components/NotizenDateiTab/notizenDateiUtils.tsx

import React from 'react';
import ArticleIcon from '@mui/icons-material/Article';
import PictureAsPdfIcon from '@mui/icons-material/PictureAsPdf';
import InsertPhotoIcon from '@mui/icons-material/InsertPhoto';
import TableViewIcon from '@mui/icons-material/TableView';
import FilePresentIcon from '@mui/icons-material/FilePresent';
import FolderIcon from '@mui/icons-material/Folder';
import StickyNote2Icon from '@mui/icons-material/StickyNote2';

const IMAGE_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg', 'ico'];
const DOCUMENT_EXTENSIONS = ['doc', 'docx', 'txt', 'odt', 'rtf'];
const SPREADSHEET_EXTENSIONS = ['xls', 'xlsx', 'csv', 'ods', 'tsv'];

/**
 * Returns the appropriate MUI icon for a given file name or type.
 * Pass type='notiz' to get the notiz (article) icon.
 */
export const getFileIcon = (fileName: string, type?: 'notiz' | 'datei'): React.ReactElement => {
  if (type === 'notiz') {
    return <StickyNote2Icon color="action" />;
  }

  const ext = fileName.split('.').pop()?.toLowerCase() ?? '';

  // Folder: no extension at all
  if (!fileName.includes('.')) {
    return <FolderIcon color="primary" />;
  }

  if (ext === 'pdf') {
    return <PictureAsPdfIcon color="action" />;
  }

  if (IMAGE_EXTENSIONS.includes(ext)) {
    return <InsertPhotoIcon color="action" />;
  }

  if (SPREADSHEET_EXTENSIONS.includes(ext)) {
    return <TableViewIcon color="action" />;
  }

  if (DOCUMENT_EXTENSIONS.includes(ext)) {
    return <ArticleIcon color="action" />;
  }

  // Fallback for all other file types
  return <FilePresentIcon color="action" />;
};

/**
 * Returns the uppercased file extension, or empty string if none found.
 */
export const getFileExtension = (fileName: string): string => {
  const parts = fileName.split('.');
  return parts.length > 1 ? parts.pop()!.toUpperCase() : '';
};

/**
 * Builds the download URL for a file, with each path segment encoded.
 */
export const getFileDownloadUrl = (contactId: number, pathOrName: string): string => {
  const encodedPath = pathOrName.split('/').map(encodeURIComponent).join('/');
  return `/crm/compfile/${contactId}/${encodedPath}`;
};
