'use client'
import { useState, useRef } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Upload, File, Trash2, Download, Eye, Image, FileText } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { toast } from 'sonner'
import { cn } from '@/lib/utils'

interface DocFile {
  id: string
  name: string
  size: number
  type: string
  url: string
  uploadedAt: string
  uploadedBy: string
}

const MOCK_DOCS: DocFile[] = [
  { id: '1', name: 'DNI_frente_Lopez.pdf', size: 245000, type: 'application/pdf', url: '#', uploadedAt: '2026-05-10', uploadedBy: 'Martín' },
  { id: '2', name: 'Recibo_sueldo_mayo.jpg', size: 1200000, type: 'image/jpeg', url: '#', uploadedAt: '2026-05-11', uploadedBy: 'Martín' },
  { id: '3', name: 'Escritura_propiedad.pdf', size: 3500000, type: 'application/pdf', url: '#', uploadedAt: '2026-05-12', uploadedBy: 'Admin' },
]

function 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'
}

function DocIcon({ type }: { type: string }) {
  if (type.includes('image')) return <Image size={20} className="text-blue-500" />
  return <FileText size={20} className="text-red-500" />
}

export function DocumentsSection({ operationId }: { operationId: string }) {
  const [docs, setDocs] = useState<DocFile[]>(MOCK_DOCS)
  const [dragging, setDragging] = useState(false)
  const inputRef = useRef<HTMLInputElement>(null)

  const handleFiles = (files: FileList | null) => {
    if (!files) return
    const allowed = ['application/pdf', 'image/jpeg', 'image/png', 'image/webp']
    Array.from(files).forEach(file => {
      if (!allowed.includes(file.type)) {
        toast.error(`Tipo no permitido: ${file.name}`)
        return
      }
      const newDoc: DocFile = {
        id: Date.now().toString(),
        name: file.name,
        size: file.size,
        type: file.type,
        url: URL.createObjectURL(file),
        uploadedAt: new Date().toISOString().split('T')[0],
        uploadedBy: 'Martín',
      }
      setDocs(prev => [newDoc, ...prev])
      toast.success(`Archivo subido: ${file.name}`)
    })
  }

  const remove = (id: string) => {
    setDocs(prev => prev.filter(d => d.id !== id))
    toast.success('Documento eliminado')
  }

  return (
    <div className="space-y-4">
      {/* Drop Zone */}
      <div
        onDragOver={e => { e.preventDefault(); setDragging(true) }}
        onDragLeave={() => setDragging(false)}
        onDrop={e => { e.preventDefault(); setDragging(false); handleFiles(e.dataTransfer.files) }}
        onClick={() => inputRef.current?.click()}
        className={cn(
          'border-2 border-dashed rounded-xl p-8 text-center cursor-pointer transition-all',
          dragging
            ? 'border-primary bg-primary/5'
            : 'border-border hover:border-primary/50 hover:bg-accent/30'
        )}
      >
        <Upload size={28} className="mx-auto text-muted-foreground mb-2" />
        <p className="text-sm font-medium text-foreground">Arrastrá archivos aquí o hacé click para subir</p>
        <p className="text-xs text-muted-foreground mt-1">PDF, JPG, PNG, WEBP · Máx. 10MB por archivo</p>
        <input
          ref={inputRef}
          type="file"
          multiple
          accept=".pdf,.jpg,.jpeg,.png,.webp"
          className="hidden"
          onChange={e => handleFiles(e.target.files)}
        />
      </div>

      {/* Files list */}
      <div className="bg-card border border-border rounded-xl overflow-hidden">
        <div className="flex items-center justify-between px-4 py-3 border-b border-border">
          <h4 className="text-sm font-semibold text-foreground">Documentos ({docs.length})</h4>
        </div>
        <AnimatePresence>
          {docs.map((doc, i) => (
            <motion.div
              key={doc.id}
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: 'auto' }}
              exit={{ opacity: 0, height: 0 }}
              className="flex items-center gap-3 px-4 py-3 border-b border-border last:border-0 hover:bg-accent/30 transition-colors"
            >
              <DocIcon type={doc.type} />
              <div className="flex-1 min-w-0">
                <p className="text-sm font-medium text-foreground truncate">{doc.name}</p>
                <p className="text-xs text-muted-foreground">
                  {formatFileSize(doc.size)} · Subido por {doc.uploadedBy} · {doc.uploadedAt}
                </p>
              </div>
              <div className="flex items-center gap-1">
                <Button size="icon" variant="ghost" className="h-7 w-7" asChild>
                  <a href={doc.url} target="_blank" rel="noreferrer"><Eye size={13} /></a>
                </Button>
                <Button size="icon" variant="ghost" className="h-7 w-7" asChild>
                  <a href={doc.url} download={doc.name}><Download size={13} /></a>
                </Button>
                <Button
                  size="icon" variant="ghost"
                  className="h-7 w-7 text-destructive hover:text-destructive"
                  onClick={() => remove(doc.id)}
                >
                  <Trash2 size={13} />
                </Button>
              </div>
            </motion.div>
          ))}
        </AnimatePresence>
        {docs.length === 0 && (
          <div className="py-10 text-center text-muted-foreground text-sm">
            No hay documentos cargados
          </div>
        )}
      </div>
    </div>
  )
}
