import React, { useState } from 'react';
import { Icons } from './IconSet';

interface LogoManagementModalProps {
  isOpen: boolean;
  onClose: () => void;
  projectId: string;
  currentLogoUrl?: string;
  onUpdate: () => void;
}

const LogoManagementModal: React.FC<LogoManagementModalProps> = ({
  isOpen,
  onClose,
  projectId,
  currentLogoUrl,
  onUpdate
}) => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleFileUpload = async (file: File) => {
    try {
      setLoading(true);
      setError(null);

      const formData = new FormData();
      formData.append('logo', file);

      const response = await fetch(`https://vollidioten.ceraticsoft.de/api/projects/${projectId}/logo/upload`, {
        method: 'POST',
        credentials: 'include',
        body: formData
      });

      if (response.ok) {
        const data = await response.json();
        console.log('Logo uploaded successfully:', data);
        onUpdate();
        onClose();
      } else {
        const errorData = await response.json();
        setError(errorData.error || 'Fehler beim Hochladen des Logos');
      }
    } catch (err) {
      console.error('Error uploading logo:', err);
      setError('Netzwerkfehler beim Hochladen');
    } finally {
      setLoading(false);
    }
  };

  const removeLogo = async () => {
    // Note: We'll need to implement logo deletion in the backend
    // For now, this is a placeholder
    alert('Logo-Löschen ist noch nicht implementiert. Kontaktieren Sie einen Administrator.');
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm animate-in fade-in duration-200">
      <div className="bg-surface border border-border rounded-xl w-full max-w-md shadow-2xl flex flex-col max-h-[90vh]">
        <div className="p-4 border-b border-border flex justify-between items-center bg-surfaceHighlight/20">
          <h3 className="font-bold text-textMain flex items-center gap-2">
            <Icons.Layers className="w-5 h-5" />
            Logo verwalten
          </h3>
          <button onClick={onClose} className="text-textMuted hover:text-white transition-colors text-xl leading-none">&times;</button>
        </div>

        <div className="p-6 flex-1 overflow-y-auto">
          {error && (
            <div className="bg-red-500/10 border border-red-500/20 rounded-lg p-4 mb-6">
              <p className="text-red-400">{error}</p>
            </div>
          )}

          {/* Current Logo Preview */}
          {currentLogoUrl && (
            <div className="mb-6">
              <h4 className="text-sm font-semibold text-textMain mb-3">Aktuelles Logo</h4>
              <div className="flex items-center gap-4 p-4 bg-surfaceHighlight/30 border border-border rounded-lg">
                <img
                  src={currentLogoUrl}
                  alt="Aktuelles Logo"
                  className="w-16 h-16 rounded-lg object-cover border border-white/10"
                />
                <div className="flex-1">
                  <p className="text-sm text-textMuted">Logo ist gesetzt</p>
                  <button
                    onClick={removeLogo}
                    className="text-xs text-red-400 hover:text-red-300 mt-1"
                    disabled={loading}
                  >
                    Logo entfernen
                  </button>
                </div>
              </div>
            </div>
          )}

          {/* File Upload */}
          <div className="border-2 border-dashed border-border rounded-lg p-6 text-center hover:border-accentInfo/50 transition-colors">
            <input
              type="file"
              accept="image/*"
              onChange={(e) => {
                const file = e.target.files?.[0];
                if (file) {
                  handleFileUpload(file);
                }
              }}
              className="hidden"
              id="logo-upload"
              disabled={loading}
            />
            <label htmlFor="logo-upload" className="cursor-pointer">
              <div className="w-12 h-12 mx-auto mb-4 bg-surfaceHighlight rounded-full flex items-center justify-center">
                <svg className="w-6 h-6 text-accentInfo" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
                </svg>
              </div>
              <p className="text-sm text-textMain font-medium">
                {loading ? 'Lädt hoch...' : 'Logo auswählen'}
              </p>
              <p className="text-xs text-textMuted mt-2">
                PNG, JPG oder GIF • Max. 2MB • Quadratische Formate bevorzugt
              </p>
            </label>
          </div>

          <div className="mt-4 text-xs text-textMuted">
            <p>• Das Logo wird in der Projektübersicht angezeigt</p>
            <p>• Verwenden Sie transparente Hintergründe für beste Ergebnisse</p>
            <p>• Das Logo wird automatisch auf 64x64px skaliert</p>
          </div>
        </div>

        <div className="p-4 border-t border-border flex justify-end">
          <button
            onClick={onClose}
            className="px-4 py-2 text-sm font-medium text-textMuted hover:text-white transition-colors"
          >
            Schließen
          </button>
        </div>
      </div>
    </div>
  );
};

export default LogoManagementModal;
