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

interface NpcBannerManagementModalProps {
  isOpen: boolean;
  onClose: () => void;
  projectId: string;
  currentBannerUrl: string;
  onUpdate: () => void;
}

const NpcBannerManagementModal: React.FC<NpcBannerManagementModalProps> = ({
  isOpen,
  onClose,
  projectId,
  currentBannerUrl,
  onUpdate
}) => {
  const [bannerUrl, setBannerUrl] = useState(currentBannerUrl);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [previewLoading, setPreviewLoading] = useState(false);

  useEffect(() => {
    if (isOpen) {
      setBannerUrl(currentBannerUrl);
      setError(null);
    }
  }, [isOpen, currentBannerUrl]);

  const updateBanner = async () => {
    if (!bannerUrl.trim()) {
      setError('Banner-URL ist erforderlich');
      return;
    }

    try {
      setLoading(true);
      setError(null);

      const response = await fetch(`https://vollidioten.ceraticsoft.de/api/projects/${projectId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ bannerUrl: bannerUrl.trim() })
      });

      if (response.ok) {
        onUpdate();
        onClose();
      } else {
        const errorData = await response.json();
        setError(errorData.error || 'Fehler beim Aktualisieren des Banners');
      }
    } catch (err) {
      console.error('Error updating banner:', err);
      setError('Netzwerkfehler');
    } finally {
      setLoading(false);
    }
  };

  const handleImageLoad = () => {
    setPreviewLoading(false);
  };

  const handleImageError = () => {
    setPreviewLoading(false);
    setError('Bild konnte nicht geladen werden');
  };

  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-2xl 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" />
            NPC-Banner bearbeiten
          </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 Banner Preview */}
          <div className="mb-6">
            <h4 className="font-semibold text-textMain mb-3">Aktuelles Banner</h4>
            <div className="relative h-32 rounded-lg overflow-hidden border border-border bg-surfaceHighlight/30">
              {currentBannerUrl ? (
                <>
                  {previewLoading && (
                    <div className="absolute inset-0 flex items-center justify-center">
                      <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-accentInfo"></div>
                    </div>
                  )}
                  <img
                    src={currentBannerUrl}
                    alt="Current banner"
                    className="w-full h-full object-cover"
                    onLoad={handleImageLoad}
                    onError={handleImageError}
                  />
                </>
              ) : (
                <div className="w-full h-full flex items-center justify-center text-textMuted">
                  <Icons.Layers className="w-8 h-8" />
                </div>
              )}
            </div>
          </div>

          {/* Banner URL Input */}
          <div className="mb-6">
            <h4 className="font-semibold text-textMain mb-3">Neue Banner-URL</h4>
            <input
              type="url"
              value={bannerUrl}
              onChange={(e) => setBannerUrl(e.target.value)}
              placeholder="https://example.com/banner-image.jpg"
              className="w-full bg-[#0b0b0d] border border-border rounded p-3 text-sm"
            />
            <p className="text-xs text-textMuted mt-2">
              Geben Sie eine direkte URL zu einem Bild ein. Empfohlene Größe: 1200x400 Pixel oder größer.
            </p>
          </div>

          {/* File Upload */}
          <div className="mb-6">
            <h4 className="font-semibold text-textMain mb-3">Oder Bild hochladen</h4>
            <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={async (e) => {
                  const file = e.target.files?.[0];
                  if (!file) return;

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

                  try {
                    setLoading(true);
                    setError(null);

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

                    if (response.ok) {
                      const data = await response.json();
                      setBannerUrl(data.bannerUrl);
                      onUpdate();
                      onClose();
                    } else {
                      const errorData = await response.json();
                      setError(errorData.error || 'Fehler beim Hochladen');
                    }
                  } catch (err) {
                    console.error('Error uploading banner:', err);
                    setError('Netzwerkfehler beim Hochladen');
                  } finally {
                    setLoading(false);
                  }
                }}
                className="hidden"
                id="npc-banner-upload"
              />
              <label htmlFor="npc-banner-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">Bild auswählen</p>
                <p className="text-xs text-textMuted mt-1">Max. 10MB, nur Bilddateien</p>
              </label>
            </div>
          </div>

          {/* Preview */}
          {bannerUrl && bannerUrl !== currentBannerUrl && (
            <div className="mb-6">
              <h4 className="font-semibold text-textMain mb-3">Vorschau</h4>
              <div className="relative h-32 rounded-lg overflow-hidden border border-border bg-surfaceHighlight/30">
                <img
                  src={bannerUrl}
                  alt="Banner preview"
                  className="w-full h-full object-cover"
                  onError={() => setError('Vorschau-Bild konnte nicht geladen werden')}
                />
              </div>
            </div>
          )}

          {/* Common Banner Suggestions */}
          <div className="mb-6">
            <h4 className="font-semibold text-textMain mb-3">Beispiele</h4>
            <div className="grid grid-cols-2 gap-2 text-xs">
              <button
                onClick={() => setBannerUrl('https://images.unsplash.com/photo-1449824913935-59a10b8d2000?q=80&w=1200&auto=format&fit=crop')}
                className="p-2 bg-surfaceHighlight/50 rounded hover:bg-surfaceHighlight transition-colors text-left"
              >
                <div className="font-medium">Berglandschaft</div>
                <div className="text-textMuted truncate">Unsplash</div>
              </button>
              <button
                onClick={() => setBannerUrl('https://images.unsplash.com/photo-1506905925346-21bda4d32df4?q=80&w=1200&auto=format&fit=crop')}
                className="p-2 bg-surfaceHighlight/50 rounded hover:bg-surfaceHighlight transition-colors text-left"
              >
                <div className="font-medium">Stadt bei Nacht</div>
                <div className="text-textMuted truncate">Unsplash</div>
              </button>
              <button
                onClick={() => setBannerUrl('https://images.unsplash.com/photo-1542601906990-b4d3fb778b09?q=80&w=1200&auto=format&fit=crop')}
                className="p-2 bg-surfaceHighlight/50 rounded hover:bg-surfaceHighlight transition-colors text-left"
              >
                <div className="font-medium">Architektur</div>
                <div className="text-textMuted truncate">Unsplash</div>
              </button>
              <button
                onClick={() => setBannerUrl('https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?q=80&w=1200&auto=format&fit=crop')}
                className="p-2 bg-surfaceHighlight/50 rounded hover:bg-surfaceHighlight transition-colors text-left"
              >
                <div className="font-medium">Abstrakt</div>
                <div className="text-textMuted truncate">Unsplash</div>
              </button>
            </div>
          </div>

          {/* Info */}
          <div className="bg-blue-500/10 border border-blue-500/20 rounded-lg p-4">
            <div className="flex items-start gap-3">
              <Icons.Terminal className="w-5 h-5 text-blue-400 mt-0.5" />
              <div>
                <h4 className="text-sm font-medium text-blue-400 mb-1">Banner-Empfehlungen</h4>
                <ul className="text-xs text-blue-300 space-y-1">
                  <li>• Verwenden Sie hochwertige Bilder mit 16:9 Seitenverhältnis</li>
                  <li>• Stellen Sie sicher, dass die Bilder öffentlich zugänglich sind</li>
                  <li>• Dunklere Bilder funktionieren oft besser mit dem Text-Overlay</li>
                </ul>
              </div>
            </div>
          </div>
        </div>

        <div className="p-4 border-t border-border flex justify-end gap-3">
          <button
            onClick={onClose}
            className="px-4 py-2 text-sm font-medium text-textMuted hover:text-white transition-colors"
          >
            Abbrechen
          </button>
          <button
            onClick={updateBanner}
            disabled={loading || !bannerUrl.trim() || bannerUrl === currentBannerUrl}
            className="px-6 py-2 text-sm font-medium bg-orange-500 hover:bg-orange-600 disabled:opacity-50 disabled:cursor-not-allowed text-white rounded transition-colors flex items-center gap-2"
          >
            {loading ? (
              <>
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                Aktualisiere...
              </>
            ) : (
              <>
                <Icons.Layers className="w-4 h-4" />
                Banner aktualisieren
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  );
};

export default NpcBannerManagementModal;
