import React, { useState, useEffect, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Container, Box } from '@mui/material';

// Services
import { adminGet } from '../../services/adminApi';
import { handleAdminError } from '../../services/adminErrorHandler';
import AdminSessionGate from '../AdminAuth/AdminSessionGate.jsx';
import { useAdminSession } from '../../contexts/AdminSessionContext.jsx';

// Components
import Navbar from '../ComponentUtils/Headers/Navbar';
import Footer from '../ComponentUtils/Footer';
import ImageDescriptionManager from '../ComponentUtils/ImageDescriptionManager';
import GroupMetadataEditor from '../ComponentUtils/GroupMetadataEditor';
import Loading from '../ComponentUtils/LoadingAnimation/Loading';

/**
 * ModerationGroupImagesPage - Admin page for moderating group images
 * 
 * Uses modular components:
 * - ImageDescriptionManager: Edit image descriptions with batch save
 * - GroupMetadataEditor: Edit group metadata with save/discard
 */
const ModerationGroupImagesPage = () => {
    const { groupId } = useParams();
    const navigate = useNavigate();
    const [group, setGroup] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
  const { isAuthenticated } = useAdminSession();

  const loadGroup = useCallback(async () => {
    if (!isAuthenticated) {
      return;
    }
        try {
            setLoading(true);
            const data = await adminGet(`/api/admin/groups/${groupId}`);
            
            // Transform data similar to ManagementPortalPage
            const transformedData = {
                ...data,
                metadata: {
                    year: data.year || new Date().getFullYear(),
                    title: data.title || '',
                    description: data.description || '',
                    name: data.name || ''
                },
                images: (data.images || []).map(img => ({
                    ...img,
                    remoteUrl: `/download/${img.fileName}`,
                    originalName: img.originalName || img.fileName,
                    id: img.id,
                    imageDescription: img.imageDescription || ''
                }))
            };
            
            setGroup(transformedData);
        } catch (e) {
            await handleAdminError(e, 'Gruppe laden');
            setError('Fehler beim Laden der Gruppe');
        } finally {
            setLoading(false);
        }
    }, [groupId, isAuthenticated]);

    useEffect(() => {
        if (!isAuthenticated) {
            return;
        }
        loadGroup();
    }, [isAuthenticated, loadGroup]);

    const renderContent = () => {
        if (loading) return <Loading />;
        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" sx={{ pt: '20px', pb: '40px', minHeight: '80vh' }}>
                    {/* Image Descriptions Manager */}
                    <ImageDescriptionManager
                        images={group.images}
                        groupId={groupId}
                        onRefresh={loadGroup}
                        mode="moderate"
                    />

                    {/* Group Metadata Editor */}
                    <GroupMetadataEditor
                        initialMetadata={group.metadata}
                        groupId={groupId}
                        onRefresh={loadGroup}
                        mode="moderate"
                    />

                    {/* Back Button */}
                    <Box sx={{ display: 'flex', justifyContent: 'center', mt: 3 }}>
                        <button
                            className="btn btn-secondary"
                            onClick={() => navigate('/moderation')}
                        >
                            ↩ Zurück zur Übersicht
                        </button>
                    </Box>
                </Container>

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

    return (
        <AdminSessionGate>
            {renderContent()}
        </AdminSessionGate>
    );
};

export default ModerationGroupImagesPage;
