import React, { useState, useEffect } from 'react';

// Components
import NavbarUpload from '../ComponentUtils/Headers/NavbarUpload';
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">
      {<NavbarUpload />}

      <div className="container">
        <div className="card">
          <div className="card-content">
            <h1 className="page-title">
              Project Image Uploader
            </h1>
            <p className="page-subtitle">
              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.
            </p>

            {!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 */}
                    <div className="flex-center">
                      <button
                        className="btn btn-success"
                        onClick={handleUpload}
                        disabled={!canUpload()}
                      >
                        🚀 {selectedImages.length} Bild{selectedImages.length !== 1 ? 'er' : ''} hochladen
                      </button>

                      <button
                        className="btn btn-secondary"
                        onClick={handleClearAll}
                      >
                        🗑️ Alle entfernen
                      </button>
                    </div>
                  </>
                )}
              </>
            ) : (
              <div style={{ textAlign: 'center', padding: '40px 0' }}>
                {!uploadComplete ? (
                  <>
                    <Loading />
                    <UploadProgress 
                      progress={uploadProgress}
                      totalFiles={selectedImages.length}
                      isUploading={uploading}
                    />
                  </>
                ) : (
                  <div className="success-box">
                    <h2>
                      ✅ Upload erfolgreich!
                    </h2>
                    <p>
                      {uploadResult?.imageCount || 0} Bild{uploadResult?.imageCount === 1 ? '' : 'er'} {uploadResult?.imageCount === 1 ? 'wurde' : 'wurden'} hochgeladen.
                    </p>
                    
                    <div className="info-box">
                      <p className="text-small">
                        Ihre Referenz-Nummer:
                      </p>
                      <p style={{ fontSize: '20px', fontFamily: 'monospace', fontWeight: 'bold', marginBottom: '8px' }}>
                        {uploadResult?.groupId}
                      </p>
                      <p className="text-small" style={{ opacity: 0.9 }}>
                        Notieren Sie sich diese Nummer für spätere Anfragen an das Team.
                      </p>
                    </div>

                    {uploadResult?.managementToken && (
                      <div className="info-box-highlight">
                        <h3 style={{ fontSize: '16px', fontWeight: 'bold', marginBottom: '12px', color: '#2e7d32' }}>
                          🔗 Verwaltungslink für Ihren Upload
                        </h3>
                        <p style={{ fontSize: '13px', marginBottom: '12px', color: '#333' }}>
                          Mit diesem Link können Sie später Ihre Bilder verwalten, Einwilligungen widerrufen oder die Gruppe löschen:
                        </p>
                        
                        <div style={{ 
                          background: '#f5f5f5', 
                          padding: '12px', 
                          borderRadius: '6px', 
                          marginBottom: '12px',
                          display: 'flex',
                          alignItems: 'center',
                          gap: '8px',
                          flexWrap: 'wrap'
                        }}>
                          <p style={{ 
                            fontSize: '13px', 
                            fontFamily: 'monospace',
                            color: '#1976d2',
                            wordBreak: 'break-all',
                            flex: 1,
                            minWidth: '200px',
                            margin: 0
                          }}>
                            {window.location.origin}/manage/{uploadResult.managementToken}
                          </p>
                          <button
                            className="btn btn-secondary"
                            onClick={() => {
                              const link = `${window.location.origin}/manage/${uploadResult.managementToken}`;
                              // Fallback für HTTP (wenn navigator.clipboard nicht verfügbar)
                              if (navigator.clipboard && navigator.clipboard.writeText) {
                                navigator.clipboard.writeText(link);
                              } else {
                                // Fallback: Erstelle temporäres Input-Element
                                const input = document.createElement('input');
                                input.value = link;
                                document.body.appendChild(input);
                                input.select();
                                document.execCommand('copy');
                                document.body.removeChild(input);
                              }
                            }}
                          >
                            📋 Kopieren
                          </button>
                        </div>
                        
                        <p className="text-small" style={{ color: '#666', marginBottom: '4px' }}>
                          ⚠️ <strong>Wichtig:</strong> Bewahre diesen Link sicher auf! Jeder mit diesem Link kann Deinen Upload verwalten.
                        </p>
                        <p className="text-small" style={{ color: '#666', fontStyle: 'italic' }}>
                          ℹ️ <strong>Hinweis:</strong> Über diesen Link kannst Du nur die Bilder in der Werkstatt verwalten. Bereits auf Social Media Plattformen veröffentlichte Bilder müssen separat dort gelöscht werden.
                        </p>
                      </div>
                    )}

                    <p style={{ fontSize: '13px', marginBottom: '16px', 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.
                    </p>

                    <p style={{ fontSize: '12px', marginBottom: '24px', opacity: 0.9 }}>
                      <strong>Fragen oder Widerruf?</strong> Kontakt: <strong>it@hobbyhimmel.de</strong>
                    </p>

                    <button
                      className="btn btn-success"
                      onClick={() => window.location.reload()}
                    >
                      👍 Weitere Bilder hochladen
                    </button>
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      </div>

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

export default MultiUploadPage;
