'use client';
import React, { useState, useRef } from 'react';
import { Upload, X, Image as ImageIcon, Loader2 } from 'lucide-react';

interface ImageUploadProps {
  label?: string;
  value?: string | string[]; // Single URL or Array of URLs
  onChange: (value: string | string[]) => void;
  multiple?: boolean;
  maxFiles?: number;
}

const ImageUpload: React.FC<ImageUploadProps> = ({ 
  label = "Upload Image", 
  value, 
  onChange, 
  multiple = false,
  maxFiles = 50 
}) => {
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Normalize value to array for display
  const currentImages = Array.isArray(value) ? value : (value ? [value] : []);

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files || files.length === 0) return;

    setError(null);
    setUploading(true);

    // Frontend Validation
    if (multiple && currentImages.length + files.length > maxFiles) {
        setError(`You can only upload up to ${maxFiles} images.`);
        setUploading(false);
        return;
    }

    for (let i = 0; i < files.length; i++) {
        if (files[i].size > 3 * 1024 * 1024) {
            setError(`File "${files[i].name}" is too large (Max 3MB).`);
            setUploading(false);
            return;
        }
    }

    const formData = new FormData();
    for (let i = 0; i < files.length; i++) {
      formData.append('file', files[i]);
    }

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

      const data = await res.json();

      if (!res.ok) {
        throw new Error(data.error || 'Upload failed');
      }

      if (multiple) {
        // Append new images to existing list
        onChange([...currentImages, ...data.filepaths]);
      } else {
        // Replace single image
        onChange(data.filepath);
      }
    } catch (err: any) {
      setError(err.message);
    } finally {
      setUploading(false);
      if (fileInputRef.current) fileInputRef.current.value = '';
    }
  };

  const removeImage = (indexToRemove: number) => {
    if (multiple) {
      const newImages = currentImages.filter((_, index) => index !== indexToRemove);
      onChange(newImages);
    } else {
      onChange('');
    }
  };

  return (
    <div className="w-full">
      <label className="block text-sm font-medium text-slate-700 mb-2">{label}</label>
      
      {/* Upload Area */}
      <div className="mb-4">
        <input
          type="file"
          ref={fileInputRef}
          onChange={handleFileChange}
          className="hidden"
          accept="image/png, image/jpeg, image/jpg, image/webp"
          multiple={multiple}
        />
        <button
          type="button"
          onClick={() => fileInputRef.current?.click()}
          disabled={uploading}
          className={`w-full border-2 border-dashed border-slate-300 rounded-lg p-6 flex flex-col items-center justify-center text-slate-500 hover:border-primary hover:bg-slate-50 transition ${uploading ? 'opacity-50 cursor-not-allowed' : ''}`}
        >
          {uploading ? (
            <>
              <Loader2 size={24} className="animate-spin text-primary mb-2" />
              <span className="text-sm font-medium">Uploading...</span>
            </>
          ) : (
            <>
              <Upload size={24} className="mb-2" />
              <span className="text-sm font-medium">Click to Upload {multiple ? '(Multiple)' : ''}</span>
              <span className="text-xs text-slate-400 mt-1">PNG, JPG, JPEG (Max 3MB)</span>
            </>
          )}
        </button>
        {error && <p className="text-red-500 text-xs mt-2">{error}</p>}
      </div>

      {/* Previews */}
      {currentImages.length > 0 && (
        <div className={`grid gap-4 ${multiple ? 'grid-cols-2 md:grid-cols-4' : 'grid-cols-1'}`}>
          {currentImages.map((src, index) => (
            <div key={index} className="relative group border border-slate-200 rounded-lg overflow-hidden bg-slate-100 aspect-video md:aspect-square">
              <img src={src} alt="Preview" className="w-full h-full object-cover" />
              <button
                type="button"
                onClick={() => removeImage(index)}
                className="absolute top-1 right-1 bg-red-500 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition shadow-sm hover:bg-red-600"
                title="Remove Image"
              >
                <X size={14} />
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default ImageUpload;