'use client'

import { Paperclip, Image, X } from 'lucide-react'
import NextImage from 'next/image'
import { useState, useRef } from 'react'

import { Button } from '@/components/ui/button'
import { useAuthContext } from '@/contexts/AuthContext'

interface FileUploaderProps {
  onSendFile: (
    fileUrl: string,
    fileName: string,
    fileSize: number,
    fileType: string,
    messageType: 'IMAGE' | 'FILE',
  ) => void
}

interface UploadedFile {
  url: string
  name: string
  size: number
  type: string
  messageType: 'IMAGE' | 'FILE'
}

export function FileUploader({ onSendFile }: FileUploaderProps) {
  const { user } = useAuthContext()
  const [isUploading, setIsUploading] = useState(false)
  const [selectedFile, setSelectedFile] = useState<UploadedFile | null>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const imageInputRef = useRef<HTMLInputElement>(null)

  const isImageType = (type: string) => {
    return type.startsWith('image/')
  }

  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 Bytes'
    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(2)) + ' ' + sizes[i]
  }

  const handleFileSelect = async (file: File, messageType: 'IMAGE' | 'FILE') => {
    if (!user?.id) return

    setIsUploading(true)

    try {
      const formData = new FormData()
      formData.append('file', file)
      formData.append('userId', user.id)
      formData.append('messageType', messageType)

      const response = await fetch('/api/upload-file', {
        method: 'POST',
        body: formData,
      })

      if (!response.ok) {
        let errorMessage = 'Failed to upload file'
        try {
          const errorData = await response.json()
          errorMessage = errorData.error || errorMessage
        } catch {
          errorMessage = `HTTP ${response.status}: ${response.statusText}`
        }
        throw new Error(errorMessage)
      }

      const result = await response.json()

      if (!result.success) {
        throw new Error(result.error || 'Upload failed')
      }

      setSelectedFile({
        url: result.url,
        name: result.originalName,
        size: result.size,
        type: result.type,
        messageType: result.messageType,
      })
    } catch (error) {
      console.error('Error uploading file:', error)
      const errorMessage = error instanceof Error ? error.message : 'Неизвестная ошибка'
      alert(`Ошибка при загрузке файла: ${errorMessage}`)
    } finally {
      setIsUploading(false)
    }
  }

  const handleFileInputChange = (event: React.ChangeEvent<HTMLInputElement>, messageType: 'IMAGE' | 'FILE') => {
    const file = event.target.files?.[0]
    if (file) {
      handleFileSelect(file, messageType)
    }
    // Очищаем input для возможности выбора того же файла
    event.target.value = ''
  }

  const handleSendFile = () => {
    if (selectedFile) {
      onSendFile(selectedFile.url, selectedFile.name, selectedFile.size, selectedFile.type, selectedFile.messageType)
      setSelectedFile(null)
    }
  }

  const handleCancelFile = () => {
    setSelectedFile(null)
  }

  if (selectedFile) {
    return (
      <div className="flex items-center space-x-2 bg-white/10 rounded-lg p-3 border border-white/20">
        <div className="flex items-center space-x-2 flex-1">
          {isImageType(selectedFile.type) ? (
            <div className="flex items-center space-x-2">
              <NextImage
                src={selectedFile.url}
                alt="Preview"
                width={40}
                height={40}
                className="w-10 h-10 object-cover rounded"
              />
              <div>
                <p className="text-white text-sm font-medium">{selectedFile.name}</p>
                <p className="text-white/60 text-xs">{formatFileSize(selectedFile.size)}</p>
              </div>
            </div>
          ) : (
            <div className="flex items-center space-x-2">
              <div className="w-10 h-10 bg-blue-500/20 rounded flex items-center justify-center">
                <Paperclip className="h-5 w-5 text-blue-300" />
              </div>
              <div>
                <p className="text-white text-sm font-medium">{selectedFile.name}</p>
                <p className="text-white/60 text-xs">{formatFileSize(selectedFile.size)}</p>
              </div>
            </div>
          )}
        </div>

        <div className="flex items-center space-x-1">
          <Button
            onClick={handleSendFile}
            size="sm"
            className="bg-green-500/20 hover:bg-green-500/30 text-green-300 border-green-500/30"
            variant="outline"
          >
            Отправить
          </Button>
          <Button
            onClick={handleCancelFile}
            size="sm"
            variant="ghost"
            className="text-white/60 hover:text-white hover:bg-white/10 p-2"
          >
            <X className="h-4 w-4" />
          </Button>
        </div>
      </div>
    )
  }

  return (
    <>
      {/* Кнопка для загрузки изображений */}
      <Button
        type="button"
        variant="ghost"
        onClick={() => imageInputRef.current?.click()}
        disabled={isUploading}
        className="text-white/60 hover:text-white hover:bg-white/10 h-10 w-10 p-0"
      >
        {/* eslint-disable-next-line jsx-a11y/alt-text */}
        <Image className="h-4 w-4" />
      </Button>

      {/* Кнопка для загрузки файлов */}
      <Button
        type="button"
        variant="ghost"
        onClick={() => fileInputRef.current?.click()}
        disabled={isUploading}
        className="text-white/60 hover:text-white hover:bg-white/10 h-10 w-10 p-0"
      >
        <Paperclip className="h-4 w-4" />
      </Button>

      {/* Скрытые input элементы */}
      <input
        ref={imageInputRef}
        type="file"
        accept="image/*"
        onChange={(e) => handleFileInputChange(e, 'IMAGE')}
        className="hidden"
      />

      <input
        ref={fileInputRef}
        type="file"
        accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.zip,.json"
        onChange={(e) => handleFileInputChange(e, 'FILE')}
        className="hidden"
      />

      {isUploading && <div className="text-white/60 text-xs">Загрузка...</div>}
    </>
  )
}
