import React from 'react';
import {
  IconFile,
  IconFileDescription,
  IconFileSpreadsheet,
  IconFileTypePdf,
  IconFileTypePpt,
  IconMovie,
  IconPhoto,
} from '@tabler/icons-react-native';
import {Typography} from '@components/_core';
import {AvatarProps} from '@components/_HuGo';
import {FILE_TYPES} from '@shared/constants';
import {shortenText} from '@shared/utils';

const NAME_LIMIT = 55;

const getComponentsBySearchTerm = (
  name: string,
  indexOfSearchTerm: number,
  searchTerm: string,
) => [
  {text: name.substring(0, indexOfSearchTerm)},
  {
    text: name.substring(
      indexOfSearchTerm,
      indexOfSearchTerm + searchTerm.length,
    ),
    bold: true,
  },
  {text: name.substring(indexOfSearchTerm + searchTerm.length)},
];

export const getItemTitle = (name: string, searchTerm?: string) => {
  const fileName = shortenText(name, NAME_LIMIT);
  const indexOfSearchTerm = searchTerm
    ? fileName.toLowerCase().indexOf(searchTerm.toLowerCase())
    : -1;
  return searchTerm && indexOfSearchTerm >= 0
    ? getComponentsBySearchTerm(fileName, indexOfSearchTerm, searchTerm).map(
        ({text, bold}, index) => (
          <Typography
            key={index}
            variant="s"
            weight={bold ? 'semiBold' : 'regular'}>
            {text}
          </Typography>
        ),
      )
    : fileName;
};

export const getFileIcon = (type: string): AvatarProps => {
  switch (type) {
    case FILE_TYPES.CSV:
    case FILE_TYPES.XLS:
    case FILE_TYPES.XLSM:
    case FILE_TYPES.XLSX:
    case FILE_TYPES.XML:
      return {Icon: IconFileSpreadsheet, variant: 'success'};
    case FILE_TYPES.PPSM:
    case FILE_TYPES.PPSX:
    case FILE_TYPES.PPT:
    case FILE_TYPES.PPTX:
      return {Icon: IconFileTypePpt, variant: 'warning'};
    case FILE_TYPES.DOC:
    case FILE_TYPES.DOCX:
      return {Icon: IconFileDescription, variant: 'primary'};
    case FILE_TYPES.GIF:
    case FILE_TYPES.JPG:
    case FILE_TYPES.JPEG:
    case FILE_TYPES.PNG:
    case FILE_TYPES.WEBP:
      return {Icon: IconPhoto, variant: 'highlight'};
    case FILE_TYPES.PDF:
      return {Icon: IconFileTypePdf, variant: 'error'};
    case FILE_TYPES.MPEG:
    case FILE_TYPES.WEBM:
    case FILE_TYPES.MOV:
    case FILE_TYPES.MP4:
    case FILE_TYPES.AVI:
    case FILE_TYPES.QUICKTIME:
    case FILE_TYPES['X-MSVIDEO']:
      return {Icon: IconMovie, variant: 'info'};
    default:
      return {Icon: IconFile, variant: 'default'};
  }
};
