'use client';
import React, { useEffect, useRef, useState } from 'react';
import { Loader2, Plus, Trash2, Upload, Pencil, X } from 'lucide-react';

export default function AdminGallery() {
  const [items, setItems] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [uploading, setUploading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [form, setForm] = useState({ name: '', images: [] as string[] });
  const [searchTerm, setSearchTerm] = useState('');
  const [page, setPage] = useState(1);
  const pageSize = 5;
  const fileInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    fetchGallery();
  }, []);
  useEffect(() => {
    setPage(1);
  }, [searchTerm]);

  const fetchGallery = async () => {
    try {
      const res = await fetch('/api/gallery');
      const data = await res.json();
      if (Array.isArray(data)) {
        setItems(data);
      }
    } catch (e) {
      console.error('Failed to fetch gallery');
    } finally {
      setLoading(false);
    }
  };

  const resetForm = () => {
    setEditingId(null);
    setForm({ name: '', images: [] });
  };

  const startEdit = (item: any) => {
    setEditingId(item._id);
    setForm({
      name: item.name || item.title || '',
      images: Array.isArray(item.images) && item.images.length > 0
        ? item.images
        : (item.imageUrl ? [item.imageUrl] : [])
    });
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Are you sure you want to delete this gallery?')) return;

    try {
      const res = await fetch(`/api/gallery/${id}`, { method: 'DELETE' });
      if (res.ok) {
        setItems((prev) => prev.filter((item) => item._id !== id));
      }
    } catch (e) {
      console.error('Failed to delete', e);
    }
  };

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

    setUploading(true);
    const formData = new FormData();
    for (let i = 0; i < files.length; i++) {
      if (files[i].size > 3 * 1024 * 1024) {
        alert(`File ${files[i].name} is too large. Max 3MB.`);
        setUploading(false);
        if (fileInputRef.current) fileInputRef.current.value = '';
        return;
      }
      formData.append('file', files[i]);
    }

    try {
      const uploadRes = await fetch('/api/upload', {
        method: 'POST',
        body: formData,
      });
      const uploadData = await uploadRes.json();
      if (!uploadRes.ok) throw new Error(uploadData.error || 'Upload failed');

      const filepaths = uploadData.filepaths || (uploadData.filepath ? [uploadData.filepath] : []);
      setForm((prev) => ({ ...prev, images: [...prev.images, ...filepaths] }));
    } catch (err: any) {
      alert('Upload failed: ' + err.message);
      console.error(err);
    } finally {
      setUploading(false);
      if (fileInputRef.current) fileInputRef.current.value = '';
    }
  };

  const removeImageFromForm = (idx: number) => {
    setForm((prev) => ({
      ...prev,
      images: prev.images.filter((_, i) => i !== idx)
    }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.name.trim()) {
      alert('Please enter Name.');
      return;
    }
    if (form.images.length === 0) {
      alert('Please upload Images.');
      return;
    }

    setSubmitting(true);
    try {
      const url = editingId ? `/api/gallery/${editingId}` : '/api/gallery';
      const method = editingId ? 'PUT' : 'POST';
      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: form.name.trim(),
          images: form.images,
        }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Failed to save gallery');

      resetForm();
      fetchGallery();
    } catch (err: any) {
      alert('Save failed: ' + err.message);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div>
      <div className="mb-8">
        <h2 className="text-2xl font-bold text-slate-800">Gallery Management</h2>
        <p className="text-sm text-slate-500">Create and edit gallery by Name and multiple Images.</p>
      </div>

      <form onSubmit={handleSubmit} className="bg-white border border-slate-200 rounded-xl p-6 shadow-sm mb-8 space-y-5">
        <div className="flex items-center justify-between">
          <h3 className="text-lg font-bold text-slate-800">{editingId ? 'Edit Gallery' : 'Add Gallery'}</h3>
          {editingId && (
            <button
              type="button"
              onClick={resetForm}
              className="text-slate-500 hover:text-slate-800 inline-flex items-center gap-1"
            >
              <X size={16} /> Cancel Edit
            </button>
          )}
        </div>

        <div>
          <label className="block text-sm font-semibold text-slate-700 mb-2">Name:</label>
          <input
            type="text"
            value={form.name}
            onChange={(e) => setForm((prev) => ({ ...prev, name: e.target.value }))}
            className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-primary outline-none"
            placeholder="e.g. UKBCCI Trade Delegation Press Conference in Bangladesh"
          />
        </div>

        <div>
          <label className="block text-sm font-semibold text-slate-700 mb-2">Images:</label>
          <div className="flex flex-wrap gap-2 mb-3">
            <input
              type="file"
              ref={fileInputRef}
              onChange={handleUploadImages}
              className="hidden"
              accept="image/png, image/jpeg, image/jpg, image/webp"
              multiple
            />
            <button
              type="button"
              onClick={() => fileInputRef.current?.click()}
              disabled={uploading}
              className="bg-primary hover:bg-primary-dark text-white px-4 py-2 rounded-lg font-medium transition flex items-center gap-2 disabled:opacity-50"
            >
              {uploading ? <Loader2 size={18} className="animate-spin" /> : <Upload size={18} />}
              Add Images
            </button>
          </div>

          {form.images.length > 0 && (
            <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3">
              {form.images.map((img, idx) => (
                <div key={`${img}-${idx}`} className="relative rounded-lg overflow-hidden border border-slate-200 aspect-square group">
                  <img src={img} alt="Preview" className="w-full h-full object-cover" />
                  <button
                    type="button"
                    onClick={() => removeImageFromForm(idx)}
                    className="absolute top-1 right-1 p-1 rounded-full bg-red-600 text-white opacity-0 group-hover:opacity-100 transition"
                    title="Remove image"
                  >
                    <X size={12} />
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>

        <button
          type="submit"
          disabled={submitting || uploading}
          className="bg-slate-900 hover:bg-slate-800 text-white px-5 py-2.5 rounded-lg font-medium transition disabled:opacity-50 flex items-center gap-2"
        >
          {submitting ? <Loader2 size={18} className="animate-spin" /> : <Plus size={18} />}
          {editingId ? 'Update Gallery' : 'Save Gallery'}
        </button>
      </form>

      {loading ? (
        <div className="flex justify-center py-20">
          <Loader2 size={32} className="animate-spin text-primary" />
        </div>
      ) : items.length === 0 ? (
        <div className="bg-slate-50 border-2 border-dashed border-slate-200 rounded-xl p-12 text-center">
          <p className="text-slate-500">No gallery found yet.</p>
        </div>
      ) : (
        <div className="space-y-4">
          <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-3">
            <div className="md:max-w-xs w-full">
              <input
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                placeholder="Search gallery..."
                className="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-primary outline-none text-sm"
              />
            </div>
          </div>

          {(() => {
            const filtered = items.filter((item) => {
              const term = searchTerm.toLowerCase().trim();
              if (!term) return true;
              const name = (item.name || item.title || '').toLowerCase();
              return name.includes(term);
            });
            const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
            const start = (page - 1) * pageSize;
            const paged = filtered.slice(start, start + pageSize);

            return (
              <>
                {paged.map((item: any) => {
                  const images = (item.images && item.images.length > 0) ? item.images : (item.imageUrl ? [item.imageUrl] : []);
                  const displayName = item.name || item.title || 'Untitled';

                  return (
                    <div key={item._id} className="bg-white border border-slate-200 rounded-xl p-4 shadow-sm">
                      <div className="flex justify-between items-center mb-3">
                        <h3 className="font-bold text-slate-900">{displayName}</h3>
                        <div className="flex items-center gap-1">
                          <button
                            onClick={() => startEdit(item)}
                            className="p-2 text-slate-400 hover:text-blue-600 rounded-full"
                            title="Edit gallery"
                          >
                            <Pencil size={16} />
                          </button>
                          <button
                            onClick={() => handleDelete(item._id)}
                            className="p-2 text-slate-400 hover:text-red-600 rounded-full"
                            title="Delete gallery"
                          >
                            <Trash2 size={16} />
                          </button>
                        </div>
                      </div>
                      <p className="text-xs text-slate-500 mb-3">{images.length} image(s)</p>
                      <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-2">
                        {images.map((img: string, idx: number) => (
                          <div key={`${img}-${idx}`} className="rounded-lg overflow-hidden border border-slate-200 aspect-square">
                            <img src={img} alt={displayName} className="w-full h-full object-cover" />
                          </div>
                        ))}
                      </div>
                    </div>
                  );
                })}

                <div className="p-4 flex flex-col md:flex-row md:items-center md:justify-between gap-3 border-t border-slate-100">
                  <p className="text-xs text-slate-500">Showing {paged.length} of {filtered.length} galleries</p>
                  <div className="flex items-center gap-2">
                    <button
                      onClick={() => setPage((p) => Math.max(1, p - 1))}
                      disabled={page === 1}
                      className="px-3 py-1.5 rounded-lg border border-slate-200 text-sm disabled:opacity-50"
                    >
                      Prev
                    </button>
                    <span className="text-sm text-slate-600">Page {page} of {totalPages}</span>
                    <button
                      onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                      disabled={page === totalPages}
                      className="px-3 py-1.5 rounded-lg border border-slate-200 text-sm disabled:opacity-50"
                    >
                      Next
                    </button>
                  </div>
                </div>
              </>
            );
          })()}
        </div>
      )}
    </div>
  );
}
