'use client'

import { useState, useRef, useCallback, useEffect } from 'react'
import {
  Upload, X, FileText, File, Loader2, Trash2, Download,
  AlertCircle, CheckCircle2, CloudUpload
} from 'lucide-react'

interface UploadedFile {
  id: string
  filename: string
  size: number
  mimeType: string
  createdAt: string
}

interface FileUploadProps {
  onFilesChange?: (files: UploadedFile[]) => void
  maxFiles?: number
  label?: string
  compact?: boolean
}

const ALLOWED_EXTENSIONS = ['.pdf', '.docx', '.doc', '.txt']
const ALLOWED_TYPES = [
  'application/pdf',
  'application/msword',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  'text/plain',
]
const MAX_SIZE = 50 * 1024 * 1024

function formatSize(bytes: number): string {
  if (bytes < 1024) return bytes + ' B'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
  return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
}

function getFileIcon(mimeType: string) {
  if (mimeType === 'application/pdf') return '📄'
  if (mimeType.includes('word')) return '📝'
  if (mimeType === 'text/plain') return '📃'
  return '📎'
}

export default function FileUpload({
  onFilesChange,
  maxFiles = 10,
  label = 'Documentos de Referência',
  compact = false,
}: FileUploadProps) {
  const [files, setFiles] = useState<UploadedFile[]>([])
  const [uploading, setUploading] = useState(false)
  const [uploadProgress, setUploadProgress] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [dragOver, setDragOver] = useState(false)
  const [deleting, setDeleting] = useState<string | null>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const dropRef = useRef<HTMLDivElement>(null)

  // Load existing uploads on mount
  useEffect(() => {
    loadFiles()
  }, [])

  useEffect(() => {
    onFilesChange?.(files)
  }, [files, onFilesChange])

  const loadFiles = async () => {
    try {
      const res = await fetch('/api/uploads?limit=50')
      if (res.ok) {
        const data = await res.json()
        setFiles(data.uploads || [])
      }
    } catch {
      // silent
    }
  }

  const validateFile = (file: File): string | null => {
    if (!ALLOWED_TYPES.includes(file.type)) {
      const ext = file.name.split('.').pop()?.toLowerCase()
      if (!ext || !ALLOWED_EXTENSIONS.includes('.' + ext)) {
        return `Tipo não permitido: ${file.name}. Aceitos: PDF, DOCX, DOC, TXT`
      }
    }
    if (file.size > MAX_SIZE) {
      return `Arquivo muito grande: ${file.name} (${formatSize(file.size)}). Máx: 50MB`
    }
    return null
  }

  const uploadFile = useCallback(async (file: File) => {
    setError(null)

    const validationError = validateFile(file)
    if (validationError) {
      setError(validationError)
      return
    }

    if (files.length >= maxFiles) {
      setError(`Máximo de ${maxFiles} arquivos`)
      return
    }

    setUploading(true)
    setUploadProgress(`Enviando ${file.name}...`)

    try {
      const formData = new FormData()
      formData.append('file', file)

      const res = await fetch('/api/uploads', {
        method: 'POST',
        body: formData,
      })

      const data = await res.json()

      if (!res.ok) {
        throw new Error(data.error || 'Erro ao fazer upload')
      }

      setFiles(prev => [data.upload, ...prev])
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Erro ao fazer upload')
    } finally {
      setUploading(false)
      setUploadProgress(null)
    }
  }, [files.length, maxFiles])

  const handleFiles = useCallback((fileList: FileList | null) => {
    if (!fileList) return
    Array.from(fileList).forEach(f => uploadFile(f))
  }, [uploadFile])

  const handleDelete = async (id: string) => {
    setDeleting(id)
    try {
      const res = await fetch(`/api/uploads/${id}`, { method: 'DELETE' })
      if (res.ok) {
        setFiles(prev => prev.filter(f => f.id !== id))
      }
    } catch {
      setError('Erro ao excluir arquivo')
    } finally {
      setDeleting(null)
    }
  }

  const handleDownload = (id: string) => {
    window.open(`/api/uploads/${id}`, '_blank')
  }

  // Drag & drop handlers
  const handleDragEnter = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setDragOver(true)
  }

  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    if (e.currentTarget === dropRef.current) {
      setDragOver(false)
    }
  }

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
  }

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setDragOver(false)
    handleFiles(e.dataTransfer.files)
  }

  return (
    <div className="space-y-3">
      {/* Drop Zone */}
      <div
        ref={dropRef}
        onDragEnter={handleDragEnter}
        onDragLeave={handleDragLeave}
        onDragOver={handleDragOver}
        onDrop={handleDrop}
        onClick={() => !uploading && fileInputRef.current?.click()}
        className={`
          relative border-2 border-dashed rounded-xl transition-all duration-200 cursor-pointer
          ${compact ? 'p-4' : 'p-6'}
          ${dragOver
            ? 'border-teal-400 bg-teal-500/10 shadow-lg shadow-teal-500/10'
            : 'border-white/10 hover:border-teal-500/30 hover:bg-white/[0.02]'
          }
          ${uploading ? 'pointer-events-none opacity-60' : ''}
        `}
      >
        <input
          ref={fileInputRef}
          type="file"
          multiple
          accept=".pdf,.docx,.doc,.txt"
          className="hidden"
          onChange={e => handleFiles(e.target.files)}
        />

        <div className="flex flex-col items-center gap-2 text-center">
          {uploading ? (
            <>
              <Loader2 className="w-8 h-8 text-teal-400 animate-spin" />
              <p className="text-sm text-teal-300">{uploadProgress}</p>
            </>
          ) : (
            <>
              <CloudUpload className={`${compact ? 'w-6 h-6' : 'w-8 h-8'} ${dragOver ? 'text-teal-400' : 'text-white/20'}`} />
              <div>
                <p className={`${compact ? 'text-xs' : 'text-sm'} text-white/40`}>
                  {dragOver ? (
                    <span className="text-teal-300 font-medium">Solte o arquivo aqui</span>
                  ) : (
                    <>Arraste arquivos ou <span className="text-teal-400 font-medium">clique para upload</span></>
                  )}
                </p>
                <p className="text-xs text-white/20 mt-1">PDF, DOCX, DOC, TXT · Máx 50MB</p>
              </div>
            </>
          )}
        </div>
      </div>

      {/* Error */}
      {error && (
        <div className="flex items-center gap-2 p-3 rounded-xl bg-red-500/10 border border-red-500/20 text-sm text-red-400">
          <AlertCircle className="w-4 h-4 flex-shrink-0" />
          <span>{error}</span>
          <button onClick={() => setError(null)} className="ml-auto">
            <X className="w-4 h-4" />
          </button>
        </div>
      )}

      {/* File List */}
      {files.length > 0 && (
        <div className="space-y-2">
          {files.map(file => (
            <div
              key={file.id}
              className="flex items-center gap-3 p-3 rounded-xl border border-white/5 bg-white/[0.02] group hover:bg-white/[0.04] transition-all"
            >
              <span className="text-lg flex-shrink-0">{getFileIcon(file.mimeType)}</span>
              <div className="flex-1 min-w-0">
                <p className="text-sm text-white truncate">{file.filename}</p>
                <p className="text-xs text-white/30">{formatSize(file.size)}</p>
              </div>
              <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                <button
                  onClick={(e) => { e.stopPropagation(); handleDownload(file.id) }}
                  className="p-1.5 rounded-lg text-white/40 hover:text-teal-400 hover:bg-teal-500/10 transition-all"
                  title="Download"
                >
                  <Download className="w-4 h-4" />
                </button>
                <button
                  onClick={(e) => { e.stopPropagation(); handleDelete(file.id) }}
                  disabled={deleting === file.id}
                  className="p-1.5 rounded-lg text-white/40 hover:text-red-400 hover:bg-red-500/10 transition-all disabled:opacity-50"
                  title="Excluir"
                >
                  {deleting === file.id ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    <Trash2 className="w-4 h-4" />
                  )}
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
