import React, { useState, useEffect } from 'react';
import { Upload, Trash2, Image as ImageIcon, FileText, Video, ExternalLink, Plus } from 'lucide-react';

interface MediaItem {
  _id: string;
  filename: string;
  originalname: string;
  mimetype: string;
  size: number;
  url: string;
  createdAt: string;
}

const MediaAdmin: React.FC = () => {
  const [media, setMedia] = useState<MediaItem[]>([]);
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchMedia = async () => {
    try {
      const response = await fetch('/api/media');
      const data = await response.json();
      setMedia(data);
    } catch (err) {
      console.error('Error fetching media:', err);
    }
  };

  useEffect(() => {
    fetchMedia();
  }, []);

  const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!e.target.files?.[0]) return;
    
    setUploading(true);
    setError(null);
    const formData = new FormData();
    formData.append('file', e.target.files[0]);

    try {
      const response = await fetch('/api/media/upload', {
        method: 'POST',
        body: formData,
      });

      if (!response.ok) throw new Error('Error al subir el archivo');
      
      await fetchMedia();
    } catch (err: any) {
      setError(err.message);
    } finally {
      setUploading(false);
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('¿Estás seguro de eliminar este archivo?')) return;

    try {
      const response = await fetch(`/api/media/${id}`, {
        method: 'DELETE',
      });

      if (!response.ok) throw new Error('Error al eliminar');
      
      setMedia(media.filter(item => item._id !== id));
    } catch (err: any) {
      alert(err.message);
    }
  };

  const formatSize = (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];
  };

  return (
    <div className="p-6 max-w-6xl mx-auto space-y-8">
      <div className="flex justify-between items-end border-b-2 border-orange-500 pb-4">
        <div>
          <h1 className="text-4xl font-black uppercase tracking-tighter">Administrador de Medios</h1>
          <p className="text-zinc-500 font-mono text-sm mt-1">// Gestor de diagramas, fotos y videos técnicos</p>
        </div>
        
        <label className="bg-orange-500 text-black px-6 py-3 font-bold uppercase cursor-pointer hover:bg-orange-400 transition-colors flex items-center gap-2">
          {uploading ? 'Subiendo...' : <><Plus size={20} /> Añadir Medio</>}
          <input type="file" className="hidden" onChange={handleUpload} disabled={uploading} />
        </label>
      </div>

      {error && (
        <div className="bg-red-900/20 border-l-4 border-red-500 p-4 text-red-500 font-mono text-sm">
          ERROR: {error}
        </div>
      )}

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {media.map((item) => (
          <div key={item._id} className="bg-zinc-900 border border-zinc-800 p-4 group hover:border-orange-500 transition-colors flex flex-col">
            <div className="aspect-video bg-black flex items-center justify-center mb-4 relative overflow-hidden border border-zinc-800">
              {item.mimetype.startsWith('image/') ? (
                <img src={item.url} alt={item.originalname} className="w-full h-full object-cover" />
              ) : item.mimetype.startsWith('video/') ? (
                <Video size={48} className="text-zinc-700" />
              ) : (
                <FileText size={48} className="text-zinc-700" />
              )}
            </div>

            <div className="flex-1 min-w-0">
              <h3 className="font-bold text-lg truncate uppercase tracking-tight" title={item.originalname}>
                {item.originalname}
              </h3>
              <div className="font-mono text-[10px] text-zinc-500 mt-2 space-y-1">
                <p>MIME: {item.mimetype}</p>
                <p>SIZE: {formatSize(item.size)}</p>
                <p>DATE: {new Date(item.createdAt).toLocaleDateString()}</p>
              </div>
            </div>

            <div className="flex gap-2 mt-6 pt-4 border-t border-zinc-800">
              <a 
                href={item.url} 
                target="_blank" 
                rel="noreferrer"
                className="flex-1 flex items-center justify-center gap-2 py-2 border border-zinc-700 hover:bg-zinc-800 text-xs font-bold uppercase transition-colors"
              >
                <ExternalLink size={14} /> Ver
              </a>
              <button 
                onClick={() => handleDelete(item._id)}
                className="w-12 flex items-center justify-center bg-zinc-800 hover:bg-red-900/30 hover:text-red-500 transition-all text-zinc-500 border border-zinc-700 hover:border-red-900"
              >
                <Trash2 size={16} />
              </button>
            </div>
          </div>
        ))}

        {media.length === 0 && !uploading && (
          <div className="col-span-full py-20 border-2 border-dashed border-zinc-800 flex flex-col items-center justify-center text-zinc-600 font-mono uppercase text-sm tracking-widest">
            <ImageIcon size={48} className="mb-4 opacity-20" />
            Galería vacía // Sube el primer medio
          </div>
        )}
      </div>
    </div>
  );
};

export default MediaAdmin;
