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

interface CookiePreferences {
  necessary: boolean;
  analytics: boolean;
  marketing: boolean;
}

const CookieConsent = () => {
  const [isVisible, setIsVisible] = useState(false);
  const [showDetails, setShowDetails] = useState(false);
  const [preferences, setPreferences] = useState<CookiePreferences>({
    necessary: true,
    analytics: false,
    marketing: false,
  });

  useEffect(() => {
    // Check if user already consented
    const consent = localStorage.getItem('cookie-consent');
    if (!consent) {
      // Show after 2 seconds
      const timer = setTimeout(() => setIsVisible(true), 2000);
      return () => clearTimeout(timer);
    }
  }, []);

  const handleAcceptAll = () => {
    const allAccepted: CookiePreferences = {
      necessary: true,
      analytics: true,
      marketing: true,
    };
    setPreferences(allAccepted);
    saveConsent(allAccepted);
  };

  const handleAcceptSelected = () => {
    saveConsent(preferences);
  };

  const handleRejectAll = () => {
    const onlyNecessary: CookiePreferences = {
      necessary: true,
      analytics: false,
      marketing: false,
    };
    setPreferences(onlyNecessary);
    saveConsent(onlyNecessary);
  };

  const saveConsent = (prefs: CookiePreferences) => {
    localStorage.setItem('cookie-consent', JSON.stringify(prefs));
    setIsVisible(false);

    // Enable/disable tracking based on consent
    if (prefs.analytics) {
      // Enable GA4
      (window as any).gtag?.('consent', 'update', {
        analytics_storage: 'granted',
      });
    } else {
      (window as any).gtag?.('consent', 'update', {
        analytics_storage: 'denied',
      });
    }

    if (prefs.marketing) {
      // Enable Google Ads
      (window as any).gtag?.('consent', 'update', {
        ad_storage: 'granted',
        ad_user_data: 'granted',
        ad_personalization: 'granted',
      });
    } else {
      (window as any).gtag?.('consent', 'update', {
        ad_storage: 'denied',
        ad_user_data: 'denied',
        ad_personalization: 'denied',
      });
    }
  };

  const togglePreference = (key: keyof CookiePreferences) => {
    if (key === 'necessary') return; // Always required
    setPreferences((prev) => ({ ...prev, [key]: !prev[key] }));
  };

  if (!isVisible) return null;

  return (
    <div className="fixed bottom-0 left-0 right-0 z-[100] bg-[#1a1a1a] border-t border-white/10 shadow-2xl">
      <div className="container-custom py-4 md:py-6">
        <div className="flex flex-col md:flex-row items-start md:items-center gap-4">
          {/* Icon */}
          <div className="hidden md:flex w-12 h-12 rounded-xl bg-[#cbf400]/10 items-center justify-center flex-shrink-0">
            <Cookie className="w-6 h-6 text-[#cbf400]" />
          </div>

          {/* Content */}
          <div className="flex-1">
            <p className="text-white font-semibold mb-1">
              Este site utiliza cookies
            </p>
            <p className="text-gray-400 text-sm">
              Utilizamos cookies para melhorar sua experiencia, analisar trafego e personalizar conteudo. 
              Voce pode aceitar todos ou gerenciar suas preferencias.{' '}
              <a href="#/privacidade" className="text-[#cbf400] hover:underline">
                Politica de Privacidade
              </a>
            </p>
          </div>

          {/* Buttons */}
          <div className="flex flex-col sm:flex-row gap-2 flex-shrink-0">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setShowDetails(!showDetails)}
              className="border-white/20 text-gray-300 hover:bg-white/10"
            >
              {showDetails ? (
                <ChevronUp className="w-4 h-4 mr-1" />
              ) : (
                <ChevronDown className="w-4 h-4 mr-1" />
              )}
              Personalizar
            </Button>
            <Button
              size="sm"
              variant="outline"
              onClick={handleRejectAll}
              className="border-white/20 text-gray-300 hover:bg-white/10"
            >
              <X className="w-4 h-4 mr-1" />
              Recusar
            </Button>
            <Button
              size="sm"
              onClick={handleAcceptAll}
              className="bg-[#cbf400] text-[#0e0e0e] hover:bg-[#b8e000] font-semibold"
            >
              Aceitar Todos
            </Button>
          </div>
        </div>

        {/* Details Panel */}
        {showDetails && (
          <div className="mt-4 pt-4 border-t border-white/10 space-y-3">
            {[
              {
                key: 'necessary' as const,
                title: 'Cookies Necessarios',
                description: 'Essenciais para o funcionamento do site. Nao podem ser desativados.',
                required: true,
              },
              {
                key: 'analytics' as const,
                title: 'Cookies de Analytics',
                description: 'Google Analytics - Ajuda a entender como voce usa o site.',
                required: false,
              },
              {
                key: 'marketing' as const,
                title: 'Cookies de Marketing',
                description: 'Google Ads - Permite anuncios relevantes e remarketing.',
                required: false,
              },
            ].map((cookie) => (
              <div
                key={cookie.key}
                className="flex items-center justify-between p-3 bg-[#0e0e0e] rounded-xl"
              >
                <div className="flex-1">
                  <p className="text-white font-medium text-sm">{cookie.title}</p>
                  <p className="text-gray-500 text-xs">{cookie.description}</p>
                </div>
                <label className="relative inline-flex items-center cursor-pointer ml-4">
                  <input
                    type="checkbox"
                    checked={preferences[cookie.key]}
                    onChange={() => togglePreference(cookie.key)}
                    disabled={cookie.required}
                    className="sr-only peer"
                  />
                  <div
                    className={`w-11 h-6 rounded-full peer transition-colors ${
                      preferences[cookie.key]
                        ? 'bg-[#cbf400]'
                        : 'bg-gray-600'
                    } ${cookie.required ? 'opacity-50' : ''}`}
                  >
                    <div
                      className={`absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full transition-transform ${
                        preferences[cookie.key] ? 'translate-x-5' : 'translate-x-0'
                      }`}
                    />
                  </div>
                </label>
              </div>
            ))}

            <div className="flex justify-end">
              <Button
                size="sm"
                onClick={handleAcceptSelected}
                className="bg-[#cbf400] text-[#0e0e0e] hover:bg-[#b8e000] font-semibold"
              >
                Salvar Preferencias
              </Button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default CookieConsent;
