import React, { useState, useEffect } from 'react';
import styled from 'styled-components';

declare global {
  interface Window {
    dataLayer: any[];
    gtag: (...args: any[]) => void;
  }
}

export interface CookiePreferences {
  essential: boolean;
  analytics_storage: boolean;
  ad_storage: boolean;
  ad_user_data: boolean;
  ad_personalization: boolean;
}

export interface CookieBannerProps {
  /** Primary color used for buttons and switches */
  primaryColor?: string;
  /** Text color for the banner */
  textColor?: string;
  /** Background color for the banner */
  backgroundColor?: string;
  /** Custom CSS class for the banner container */
  className?: string;
  /** Callback function when preferences are updated */
  onPreferencesUpdate?: (preferences: CookiePreferences) => void;
  /** Custom text for the title */
  titleText?: string;
  /** Custom text for the description */
  descriptionText?: string;
  /** Wait time in milliseconds before showing the banner */
  showDelay?: number;
  /** Google Tag Manager container ID */
  gtmContainerId?: string;
}

interface StyledButtonProps {
  $primaryColor: string;
  $textColor: string;
}

const defaultProps: Required<CookieBannerProps> = {
  primaryColor: '#FFD700',
  textColor: '#FFFFFF',
  backgroundColor: 'rgba(0, 0, 0, 0.95)',
  className: '',
  onPreferencesUpdate: () => {},
  titleText: 'Privacy Preferences Center',
  descriptionText: 'We use cookies and similar technologies to help personalize content, tailor and measure ads, and provide a better experience. By clicking "Accept All", you agree to this use. You can manage your preferences below. These settings will apply to all websites in this domain.',
  showDelay: 1000,
  gtmContainerId: ''
};

const BannerContainer = styled.div<{ show: boolean; backgroundColor: string; textColor: string }>`
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: ${props => props.backgroundColor};
  color: ${props => props.textColor};
  padding: 1.5rem;
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  z-index: 9999;
  transform: ${({ show }) => (show ? 'translateY(0)' : 'translateY(100%)')};
  transition: transform 0.3s ease-in-out;
  opacity: ${({ show }) => (show ? '1' : '0')};
  visibility: ${({ show }) => (show ? 'visible' : 'hidden')};
  max-width: 1200px;
  margin: 0 auto;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
  box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.15);
  
  @media (max-width: 768px) {
    padding: 1rem;
  }
`;

const Message = styled.div`
  display: flex;
  flex-direction: column;
  gap: 1rem;
`;

const Title = styled.h3`
  margin: 0;
  font-size: 1.2rem;
  font-weight: 600;
`;

const Description = styled.p`
  margin: 0;
  font-size: 0.9rem;
  line-height: 1.5;
  color: rgba(255, 255, 255, 0.9);
`;

const PreferenceSection = styled.div`
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
`;

const PreferenceItem = styled.div`
  display: flex;
  align-items: center;
  gap: 0.5rem;
`;

const Switch = styled.label<{ $primaryColor: string }>`
  position: relative;
  display: inline-block;
  width: 48px;
  height: 24px;
  
  input {
    opacity: 0;
    width: 0;
    height: 0;
    
    &:checked + span {
      background-color: ${props => props.$primaryColor};
    }
    
    &:checked + span:before {
      transform: translateX(24px);
    }
    
    &:disabled + span {
      opacity: 0.5;
      cursor: not-allowed;
    }
  }
  
  span {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    transition: 0.3s;
    border-radius: 24px;
    
    &:before {
      position: absolute;
      content: "";
      height: 18px;
      width: 18px;
      left: 3px;
      bottom: 3px;
      background-color: white;
      transition: 0.3s;
      border-radius: 50%;
    }
  }
`;

const ButtonGroup = styled.div`
  display: flex;
  gap: 1rem;
  margin-top: 1rem;
  
  @media (max-width: 768px) {
    flex-direction: column;
  }
`;

const Button = styled.button<StyledButtonProps>`
  padding: 0.75rem 1.5rem;
  border-radius: 6px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 0.9rem;
  
  &.accept-all {
    background: ${props => props.$primaryColor};
    color: black;
    border: none;
    
    &:hover {
      filter: brightness(0.9);
    }
  }
  
  &.accept-selected {
    background: transparent;
    color: ${props => props.$textColor};
    border: 1px solid ${props => props.$primaryColor};
    
    &:hover {
      background: ${props => props.$primaryColor}1A;
    }
  }
  
  &.decline-all {
    background: transparent;
    color: ${props => props.$textColor};
    border: 1px solid ${props => props.$textColor};
    
    &:hover {
      background: ${props => props.$textColor}1A;
    }
  }
  
  @media (max-width: 768px) {
    width: 100%;
  }
`;

