'use client'
import { useState, useRef } from 'react'
import { Upload, X, ImageIcon } from 'lucide-react'
import { Skeleton } from '@/components/ui/Skeleton'
import { toast } from 'sonner'

interface LogoUploadProps {
  loading?: boolean
}

export function LogoUpload({ loading }: LogoUploadProps) {
  const [logo, setLogo] = useState<string | null>(null)
  const [dragging, setDragging] = useState(false)
  const inputRef = useRef<HTMLInputElement>(null)

  const handleFile = (file: File) => {
    if (!file.type.startsWith('image/')) {
      toast.error('Solo se permiten imágenes (PNG, JPG, SVG)')
      return
    }
    if (file.size > 2 * 1024 * 1024) {
      toast.error('El archivo no puede superar los 2 MB')
      return
    }
    const reader = new FileReader()
    reader.onload = e => {
      setLogo(e.target?.result as string)
      toast.success('Logo cargado correctamente')
    }
    reader.readAsDataURL(file)
  }

  const onInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) handleFile(file)
  }

  const onDrop = (e: React.DragEvent) => {
    e.preventDefault()
    setDragging(false)
    const file = e.dataTransfer.files?.[0]
    if (file) handleFile(file)
  }

  if (loading) {
    return (
      <div className="bg-card border border-border rounded-xl p-6 space-y-4">
        <Skeleton className="h-5 w-32" />
        <Skeleton className="h-32 w-full rounded-xl" />
      </div>
    )
  }

  return (
    <div className="bg-card border border-border rounded-xl p-6 space-y-4">
      <div className="flex items-center gap-2">
        <ImageIcon size={16} className="text-primary" />
        <h3 className="text-sm font-semibold">Logo de la Inmobiliaria</h3>
      </div>
      <p className="text-xs text-muted-foreground -mt-1">
        Se usa en la ficha exportada de cada operación. PNG, JPG o SVG · máx. 2 MB.
      </p>

      {logo ? (
        <div className="flex items-center gap-4">
          <div className="relative w-28 h-28 rounded-xl border border-border overflow-hidden bg-muted/20 flex items-center justify-center">
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img src={logo} alt="Logo" className="max-w-full max-h-full object-contain p-2" />
            <button
              onClick={() => setLogo(null)}
              className="absolute top-1 right-1 bg-destructive text-white rounded-full p-0.5 hover:bg-destructive/80 transition-colors"
            >
              <X size={12} />
            </button>
          </div>
          <div className="space-y-2">
            <p className="text-sm font-medium text-foreground">Logo cargado</p>
            <p className="text-xs text-muted-foreground">Aparecerá en las fichas exportadas</p>
            <button
              onClick={() => inputRef.current?.click()}
              className="text-xs text-primary hover:underline"
            >
              Cambiar logo
            </button>
          </div>
        </div>
      ) : (
        <div
          onDragOver={e => { e.preventDefault(); setDragging(true) }}
          onDragLeave={() => setDragging(false)}
          onDrop={onDrop}
          onClick={() => inputRef.current?.click()}
          className={`
            relative 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={24} className="mx-auto mb-3 text-muted-foreground/50" />
          <p className="text-sm font-medium text-foreground">
            Arrastrá el logo acá o <span className="text-primary">hacé click</span>
          </p>
          <p className="text-xs text-muted-foreground mt-1">PNG, JPG, SVG · máx. 2 MB</p>
        </div>
      )}

      <input
        ref={inputRef}
        type="file"
        accept="image/*"
        className="hidden"
        onChange={onInputChange}
      />
    </div>
  )
}
