'use client';

import { useState } from 'react';
import { Upload, X, Image as ImageIcon } from 'lucide-react';

interface ReferenceImage {
  id: string;
  data: string; // Base64
  mimeType: string;
  preview: string; // Data URL para preview
  name: string;
}

interface ReferenceImagesProps {
  images: ReferenceImage[];
  onImagesChange: (images: ReferenceImage[]) => void;
  maxImages?: number;
}

export function ReferenceImages({ images, onImagesChange, maxImages = 3 }: ReferenceImagesProps) {
  const [isDragging, setIsDragging] = useState(false);

  const handleFileSelect = async (files: FileList | null) => {
    if (!files || files.length === 0) return;

    const newImages: ReferenceImage[] = [];

    for (let i = 0; i < Math.min(files.length, maxImages - images.length); i++) {
      const file = files[i];

      // Validar que sea una imagen
      if (!file.type.startsWith('image/')) {
        continue;
      }

      // Validar tamaño (máx 5MB)
      if (file.size > 5 * 1024 * 1024) {
        continue;
      }

      try {
        // Leer archivo como base64
        const base64 = await fileToBase64(file);

        newImages.push({
          id: `${Date.now()}-${i}`,
          data: base64,
          mimeType: file.type,
          preview: `data:${file.type};base64,${base64}`,
          name: file.name,
        });
      } catch (error) {
      }
    }

    if (newImages.length > 0) {
      onImagesChange([...images, ...newImages]);
    }
  };

  const fileToBase64 = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => {
        const result = reader.result as string;
        // Remover el prefijo "data:image/...;base64,"
        const base64 = result.split(',')[1];
        resolve(base64);
      };
      reader.onerror = reject;
      reader.readAsDataURL(file);
    });
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
    handleFileSelect(e.dataTransfer.files);
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  };

  const handleDragLeave = () => {
    setIsDragging(false);
  };

  const removeImage = (id: string) => {
    onImagesChange(images.filter(img => img.id !== id));
  };

  return (
    <div className="space-y-3">
      <label className="text-xs font-medium text-muted-foreground">
        Imágenes de Referencia (Opcional) - {images.length}/{maxImages}
      </label>

      {/* Zona de drop */}
      {images.length < maxImages && (
        <div
          onDrop={handleDrop}
          onDragOver={handleDragOver}
          onDragLeave={handleDragLeave}
          className={`
            relative border-2 border-dashed rounded-lg p-6 text-center cursor-pointer
            transition-all
            ${isDragging
              ? 'border-primary bg-primary/10'
              : 'border-border hover:border-primary hover:bg-accent'
            }
          `}
        >
          <input
            type="file"
            accept="image/*"
            multiple
            onChange={(e) => handleFileSelect(e.target.files)}
            className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
          />
          <div className="flex flex-col items-center gap-2">
            <Upload className="w-8 h-8 text-muted-foreground" />
            <p className="text-sm text-muted-foreground">
              Arrastra imágenes aquí o haz clic para seleccionar
            </p>
            <p className="text-xs text-muted-foreground">
              PNG, JPG, WebP (máx 5MB)
            </p>
          </div>
        </div>
      )}

      {/* Grid de imágenes */}
      {images.length > 0 && (
        <div className="grid grid-cols-3 gap-2">
          {images.map((image) => (
            <div
              key={image.id}
              className="relative group aspect-square bg-secondary rounded-lg overflow-hidden border border-border"
            >
              <img
                src={image.preview}
                alt={image.name}
                className="w-full h-full object-cover"
              />
              <button
                onClick={() => removeImage(image.id)}
                className="absolute top-1 right-1 p-1 bg-red-500 text-white rounded-full opacity-0 group-hover:opacity-100 transition-opacity"
                title="Eliminar imagen"
              >
                <X className="w-4 h-4" />
              </button>
              <div className="absolute bottom-0 left-0 right-0 bg-black/60 text-white text-xs p-1 truncate">
                {image.name}
              </div>
            </div>
          ))}
        </div>
      )}

      {images.length === 0 && (
        <p className="text-xs text-muted-foreground italic">
          Las imágenes de referencia ayudan a guiar el estilo y composición de la imagen generada
        </p>
      )}
    </div>
  );
}
