"use client"

import { Download, FileText, Archive, Image as ImageIcon } from 'lucide-react'
import { Button } from '@/components/ui/button'

interface FileMessageProps {
  fileUrl: string
  fileName: string
  fileSize?: number
  fileType?: string
  isCurrentUser?: boolean
}

export function FileMessage({ fileUrl, fileName, fileSize, fileType, isCurrentUser = false }: FileMessageProps) {
  
  const formatFileSize = (bytes?: number) => {
    if (!bytes) return ''
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
  }

  const getFileIcon = (type?: string) => {
    if (!type) return <FileText className="h-6 w-6" />
    
    if (type.includes('pdf')) return <FileText className="h-6 w-6 text-red-400" />
    if (type.includes('zip') || type.includes('archive')) return <Archive className="h-6 w-6 text-yellow-400" />
    if (type.includes('image')) return <ImageIcon className="h-6 w-6 text-green-400" />
    if (type.includes('word') || type.includes('document')) return <FileText className="h-6 w-6 text-blue-400" />
    if (type.includes('excel') || type.includes('spreadsheet')) return <FileText className="h-6 w-6 text-green-600" />
    if (type.includes('powerpoint') || type.includes('presentation')) return <FileText className="h-6 w-6 text-orange-400" />
    
    return <FileText className="h-6 w-6" />
  }

  const getFileExtension = (name: string) => {
    const parts = name.split('.')
    return parts.length > 1 ? parts.pop()?.toUpperCase() : 'FILE'
  }

  const handleDownload = async () => {
    console.log('🔽 Начинаем скачивание файла:', fileName, fileUrl)
    
    try {
      // Используем наш API endpoint для проксирования скачивания
      const downloadUrl = `/api/download-file?url=${encodeURIComponent(fileUrl)}&filename=${encodeURIComponent(fileName)}`
      console.log('📡 Скачиваем через API endpoint:', downloadUrl)
      
      // Создаем ссылку для прямого скачивания
      const link = document.createElement('a')
      link.href = downloadUrl
      link.download = fileName || 'file'
      link.style.display = 'none'
      
      document.body.appendChild(link)
      console.log('⬇️ Запускаем скачивание через API...')
      link.click()
      
      // Очистка с задержкой
      setTimeout(() => {
        try {
          document.body.removeChild(link)
          console.log('✅ Скачивание через API успешно запущено')
        } catch (cleanupError) {
          console.warn('⚠️ Ошибка очистки:', cleanupError)
        }
      }, 1000)
      
    } catch (error) {
      console.error('❌ Ошибка скачивания через API:', error)
      fallbackDownload()
    }
    
    function fallbackDownload() {
      console.log('🚨 Используем fallback метод - открытие в новой вкладке')
      window.open(fileUrl, '_blank')
    }
  }

  return (
    <div className={`flex items-center space-x-3 p-3 rounded-lg max-w-sm cursor-pointer hover:opacity-80 transition-opacity ${
      isCurrentUser 
        ? 'bg-blue-500/20 border border-blue-500/30' 
        : 'bg-white/10 border border-white/20'
    }`} onClick={handleDownload}>
      
      {/* Иконка файла */}
      <div className={`flex-shrink-0 w-12 h-12 rounded-lg flex items-center justify-center ${
        isCurrentUser ? 'bg-blue-500/30' : 'bg-white/20'
      }`}>
        {getFileIcon(fileType)}
      </div>

      {/* Информация о файле */}
      <div className="flex-1 min-w-0">
        <p className={`font-medium text-sm truncate ${
          isCurrentUser ? 'text-white' : 'text-white'
        }`}>
          {fileName}
        </p>
        
        <div className="flex items-center space-x-2 mt-1">
          {fileSize && (
            <span className={`text-xs ${
              isCurrentUser ? 'text-blue-300/70' : 'text-white/60'
            }`}>
              {formatFileSize(fileSize)}
            </span>
          )}
          
          <span className={`text-xs ${
            isCurrentUser ? 'text-blue-300/70' : 'text-white/60'
          }`}>
            {getFileExtension(fileName)}
          </span>
        </div>
      </div>

      {/* Кнопка скачивания */}
      <Button
        onClick={(e) => {
          e.stopPropagation()
          handleDownload()
        }}
        size="sm"
        variant="ghost"
        className={`flex-shrink-0 ${
          isCurrentUser 
            ? 'text-blue-300 hover:text-blue-200 hover:bg-blue-500/30' 
            : 'text-white/60 hover:text-white hover:bg-white/20'
        }`}
      >
        <Download className="h-4 w-4" />
      </Button>
    </div>
  )
} 