import React, { useState } from 'react';
import { Box, Typography, Paper } from '@mui/material';
import Swal from 'sweetalert2';
import DescriptionInput from './MultiUpload/DescriptionInput';
import { adminRequest } from '../../services/adminApi';
import { handleAdminError } from '../../services/adminErrorHandler';

/**
 * Manages group metadata with save functionality
 * Wraps DescriptionInput and provides save for title, description, name, year
 * 
 * @param mode - 'edit' (default) shows save/discard, 'upload' hides them, 'moderate' uses different API
 */
function GroupMetadataEditor({ 
  initialMetadata,
  metadata: externalMetadata,
  onMetadataChange,
  token,
  groupId,
  onRefresh,
  mode = 'edit'
}) {
  const [metadata, setMetadata] = useState(initialMetadata || {
    year: new Date().getFullYear(),
    title: '',
    description: '',
    name: ''
  });
  const [originalMetadata, setOriginalMetadata] = useState(initialMetadata || {
    year: new Date().getFullYear(),
    title: '',
    description: '',
    name: ''
  });
  const [saving, setSaving] = useState(false);

  // In upload mode: use external state
  const isUploadMode = mode === 'upload';
  const isModerateMode = mode === 'moderate';
  const currentMetadata = isUploadMode ? externalMetadata : metadata;
  const setCurrentMetadata = isUploadMode ? onMetadataChange : setMetadata;

  // Update when initialMetadata changes (edit mode only)
  React.useEffect(() => {
    if (initialMetadata && !isUploadMode) {
      setMetadata(initialMetadata);
      setOriginalMetadata(initialMetadata);
    }
  }, [initialMetadata, isUploadMode]);

  const hasChanges = () => {
    if (isUploadMode) return false; // No changes tracking in upload mode
    return JSON.stringify(metadata) !== JSON.stringify(originalMetadata);
  };

  const handleSave = async () => {
    if (!hasChanges()) {
      Swal.fire({
        icon: 'info',
        title: 'Keine Änderungen',
        text: 'Es wurden keine Änderungen an den Metadaten vorgenommen.'
      });
      return;
    }

    try {
      setSaving(true);

      // Different API endpoints for manage vs moderate
      const endpoint = isModerateMode
        ? `/api/admin/groups/${groupId}`
        : `/api/manage/${token}/metadata`;
      
      const method = isModerateMode ? 'PATCH' : 'PUT';

      if (isModerateMode) {
        await adminRequest(endpoint, method, metadata);
      } else {
        const res = await fetch(endpoint, {
          method: method,
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(metadata)
        });

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

      await Swal.fire({
        icon: 'success',
        title: 'Gespeichert',
        text: 'Metadaten wurden erfolgreich aktualisiert. Gruppe wird erneut moderiert.',
        timer: 2000,
        showConfirmButton: false
      });

      // Update original metadata
      setOriginalMetadata(metadata);

      // Refresh data if callback provided
      if (onRefresh) {
        await onRefresh();
      }

    } catch (error) {
      console.error('Error saving metadata:', error);
      
      if (isModerateMode) {
        handleAdminError(error, 'Metadaten speichern');
      } else {
        Swal.fire({
          icon: 'error',
          title: 'Fehler',
          text: error.message || 'Metadaten konnten nicht gespeichert werden'
        });
      }
    } finally {
      setSaving(false);
    }
  };

  const handleDiscard = () => {
    setMetadata(originalMetadata);
    Swal.fire({
      icon: 'info',
      title: 'Verworfen',
      text: 'Änderungen wurden zurückgesetzt.',
      timer: 1500,
      showConfirmButton: false
    });
  };

  return (
    <Paper 
      sx={{ 
        p: 3, 
        borderRadius: '12px', 
        boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
        border: '2px solid #e0e0e0'
      }}
    >
      {/* Component Header */}
      <Typography variant="h6" gutterBottom sx={{ fontWeight: 600, mb: 2 }}>
        📝 Projekt-Informationen
      </Typography>

      <DescriptionInput 
        metadata={currentMetadata}
        onMetadataChange={setCurrentMetadata}
      />

      {!isUploadMode && hasChanges() && (
        <Box sx={{ mt: 2, display: 'flex', gap: 1, justifyContent: 'center' }}>
          <button
            className="btn btn-success"
            onClick={handleSave}
            disabled={saving}
          >
            {saving ? '⏳ Speichern...' : '💾 Informationen speichern'}
          </button>
          
          <button
            className="btn btn-secondary"
            onClick={handleDiscard}
            disabled={saving}
          >
            ↩ Verwerfen
          </button>
        </Box>
      )}
    </Paper>
  );
}

export default GroupMetadataEditor;