const CookieBanner: React.FC<CookieBannerProps> = (props) => {
  const {
    primaryColor,
    textColor,
    backgroundColor,
    className,
    onPreferencesUpdate,
    titleText,
    descriptionText,
    showDelay,
    gtmContainerId
  } = { ...defaultProps, ...props };

  const [show, setShow] = useState(false);
  const [preferences, setPreferences] = useState<CookiePreferences>({
    essential: true,
    analytics_storage: false,
    ad_storage: false,
    ad_user_data: false,
    ad_personalization: false
  });

  const updateGoogleConsent = (prefs: CookiePreferences) => {
    if (!gtmContainerId) return;

    window.dataLayer = window.dataLayer || [];
    window.gtag = window.gtag || function(...args) { window.dataLayer.push(arguments); };
    
    window.gtag('consent', 'update', {
      'ad_user_data': prefs.ad_user_data ? 'granted' : 'denied',
      'ad_personalization': prefs.ad_personalization ? 'granted' : 'denied',
      'ad_storage': prefs.ad_storage ? 'granted' : 'denied',
      'analytics_storage': prefs.analytics_storage ? 'granted' : 'denied'
    });
  };

  useEffect(() => {
    const checkConsent = () => {
      try {
        const savedConsent = localStorage.getItem('cookieConsent');
        if (!savedConsent) {
          setShow(true);
          if (gtmContainerId) {
            window.dataLayer = window.dataLayer || [];
            window.gtag = window.gtag || function(...args) { window.dataLayer.push(arguments); };
            
            window.gtag('consent', 'default', {
              'ad_user_data': 'denied',
              'ad_personalization': 'denied',
              'ad_storage': 'denied',
              'analytics_storage': 'denied',
              'wait_for_update': 500
            });
          }
        } else {
          const savedPreferences = JSON.parse(savedConsent);
          setPreferences(savedPreferences);
          updateGoogleConsent(savedPreferences);
        }
      } catch (error) {
        console.error('localStorage error:', error);
        setShow(true);
      }
    };

    if (typeof window !== 'undefined') {
      setTimeout(checkConsent, showDelay);
    }
  }, [showDelay, gtmContainerId]);

  const handlePreferenceChange = (key: keyof CookiePreferences) => {
    setPreferences(prev => ({
      ...prev,
      [key]: !prev[key]
    }));
  };

  const handleAcceptAll = () => {
    const allAccepted = {
      essential: true,
      analytics_storage: true,
      ad_storage: true,
      ad_user_data: true,
      ad_personalization: true
    };
    setPreferences(allAccepted);
    localStorage.setItem('cookieConsent', JSON.stringify(allAccepted));
    updateGoogleConsent(allAccepted);
    onPreferencesUpdate(allAccepted);
    setShow(false);
  };

  const handleAcceptSelected = () => {
    localStorage.setItem('cookieConsent', JSON.stringify(preferences));
    updateGoogleConsent(preferences);
    onPreferencesUpdate(preferences);
    setShow(false);
  };

  const handleDeclineAll = () => {
    const allDeclined = {
      essential: true,
      analytics_storage: false,
      ad_storage: false,
      ad_user_data: false,
      ad_personalization: false
    };
    setPreferences(allDeclined);
    localStorage.setItem('cookieConsent', JSON.stringify(allDeclined));
    updateGoogleConsent(allDeclined);
    onPreferencesUpdate(allDeclined);
    setShow(false);
  };

  return (
    <BannerContainer 
      show={show} 
      backgroundColor={backgroundColor}
      textColor={textColor}
      className={className}
      role="dialog" 
      aria-modal="true" 
      aria-label="Cookie consent preferences"
    >
      <Message>
        <Title>{titleText}</Title>
        <Description>{descriptionText}</Description>
      </Message>
      
      <PreferenceSection>
        <PreferenceItem>
          <Switch $primaryColor={primaryColor}>
            <input
              type="checkbox"
              checked={preferences.essential}
              disabled
              aria-label="Essential cookies"
            />
            <span />
          </Switch>
          <span>Essential Cookies (Required)</span>
        </PreferenceItem>
        
        <PreferenceItem>
          <Switch $primaryColor={primaryColor}>
            <input
              type="checkbox"
              checked={preferences.analytics_storage}
              onChange={() => handlePreferenceChange('analytics_storage')}
              aria-label="Analytics cookies"
            />
            <span />
          </Switch>
          <span>Analytics Cookies</span>
        </PreferenceItem>
        
        <PreferenceItem>
          <Switch $primaryColor={primaryColor}>
            <input
              type="checkbox"
              checked={preferences.ad_storage}
              onChange={() => handlePreferenceChange('ad_storage')}
              aria-label="Advertising cookies"
            />
            <span />
          </Switch>
          <span>Advertising Cookies</span>
        </PreferenceItem>
        
        <PreferenceItem>
          <Switch $primaryColor={primaryColor}>
            <input
              type="checkbox"
              checked={preferences.ad_personalization}
              onChange={() => handlePreferenceChange('ad_personalization')}
              aria-label="Personalization cookies"
            />
            <span />
          </Switch>
          <span>Personalization</span>
        </PreferenceItem>
      </PreferenceSection>

      <ButtonGroup>
        <Button 
          $primaryColor={primaryColor}
          $textColor={textColor}
          className="accept-all" 
          onClick={handleAcceptAll}
          aria-label="Accept all cookies"
        >
          Accept All
        </Button>
        <Button 
          $primaryColor={primaryColor}
          $textColor={textColor}
          className="accept-selected" 
          onClick={handleAcceptSelected}
          aria-label="Accept selected cookies"
        >
          Accept Selected
        </Button>
        <Button 
          $primaryColor={primaryColor}
          $textColor={textColor}
          className="decline-all" 
          onClick={handleDeclineAll}
          aria-label="Decline all cookies"
        >
          Decline All
        </Button>
      </ButtonGroup>
    </BannerContainer>
  );
};

export default CookieBanner; 