import { useEffect, useState, useRef } from 'react';
import { supabase } from './supabaseClient';
import toast from 'react-hot-toast';
import { Trash2, Upload, X, Image } from 'lucide-react';

interface GalleryImage {
  name: string;
  path: string;
  url: string;
  size?: number;
}

interface Props {
  userId: string;
  onInsert: (url: string, mode: 'header' | 'cursor') => void;
  onClose: () => void;
}

const BUCKET = 'template-images';

const ImageGallery = ({ userId, onInsert, onClose }: Props) => {
  const folder = userId || 'default';
  const [images, setImages] = useState<GalleryImage[]>([]);
  const [loading, setLoading] = useState(true);
  const [uploading, setUploading] = useState(false);
  const [deletingPath, setDeletingPath] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    fetchImages();
  }, [folder]);

  const fetchImages = async () => {
    setLoading(true);
    try {
      const { data, error } = await supabase.storage.from(BUCKET).list(folder, {
        limit: 200,
        sortBy: { column: 'created_at', order: 'desc' },
      });
      if (error) throw error;
      const files = (data || []).filter(f => f.name !== '.emptyFolderPlaceholder');
      const mapped: GalleryImage[] = files.map(f => {
        const path = `${folder}/${f.name}`;
        return {
          name: f.name,
          path,
          url: supabase.storage.from(BUCKET).getPublicUrl(path).data.publicUrl,
          size: f.metadata?.size,
        };
      });
      setImages(mapped);
    } catch (err: any) {
      toast.error('Could not load gallery: ' + err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    const validTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/webp'];
    if (!validTypes.includes(file.type)) {
      toast.error('Please upload a PNG, JPG, GIF, or WebP image.');
      return;
    }
    if (file.size > 2 * 1024 * 1024) {
      toast.error('File must be under 2 MB.');
      return;
    }

    setUploading(true);
    try {
      const ext = file.name.split('.').pop();
      const fileName = `${Math.random().toString(36).substring(2)}_${Date.now()}.${ext}`;
      const path = `${folder}/${fileName}`;
      const { error } = await supabase.storage.from(BUCKET).upload(path, file);
      if (error) throw error;
      toast.success('Image uploaded.');
      await fetchImages();
    } catch (err: any) {
      toast.error('Upload failed: ' + err.message);
    } finally {
      setUploading(false);
      if (fileInputRef.current) fileInputRef.current.value = '';
    }
  };

  const handleDelete = async (img: GalleryImage) => {
    setDeletingPath(img.path);
    try {
      const { error } = await supabase.storage.from(BUCKET).remove([img.path]);
      if (error) throw error;
      toast.success('Image deleted.');
      setImages(prev => prev.filter(i => i.path !== img.path));
    } catch (err: any) {
      toast.error('Delete failed: ' + err.message);
    } finally {
      setDeletingPath(null);
    }
  };

  const formatSize = (bytes?: number) => {
    if (!bytes) return '';
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm">
      <div className="bg-white rounded-3xl shadow-2xl w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden">

        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-slate-100">
          <div className="flex items-center gap-3">
            <Image className="text-purple-500" size={22} />
            <div>
              <h2 className="text-lg font-bold text-slate-800">Image Gallery</h2>
              <p className="text-[10px] uppercase tracking-widest font-bold text-slate-400">
                {images.length} image{images.length !== 1 ? 's' : ''} · folder: <span className="font-mono">{folder}</span>
              </p>
            </div>
          </div>
          <div className="flex items-center gap-3">
            <button
              onClick={() => fileInputRef.current?.click()}
              disabled={uploading}
              className="flex items-center gap-2 bg-purple-600 text-white px-4 py-2 rounded-xl text-xs font-bold uppercase tracking-widest hover:bg-purple-700 transition-colors disabled:opacity-50"
            >
              <Upload size={14} />
              {uploading ? 'Uploading…' : 'Upload Image'}
            </button>
            <button onClick={onClose} className="p-2 rounded-xl hover:bg-slate-100 transition-colors text-slate-400">
              <X size={20} />
            </button>
          </div>
          <input
            ref={fileInputRef}
            type="file"
            accept="image/png,image/jpeg,image/jpg,image/gif,image/webp"
            className="hidden"
            onChange={handleFileChange}
          />
        </div>

        {/* Body */}
        <div className="flex-1 overflow-y-auto p-6">
          {loading ? (
            <div className="flex items-center justify-center h-48 text-slate-400 italic">
              Loading gallery…
            </div>
          ) : images.length === 0 ? (
            <div className="flex flex-col items-center justify-center h-48 gap-3 text-slate-300">
              <Image size={40} />
              <p className="italic text-sm">No images yet. Upload one to get started.</p>
              <button
                onClick={() => fileInputRef.current?.click()}
                className="text-purple-600 text-xs font-bold hover:underline"
              >
                Upload your first image
              </button>
            </div>
          ) : (
            <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
              {images.map(img => (
                <div
                  key={img.path}
                  className="group relative bg-slate-50 border border-slate-100 rounded-2xl overflow-hidden flex flex-col"
                >
                  {/* Thumbnail */}
                  <div className="relative aspect-video bg-slate-100 overflow-hidden">
                    <img
                      src={img.url}
                      alt={img.name}
                      className="w-full h-full object-cover"
                      loading="lazy"
                    />
                    <button
                      onClick={() => handleDelete(img)}
                      disabled={deletingPath === img.path}
                      className="absolute top-2 right-2 bg-red-500 text-white p-1.5 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity hover:bg-red-600 disabled:opacity-50"
                      title="Delete image"
                    >
                      <Trash2 size={12} />
                    </button>
                  </div>

                  {/* Info + actions */}
                  <div className="p-3 space-y-2">
                    <p className="text-[10px] text-slate-500 truncate font-mono" title={img.name}>
                      {img.name.replace(/^[a-z0-9]+_\d+\./, 'img.')}
                    </p>
                    {img.size && (
                      <p className="text-[9px] text-slate-400">{formatSize(img.size)}</p>
                    )}
                    <div className="flex gap-1.5">
                      <button
                        onClick={() => { onInsert(img.url, 'header'); onClose(); }}
                        className="flex-1 py-1.5 text-[9px] font-bold uppercase tracking-wider bg-slate-100 hover:bg-purple-100 hover:text-purple-700 text-slate-500 rounded-lg transition-colors"
                      >
                        Header
                      </button>
                      <button
                        onClick={() => { onInsert(img.url, 'cursor'); onClose(); }}
                        className="flex-1 py-1.5 text-[9px] font-bold uppercase tracking-wider bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors"
                      >
                        Insert
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

      </div>
    </div>
  );
};

export default ImageGallery;
