import React, { useState, useEffect } from 'react';
import { Card, CardContent, Typography, Container, Box } from '@mui/material';

// Components
import Navbar from '../ComponentUtils/Headers/Navbar';
import Footer from '../ComponentUtils/Footer';
import MultiImageDropzone from '../ComponentUtils/MultiUpload/MultiImageDropzone';
import ImageGallery from '../ComponentUtils/ImageGallery';
import GroupMetadataEditor from '../ComponentUtils/GroupMetadataEditor';
import ConsentManager from '../ComponentUtils/ConsentManager';
import UploadProgress from '../ComponentUtils/MultiUpload/UploadProgress';
import Loading from '../ComponentUtils/LoadingAnimation/Loading';

// Utils
import { uploadImageBatch } from '../../Utils/batchUpload';

// Styles
import '../../App.css';

function MultiUploadPage() {
  const [selectedImages, setSelectedImages] = useState([]);
  const [metadata, setMetadata] = useState({
    year: new Date().getFullYear(),
    title: '',
    description: '',
    name: ''
  });
  const [consents, setConsents] = useState({
    workshopConsent: false,
    socialMediaConsents: []
  });
  const [uploading, setUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [uploadComplete, setUploadComplete] = useState(false);
  const [uploadResult, setUploadResult] = useState(null);
  const [isEditMode, setIsEditMode] = useState(false);
  const [imageDescriptions, setImageDescriptions] = useState({});

  // Cleanup object URLs when component unmounts
  useEffect(() => {
    return () => {
      selectedImages.forEach(img => {
        if (img.url && img.url.startsWith('blob:')) {
          URL.revokeObjectURL(img.url);
        }
      });
    };
  }, [selectedImages]);

  const handleImagesSelected = (newImages) => {
    // Convert File objects to preview objects with URLs
    const imageObjects = newImages.map((file, index) => ({
      id: `preview-${Date.now()}-${index}`,
      file: file,
      url: URL.createObjectURL(file),
      name: file.name,
      originalName: file.name,
      size: file.size,
      type: file.type
    }));
    
    setSelectedImages(prev => [...prev, ...imageObjects]);
  };

  const handleRemoveImage = (indexToRemove) => {
    setSelectedImages(prev => {
      const imageToRemove = prev[indexToRemove];
      if (imageToRemove && imageToRemove.url && imageToRemove.url.startsWith('blob:')) {
        URL.revokeObjectURL(imageToRemove.url);
      }
      return prev.filter((_, index) => index !== indexToRemove);
    });
  };

  const handleClearAll = () => {
    selectedImages.forEach(img => {
      if (img.url && img.url.startsWith('blob:')) {
        URL.revokeObjectURL(img.url);
      }
    });
    
    setSelectedImages([]);
    setMetadata({
      year: new Date().getFullYear(),
      title: '',
      description: '',
      name: ''
    });
    setConsents({
      workshopConsent: false,
      socialMediaConsents: []
    });
    setImageDescriptions({});
    setIsEditMode(false);
  };

  const handleReorder = (reorderedItems) => {
    setSelectedImages(reorderedItems);
  };

  const handleEditMode = (enabled) => {
    setIsEditMode(enabled);
  };

  const handleDescriptionChange = (imageId, description) => {
    setImageDescriptions(prev => ({
      ...prev,
      [imageId]: description.slice(0, 200)
    }));
  };

  const handleUpload = async () => {
    if (selectedImages.length === 0) return;

    if (!metadata.year || !metadata.title.trim()) return;

    if (!consents.workshopConsent) return;

    setUploading(true);
    setUploadProgress(0);

    try {
      const filesToUpload = selectedImages.map(img => img.file).filter(Boolean);
      
      if (filesToUpload.length === 0) {
        throw new Error('Keine gültigen Bilder zum Upload');
      }

      // Map preview IDs to actual file names for backend
      const descriptionsForUpload = {};
      selectedImages.forEach(img => {
        if (imageDescriptions[img.id]) {
          descriptionsForUpload[img.originalName] = imageDescriptions[img.id];
        }
      });

      const result = await uploadImageBatch({
        images: filesToUpload,
        metadata,
        imageDescriptions: descriptionsForUpload,
        consents,
        onProgress: setUploadProgress
      });

      setUploadComplete(true);
      setUploadResult(result);

    } catch (error) {
      console.error('Upload error:', error);
      setUploading(false);
      setUploadComplete(false);
    }
  };

  const canUpload = () => {
    return selectedImages.length > 0 && 
           metadata.year && 
           metadata.title.trim() && 
           consents.workshopConsent;
  };

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

      <Container maxWidth="lg" sx={{ pt: '20px', pb: '40px', minHeight: '80vh' }}>
        <Card sx={{ borderRadius: '12px', boxShadow: '0 4px 12px rgba(0,0,0,0.1)', p: '20px', mb: '20px' }}>
          <CardContent>
            <Typography sx={{ fontFamily: 'roboto', fontWeight: 400, fontSize: '28px', textAlign: 'center', mb: '10px', color: '#333333' }}>
              Project Image Uploader
            </Typography>
            <Typography sx={{ fontFamily: 'roboto', fontWeight: 300, fontSize: '16px', color: '#666666', textAlign: 'center', mb: '30px' }}>
              Lade ein oder mehrere Bilder von deinem Projekt hoch und beschreibe dein Projekt in wenigen Worten.
              <br />
              Die Bilder werden nur hier im Hobbyhimmel auf dem Monitor gezeigt, es wird an keine Dritten weiter gegeben.
            </Typography>

            {!uploading ? (
              <>
                {/* Image Dropzone - stays inline as it's upload-specific */}
                <MultiImageDropzone 
                  onImagesSelected={handleImagesSelected}
                  selectedImages={selectedImages}
                />

                {/* Image Gallery with descriptions */}
                {selectedImages.length > 0 && (
                  <ImageGallery 
                    items={selectedImages}
                    onDelete={handleRemoveImage}
                    mode="preview"
                    showActions={true}
                    enableReordering={true}
                    onReorder={handleReorder}
                    isEditMode={isEditMode}
                    onEditMode={handleEditMode}
                    imageDescriptions={imageDescriptions}
                    onDescriptionChange={handleDescriptionChange}
                  />
                )}

                {selectedImages.length > 0 && (
                  <>
                    {/* Modular Components like ManagementPortalPage */}
                    <GroupMetadataEditor
                      metadata={metadata}
                      onMetadataChange={setMetadata}
                      mode="upload"
                    />

                    <ConsentManager
                      consents={consents}
                      onConsentsChange={setConsents}
                      mode="upload"
                    />

                    {/* Action Buttons */}
                    <Box sx={{ display: 'flex', gap: 1, justifyContent: 'center', mt: 3, flexWrap: 'wrap' }}>
                      <button
                        className="btn btn-success"
                        onClick={handleUpload}
                        disabled={!canUpload()}
                        style={{ 
                          fontSize: '16px',
                          padding: '12px 30px'
                        }}
                      >
                        🚀 {selectedImages.length} Bild{selectedImages.length !== 1 ? 'er' : ''} hochladen
                      </button>

                      <button
                        className="btn btn-secondary"
                        onClick={handleClearAll}
                        style={{ 
                          fontSize: '16px',
                          padding: '12px 30px'
                        }}
                      >
                        🗑️ Alle entfernen
                      </button>
                    </Box>
                  </>
                )}
              </>
            ) : (
              <div style={{ textAlign: 'center', padding: '40px 0' }}>
                {!uploadComplete ? (
                  <>
                    <Loading />
                    <UploadProgress 
                      progress={uploadProgress}
                      totalFiles={selectedImages.length}
                      isUploading={uploading}
                    />
                  </>
                ) : (
                  <Box sx={{
                    mt: 4,
                    p: 3,
                    borderRadius: '12px',
                    background: 'linear-gradient(135deg, #4CAF50 0%, #45a049 100%)',
                    color: 'white',
                    boxShadow: '0 4px 20px rgba(76, 175, 80, 0.4)',
                    animation: 'slideIn 0.5s ease-out',
                    '@keyframes slideIn': {
                      from: {
                        opacity: 0,
                        transform: 'translateY(-20px)'
                      },
                      to: {
                        opacity: 1,
                        transform: 'translateY(0)'
                      }
                    }
                  }}>
                    <Typography sx={{ fontSize: '28px', fontWeight: 'bold', mb: 1 }}>
                      ✅ Upload erfolgreich!
                    </Typography>
                    <Typography sx={{ fontSize: '18px', mb: 2 }}>
                      {uploadResult?.imageCount || 0} Bild{uploadResult?.imageCount === 1 ? '' : 'er'} {uploadResult?.imageCount === 1 ? 'wurde' : 'wurden'} hochgeladen.
                    </Typography>
                    
                    <Box sx={{ bgcolor: 'rgba(255,255,255,0.2)', borderRadius: '8px', p: 2, mb: 2 }}>
                      <Typography sx={{ fontSize: '14px', mb: 1 }}>
                        Ihre Referenz-Nummer:
                      </Typography>
                      <Typography sx={{ fontSize: '20px', fontFamily: 'monospace', fontWeight: 'bold', mb: 1 }}>
                        {uploadResult?.groupId}
                      </Typography>
                      <Typography sx={{ fontSize: '12px', opacity: 0.9 }}>
                        Notieren Sie sich diese Nummer für spätere Anfragen an das Team.
                      </Typography>
                    </Box>

                    {uploadResult?.managementToken && (
                      <Box sx={{ 
                        bgcolor: 'rgba(255,255,255,0.95)', 
                        borderRadius: '8px', 
                        p: 2.5, 
                        mb: 2,
                        border: '2px solid rgba(255,255,255,0.3)'
                      }}>
                        <Typography sx={{ fontSize: '16px', fontWeight: 'bold', mb: 1.5, color: '#2e7d32' }}>
                          🔗 Verwaltungslink für Ihren Upload
                        </Typography>
                        <Typography sx={{ fontSize: '13px', mb: 1.5, color: '#333' }}>
                          Mit diesem Link können Sie später Ihre Bilder verwalten, Einwilligungen widerrufen oder die Gruppe löschen:
                        </Typography>
                        
                        <Box sx={{ 
                          bgcolor: '#f5f5f5', 
                          p: 1.5, 
                          borderRadius: '6px', 
                          mb: 1.5,
                          display: 'flex',
                          alignItems: 'center',
                          gap: 1,
                          flexWrap: 'wrap'
                        }}>
                          <Typography sx={{ 
                            fontSize: '13px', 
                            fontFamily: 'monospace',
                            color: '#1976d2',
                            wordBreak: 'break-all',
                            flex: 1,
                            minWidth: '200px'
                          }}>
                            {window.location.origin}/manage/{uploadResult.managementToken}
                          </Typography>
                          <button
                            className="btn btn-secondary"
                            style={{
                              fontSize: '12px',
                              padding: '6px 16px'
                            }}
                            onClick={() => {
                              const link = `${window.location.origin}/manage/${uploadResult.managementToken}`;
                              navigator.clipboard.writeText(link);
                            }}
                          >
                            📋 Kopieren
                          </button>
                        </Box>
                        
                        <Typography sx={{ fontSize: '11px', color: '#666', mb: 0.5 }}>
                          ⚠️ <strong>Wichtig:</strong> Bewahren Sie diesen Link sicher auf! Jeder mit diesem Link kann Ihren Upload verwalten.
                        </Typography>
                        <Typography sx={{ fontSize: '11px', color: '#666', fontStyle: 'italic' }}>
                          ℹ️ <strong>Hinweis:</strong> Über diesen Link können Sie nur die Bilder in der Werkstatt verwalten. Bereits auf Social Media Plattformen veröffentlichte Bilder müssen separat dort gelöscht werden.
                        </Typography>
                      </Box>
                    )}

                    <Typography sx={{ fontSize: '13px', mb: 2, opacity: 0.95 }}>
                      Die Bilder werden geprüft und nach Freigabe auf dem Werkstatt-Monitor angezeigt.
                      {' '}Bei Social Media Einwilligung werden sie entsprechend veröffentlicht.
                    </Typography>

                    <Typography sx={{ fontSize: '12px', mb: 3, opacity: 0.9 }}>
                      <strong>Fragen oder Widerruf?</strong> Kontakt: <strong>it@hobbyhimmel.de</strong>
                    </Typography>

                    <button
                      className="btn btn-success"
                      style={{
                        fontSize: '16px',
                        padding: '12px 30px'
                      }}
                      onClick={() => window.location.reload()}
                    >
                      👍 Weitere Bilder hochladen
                    </button>
                  </Box>
                )}
              </div>
            )}
          </CardContent>
        </Card>
      </Container>

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

export default MultiUploadPage;
