import React, { useState, useEffect, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Button, Container } from '@mui/material';
import Swal from 'sweetalert2/dist/sweetalert2.js';
import 'sweetalert2/src/sweetalert2.scss';

// Components
import Navbar from '../ComponentUtils/Headers/Navbar';
import Footer from '../ComponentUtils/Footer';
import ImageGallery from '../ComponentUtils/ImageGallery';
import DescriptionInput from '../ComponentUtils/MultiUpload/DescriptionInput';

// Services
import { updateImageOrder } from '../../services/reorderService';




const ModerationGroupImagesPage = () => {
    const { groupId } = useParams();
    const navigate = useNavigate();
    const [group, setGroup] = useState(null);
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [error, setError] = useState(null);

    // selectedImages will hold objects compatible with ImagePreviewGallery
    const [selectedImages, setSelectedImages] = useState([]);
    const [metadata, setMetadata] = useState({ year: new Date().getFullYear(), title: '', description: '', name: '' });
    const [isReordering, setIsReordering] = useState(false);
    const [isEditMode, setIsEditMode] = useState(false);
    const [imageDescriptions, setImageDescriptions] = useState({});

    useEffect(() => {
        loadGroup();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [groupId]);

    const loadGroup = useCallback(async () => {
        try {
            setLoading(true);
            const res = await fetch(`/moderation/groups/${groupId}`);
            if (!res.ok) throw new Error('Nicht gefunden');
            const data = await res.json();
            setGroup(data);

            // Map group's images to preview-friendly objects
            if (data.images && data.images.length > 0) {
                const mapped = data.images.map(img => ({
                    ...img, // Pass all image fields including previewPath and imageDescription
                    remoteUrl: `/download/${img.fileName}`, // Keep for backward compatibility
                    originalName: img.originalName || img.fileName,
                    id: img.id
                }));
                setSelectedImages(mapped);
                
                // Initialize descriptions from server
                const descriptions = {};
                data.images.forEach(img => {
                    if (img.imageDescription) {
                        descriptions[img.id] = img.imageDescription;
                    }
                });
                setImageDescriptions(descriptions);
            }

            // populate metadata from group
            setMetadata({
                year: data.year || new Date().getFullYear(),
                title: data.title || '',
                description: data.description || '',
                name: data.name || ''
            });
        } catch (e) {
            setError('Fehler beim Laden der Gruppe');
        } finally {
            setLoading(false);
        }
    }, [groupId]);

    const handleSave = async () => {
        if (!group) return;
        setSaving(true);
        try {
            // 1. Speichere Gruppen-Metadaten
            const payload = {
                title: metadata.title,
                description: metadata.description,
                year: metadata.year,
                name: metadata.name
            };

            const res = await fetch(`/groups/${groupId}`, {
                method: 'PATCH',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });

            if (!res.ok) {
                const body = await res.json().catch(() => ({}));
                throw new Error(body.message || 'Speichern der Metadaten fehlgeschlagen');
            }

            // 2. Speichere Bildbeschreibungen (falls vorhanden)
            if (Object.keys(imageDescriptions).length > 0) {
                const descriptions = Object.entries(imageDescriptions).map(([id, desc]) => ({
                    imageId: parseInt(id),
                    description: desc
                }));
                
                console.log('Speichere Beschreibungen:', descriptions);
                
                const descRes = await fetch(`/groups/${groupId}/images/batch-description`, {
                    method: 'PATCH',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ descriptions })
                });
                
                if (!descRes.ok) {
                    const body = await descRes.json().catch(() => ({}));
                    throw new Error(body.message || 'Speichern der Beschreibungen fehlgeschlagen');
                }
            }

            Swal.fire({ icon: 'success', title: 'Gruppe erfolgreich aktualisiert', timer: 1500, showConfirmButton: false });
            navigate('/moderation');
        } catch (e) {
            console.error(e);
            Swal.fire({ icon: 'error', title: 'Fehler beim Speichern', text: e.message });
        } finally {
            setSaving(false);
        }
    };

    const handleDeleteImage = async (imageId) => {
        if (!window.confirm('Bild wirklich löschen?')) return;
        try {
            const res = await fetch(`/groups/${groupId}/images/${imageId}`, { method: 'DELETE' });
            if (!res.ok) throw new Error('Löschen fehlgeschlagen');
            // Aktualisiere lokale Ansicht
            const newImages = group.images.filter(img => img.id !== imageId);
            setGroup({ ...group, images: newImages, imageCount: (group.imageCount || 0) - 1 });
            setSelectedImages(prev => prev.filter(img => img.id !== imageId));
            Swal.fire({ icon: 'success', title: 'Bild gelöscht', timer: 1200, showConfirmButton: false });
        } catch (e) {
            console.error(e);
            Swal.fire({ icon: 'error', title: 'Fehler beim Löschen des Bildes' });
        }
    };

    const handleRemoveImage = (indexToRemove) => {
        // If it's a remote image mapped with id, call delete
        const img = selectedImages[indexToRemove];
        if (img && img.id) {
            handleDeleteImage(img.id);
            return;
        }
        setSelectedImages(prev => prev.filter((_, index) => index !== indexToRemove));
    };

    // Handle drag-and-drop reordering
    const handleReorder = useCallback(async (reorderedItems) => {
        if (isReordering) return; // Prevent concurrent reordering

        try {
            setIsReordering(true);
            const imageIds = reorderedItems.map(img => img.id);
            
            // Update local state immediately (optimistic update)
            setSelectedImages(reorderedItems);
            
            // Also update group state to keep consistency
            if (group) {
                setGroup({ ...group, images: reorderedItems });
            }
            
            // Send API request
            await updateImageOrder(groupId, imageIds);
            
            // Show success feedback
            Swal.fire({
                icon: 'success',
                title: 'Reihenfolge gespeichert',
                timer: 1500,
                showConfirmButton: false,
                toast: true,
                position: 'top-end'
            });
            
        } catch (error) {
            console.error('❌ Fehler beim Neuordnen:', error);
            
            // Rollback on error - reload original order
            await loadGroup();
            
            Swal.fire({
                icon: 'error',
                title: 'Fehler beim Speichern',
                text: 'Reihenfolge konnte nicht gespeichert werden',
                timer: 3000,
                showConfirmButton: false
            });
        } finally {
            setIsReordering(false);
        }
    }, [groupId, group, isReordering, loadGroup]);

    // Handle edit mode toggle
    const handleEditMode = (enabled) => {
        console.log('🔄 Edit mode toggled:', enabled ? 'ENABLED' : 'DISABLED');
        setIsEditMode(enabled);
    };

    // Handle description changes
    const handleDescriptionChange = (imageId, description) => {
        console.log('✏️ Description changed for image', imageId, ':', description);
        setImageDescriptions(prev => {
            const newDescriptions = {
                ...prev,
                [imageId]: description.slice(0, 200) // Enforce max length
            };
            console.log('📝 Updated imageDescriptions:', newDescriptions);
            return newDescriptions;
        });
    };

    // Note: approve/delete group actions are intentionally removed from this page

    if (loading) return <div className="moderation-loading">Lade Gruppe...</div>;
    if (error) return <div className="moderation-error">{error}</div>;
    if (!group) return <div className="moderation-error">Gruppe nicht gefunden</div>;

    return (
      <div className="allContainer">
        <Navbar />

        <Container maxWidth="lg" className="page-container">
        <ImageGallery 
          items={selectedImages} 
          onDelete={handleRemoveImage}
          onReorder={handleReorder}
          enableReordering={true}
          isReordering={isReordering}
          mode="preview"
          showActions={true}
          isEditMode={isEditMode}
          onEditMode={handleEditMode}
          imageDescriptions={imageDescriptions}
          onDescriptionChange={handleDescriptionChange}
        />

          {selectedImages.length > 0 && (
            <>
              <DescriptionInput metadata={metadata} onMetadataChange={setMetadata} />

              <div className="action-buttons">
                <Button className="btn btn-secondary" onClick={() => navigate('/moderation')}>
                  ↩ Zurück
                </Button>
                <Button 
                  className="btn btn-success" 
                  onClick={handleSave} 
                  disabled={saving}
                  style={{ minWidth: '160px' }}
                >
                  {saving ? '⏳ Speichern...' : '💾 Speichern'}
                </Button>
              </div>
            </>
          )}

        </Container>

        <div className="footerContainer"><Footer /></div>
      </div>
    );

};

export default ModerationGroupImagesPage;
