// React Imports
import { useState } from 'react'

// MUI Imports
import Box from '@mui/material/Box'
import IconButton from '@mui/material/IconButton'
import Typography from '@mui/material/Typography'

// Third-party Imports
import classnames from 'classnames'

// Type Imports
import type { ChatFile } from '@/types/apps/aiChatTypes'

type Props = {
  files: ChatFile[]
  onRemove?: (index: number) => void
  className?: string
  readOnly?: boolean
}

const getFileIcon = (mimeType: string, fileName: string) => {
  const lowerName = fileName.toLowerCase()
  if (mimeType.includes('pdf') || lowerName.endsWith('.pdf')) return 'tabler-file-text'
  if (mimeType.includes('word') || mimeType.includes('document') || lowerName.endsWith('.doc') || lowerName.endsWith('.docx')) return 'tabler-file-word'
  if (mimeType.includes('excel') || mimeType.includes('spreadsheet') || lowerName.endsWith('.xls') || lowerName.endsWith('.xlsx')) return 'tabler-file-excel'
  if (mimeType.includes('powerpoint') || mimeType.includes('presentation') || lowerName.endsWith('.ppt') || lowerName.endsWith('.pptx')) return 'tabler-file-powerpoint'
  return 'tabler-file-description'
}

const formatFileSize = (bytes: number) => {
  if (bytes < 1024) return `${bytes} B`
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}

const FilePreview = ({ files, onRemove, className, readOnly = false }: Props) => {
  if (files.length === 0) {
    return null
  }

  const handleFileClick = (file: ChatFile) => {
    // Create a blob from base64 and open in new tab
    const byteCharacters = atob(file.data.split(',')[1])
    const byteNumbers = new Array(byteCharacters.length)
    for (let i = 0; i < byteCharacters.length; i++) {
      byteNumbers[i] = byteCharacters.charCodeAt(i)
    }
    const byteArray = new Uint8Array(byteNumbers)
    const blob = new Blob([byteArray], { type: file.type })
    const url = URL.createObjectURL(blob)
    window.open(url, '_blank')
  }

  return (
    <Box className={classnames('flex flex-wrap gap-2', className)}>
      {files.map((file, index) => (
        <Box
          key={index}
          className='relative flex items-center gap-2 rounded border border-divider bg-backgroundPaper p-3'
          sx={{
            minWidth: 200,
            maxWidth: 300,
            cursor: 'pointer',
            '&:hover': {
              backgroundColor: 'var(--mui-palette-action-hover)'
            }
          }}
          onClick={() => handleFileClick(file)}
        >
          <Box
            sx={{
              width: 40,
              height: 40,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              backgroundColor: 'var(--mui-palette-primary-lightOpacity)',
              borderRadius: 1,
              color: 'var(--mui-palette-primary-main)'
            }}
          >
            <i className={`${getFileIcon(file.type, file.name)} text-xl`} />
          </Box>
          <Box className='flex-1 min-is-0'>
            <Typography
              variant='body2'
              className='font-medium truncate'
              sx={{ color: 'var(--mui-palette-text-primary)' }}
              title={file.name}
            >
              {file.name}
            </Typography>
            <Typography variant='caption' sx={{ color: 'var(--mui-palette-text-secondary)' }}>
              {formatFileSize(file.size)}
            </Typography>
          </Box>
          {!readOnly && onRemove && (
            <IconButton
              size='small'
              onClick={e => {
                e.stopPropagation()
                onRemove(index)
              }}
              sx={{
                width: 24,
                height: 24,
                '&:hover': {
                  backgroundColor: 'var(--mui-palette-error-main)',
                  color: 'var(--mui-palette-error-contrastText)'
                }
              }}
            >
              <i className='tabler-x text-sm' />
            </IconButton>
          )}
        </Box>
      ))}
    </Box>
  )
}

export default FilePreview

