import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { X } from 'lucide-react';

interface ConsentState {
  necessary: boolean;
  analytics: boolean;
  advertising: boolean;
}

export default function CookieConsent() {
  const [showBanner, setShowBanner] = useState(false);
  const [showDetails, setShowDetails] = useState(false);
  const [consent, setConsent] = useState<ConsentState>({
    necessary: true,
    analytics: false,
    advertising: false
  });

  useEffect(() => {
    // Check if user has already given consent
    const savedConsent = localStorage.getItem('cookie_consent');
    if (savedConsent) {
      try {
        const parsedConsent = JSON.parse(savedConsent);
        setConsent(parsedConsent);
        updateGoogleConsent(parsedConsent);
        setShowBanner(false); // Don't show banner if consent already exists
      } catch (error) {
        // If parsing fails, show banner
        setShowBanner(true);
      }
    } else {
      // No saved consent, show banner
      setShowBanner(true);
    }
  }, []);

  const updateGoogleConsent = (consentState: ConsentState) => {
    if (window.gtag) {
      window.gtag('consent', 'update', {
        'ad_storage': consentState.advertising ? 'granted' : 'denied',
        'analytics_storage': consentState.analytics ? 'granted' : 'denied',
        'ad_user_data': consentState.advertising ? 'granted' : 'denied',
        'ad_personalization': consentState.advertising ? 'granted' : 'denied'
      });
    }
  };

  const handleAcceptAll = () => {
    const newConsent = {
      necessary: true,
      analytics: true,
      advertising: true
    };
    
    setConsent(newConsent);
    updateGoogleConsent(newConsent);
    localStorage.setItem('cookie_consent', JSON.stringify(newConsent));
    setShowBanner(false);
    setShowDetails(false);
  };

  const handleRejectAll = () => {
    const newConsent = {
      necessary: true,
      analytics: false,
      advertising: false
    };
    
    setConsent(newConsent);
    updateGoogleConsent(newConsent);
    localStorage.setItem('cookie_consent', JSON.stringify(newConsent));
    setShowBanner(false);
    setShowDetails(false);
  };

  const handleSavePreferences = () => {
    updateGoogleConsent(consent);
    localStorage.setItem('cookie_consent', JSON.stringify(consent));
    setShowBanner(false);
    setShowDetails(false);
  };

  const handleConsentChange = (key: keyof ConsentState, value: boolean) => {
    if (key === 'necessary') return; // Cannot disable necessary cookies
    setConsent(prev => ({ ...prev, [key]: value }));
  };

  if (!showBanner) return null;

  return (
    <div className="fixed inset-0 z-[9999] flex items-end justify-center p-4 pointer-events-none">
      <div className="w-full max-w-4xl pointer-events-auto">
        <div className="bg-bunny-dark/95 backdrop-blur-sm border border-white/20 rounded-lg shadow-2xl" translate="no">
          {!showDetails ? (
            // Simple banner
            <div className="p-6">
              <div className="flex items-start justify-between mb-4">
                <div className="flex items-center space-x-2">
                  <div className="w-6 h-6 bg-[#da234d] rounded-lg flex items-center justify-center">
                    <div className="w-0 h-0 border-l-[6px] border-l-white border-y-[4px] border-y-transparent ml-0.5"></div>
                  </div>
                  <h3 className="text-lg font-semibold text-white" translate="no">Cookie-Einstellungen</h3>
                </div>
                <button 
                  onClick={() => setShowBanner(false)}
                  className="text-bunny-muted hover:text-white transition-colors"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>

              <p className="text-bunny-light text-sm mb-4" translate="no">
                Wir verwenden Cookies und ähnliche Technologien, um unsere Website zu verbessern, 
                Inhalte zu personalisieren und Werbung zu schalten. Durch das Fortsetzen der Nutzung 
                unserer Website stimmen Sie der Verwendung von Cookies zu.
              </p>

              <div className="flex flex-col sm:flex-row gap-3">
                <Button
                  onClick={handleAcceptAll}
                  className="bg-[#da234d] hover:bg-[#da234d] text-white border-none transition-colors"
                >
                  <span translate="no">Alle akzeptieren</span>
                </Button>
                <Button
                  onClick={handleRejectAll}
                  variant="outline"
                  className="border-white/20 text-white hover:bg-white/10"
                >
                  <span translate="no">Alle ablehnen</span>
                </Button>
                <Button
                  onClick={() => setShowDetails(true)}
                  variant="ghost"
                  className="text-white hover:text-purple-400 hover:bg-transparent"
                >
                  <span translate="no">Einstellungen verwalten</span>
                </Button>
              </div>
            </div>
          ) : (
            // Detailed settings
            <div className="p-6">
              <div className="flex items-start justify-between mb-6">
                <h3 className="text-xl font-semibold text-white">Cookie-Einstellungen</h3>
                <button 
                  onClick={() => setShowDetails(false)}
                  className="text-bunny-muted hover:text-white transition-colors"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>

              <div className="space-y-6 mb-6">
                {/* Necessary Cookies */}
                <div className="bg-bunny-gray/20 p-4 rounded-lg">
                  <div className="flex items-center justify-between mb-2">
                    <h4 className="text-white font-medium">Notwendige Cookies</h4>
                    <div className="bg-[#da234d]/20 text-white px-2 py-1 rounded text-xs">
                      Immer aktiv
                    </div>
                  </div>
                  <p className="text-bunny-light text-sm">
                    Diese Cookies sind für das Funktionieren der Website erforderlich und können 
                    in unseren Systemen nicht deaktiviert werden.
                  </p>
                </div>

                {/* Analytics Cookies */}
                <div className="bg-bunny-gray/20 p-4 rounded-lg">
                  <div className="flex items-center justify-between mb-2">
                    <h4 className="text-white font-medium">Analyse-Cookies</h4>
                    <label className="relative inline-flex items-center cursor-pointer">
                      <input
                        type="checkbox"
                        checked={consent.analytics}
                        onChange={(e) => handleConsentChange('analytics', e.target.checked)}
                        className="sr-only peer"
                      />
                      <div className="w-11 h-6 bg-bunny-gray peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[#da234d]"></div>
                    </label>
                  </div>
                  <p className="text-bunny-light text-sm">
                    Diese Cookies ermöglichen es uns, Besuche und Verkehrsquellen zu zählen, 
                    damit wir die Leistung unserer Website messen und verbessern können.
                  </p>
                </div>

                {/* Advertising Cookies */}
                <div className="bg-bunny-gray/20 p-4 rounded-lg">
                  <div className="flex items-center justify-between mb-2">
                    <h4 className="text-white font-medium">Werbe-Cookies</h4>
                    <label className="relative inline-flex items-center cursor-pointer">
                      <input
                        type="checkbox"
                        checked={consent.advertising}
                        onChange={(e) => handleConsentChange('advertising', e.target.checked)}
                        className="sr-only peer"
                      />
                      <div className="w-11 h-6 bg-bunny-gray peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[#da234d]"></div>
                    </label>
                  </div>
                  <p className="text-bunny-light text-sm">
                    Diese Cookies werden von Werbepartnern über unsere Website gesetzt. Sie können 
                    verwendet werden, um ein Profil Ihrer Interessen zu erstellen und relevante 
                    Werbung auf anderen Websites zu zeigen.
                  </p>
                </div>
              </div>

              <div className="flex flex-col sm:flex-row gap-3">
                <Button
                  onClick={handleSavePreferences}
                  className="bg-[#da234d] hover:bg-[#da234d] text-white border-none transition-colors"
                >
                  Einstellungen speichern
                </Button>
                <Button
                  onClick={handleAcceptAll}
                  variant="outline"
                  className="border-white/20 text-white hover:bg-white/10"
                >
                  Alle akzeptieren
                </Button>
                <Button
                  onClick={handleRejectAll}
                  variant="ghost"
                  className="text-bunny-muted hover:text-white hover:bg-white/5"
                >
                  Alle ablehnen
                </Button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// Global declaration for gtag
declare global {
  interface Window {
    gtag: (...args: any[]) => void;
  }
}