import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';

const COOKIE_CONSENT_KEY = 'webmoney_cookie_consent';

const CookieConsent = () => {
  const { t } = useTranslation();
  const [showBanner, setShowBanner] = useState(false);
  const [showSettings, setShowSettings] = useState(false);
  const [preferences, setPreferences] = useState({
    essential: true,
    analytics: false,
    marketing: false,
  });

  useEffect(() => {
    const consent = localStorage.getItem(COOKIE_CONSENT_KEY);
    
    if (!consent) {
      const timer = setTimeout(() => {
        setShowBanner(true);
      }, 1000);
      return () => clearTimeout(timer);
    } else {
      try {
        const savedPreferences = JSON.parse(consent);
        setPreferences(savedPreferences);
      } catch (e) {
        setShowBanner(true);
      }
    }
  }, []);

  const saveConsent = (prefs) => {
    localStorage.setItem(COOKIE_CONSENT_KEY, JSON.stringify(prefs));
    setPreferences(prefs);
    setShowBanner(false);
    setShowSettings(false);
    window.dispatchEvent(new CustomEvent('cookieConsentUpdated', { detail: prefs }));
  };

  const acceptAll = () => {
    saveConsent({ essential: true, analytics: true, marketing: true });
  };

  const acceptEssential = () => {
    saveConsent({ essential: true, analytics: false, marketing: false });
  };

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

  if (!showBanner) return null;

  const overlayStyle = {
    position: 'fixed',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    zIndex: 1040,
  };

  const bannerStyle = {
    position: 'fixed',
    bottom: 0,
    left: 0,
    right: 0,
    zIndex: 1050,
    backgroundColor: '#1a1d21',
    borderTop: '1px solid #343a40',
    boxShadow: '0 -4px 20px rgba(0, 0, 0, 0.3)',
  };

  return (
    <>
      <div style={overlayStyle} />
      
      <div style={bannerStyle} className="p-4">
        <div className="container">
          {!showSettings ? (
            <div className="row align-items-center">
              <div className="col-lg-8 mb-3 mb-lg-0">
                <div className="d-flex align-items-center mb-2">
                  <i className="bi bi-shield-lock text-primary fs-4 me-2"></i>
                  <h5 className="mb-0 text-white">{t('cookies.title')}</h5>
                </div>
                <p className="text-secondary mb-0 small">
                  {t('cookies.description')}
                </p>
              </div>
              <div className="col-lg-4">
                <div className="d-flex flex-column flex-sm-row gap-2 justify-content-lg-end">
                  <button
                    onClick={() => setShowSettings(true)}
                    className="btn btn-outline-secondary btn-sm"
                  >
                    <i className="bi bi-gear me-1"></i>
                    {t('cookies.settings')}
                  </button>
                  <button
                    onClick={acceptEssential}
                    className="btn btn-outline-light btn-sm"
                  >
                    {t('cookies.essentialOnly')}
                  </button>
                  <button
                    onClick={acceptAll}
                    className="btn btn-primary btn-sm"
                  >
                    <i className="bi bi-check-lg me-1"></i>
                    {t('cookies.acceptAll')}
                  </button>
                </div>
              </div>
            </div>
          ) : (
            <div>
              <div className="d-flex justify-content-between align-items-center mb-3">
                <h5 className="mb-0 text-white">
                  <i className="bi bi-sliders me-2"></i>
                  {t('cookies.settingsTitle')}
                </h5>
                <button
                  onClick={() => setShowSettings(false)}
                  className="btn btn-sm btn-outline-secondary"
                >
                  <i className="bi bi-x-lg"></i>
                </button>
              </div>
              
              <p className="text-secondary small mb-3">
                {t('cookies.settingsDescription')}
              </p>
              
              <div className="bg-dark rounded p-3 mb-2">
                <div className="d-flex justify-content-between align-items-center">
                  <div>
                    <h6 className="text-white mb-1">{t('cookies.essential.title')}</h6>
                    <small className="text-secondary">{t('cookies.essential.description')}</small>
                  </div>
                  <span className="badge bg-success">{t('cookies.alwaysActive')}</span>
                </div>
              </div>
              
              <div className="bg-dark rounded p-3 mb-2">
                <div className="d-flex justify-content-between align-items-center">
                  <div>
                    <h6 className="text-white mb-1">{t('cookies.analytics.title')}</h6>
                    <small className="text-secondary">{t('cookies.analytics.description')}</small>
                  </div>
                  <div className="form-check form-switch">
                    <input
                      className="form-check-input"
                      type="checkbox"
                      role="switch"
                      checked={preferences.analytics}
                      onChange={(e) => setPreferences({ ...preferences, analytics: e.target.checked })}
                      style={{ cursor: 'pointer', width: '3rem', height: '1.5rem' }}
                    />
                  </div>
                </div>
              </div>
              
              <div className="bg-dark rounded p-3 mb-3">
                <div className="d-flex justify-content-between align-items-center">
                  <div>
                    <h6 className="text-white mb-1">{t('cookies.marketing.title')}</h6>
                    <small className="text-secondary">{t('cookies.marketing.description')}</small>
                  </div>
                  <div className="form-check form-switch">
                    <input
                      className="form-check-input"
                      type="checkbox"
                      role="switch"
                      checked={preferences.marketing}
                      onChange={(e) => setPreferences({ ...preferences, marketing: e.target.checked })}
                      style={{ cursor: 'pointer', width: '3rem', height: '1.5rem' }}
                    />
                  </div>
                </div>
              </div>
              
              <div className="d-flex justify-content-end gap-2">
                <button
                  onClick={() => setShowSettings(false)}
                  className="btn btn-outline-secondary btn-sm"
                >
                  {t('common.cancel')}
                </button>
                <button
                  onClick={saveSettingsHandler}
                  className="btn btn-primary btn-sm"
                >
                  <i className="bi bi-check-lg me-1"></i>
                  {t('cookies.saveSettings')}
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </>
  );
};

export const useCookieConsent = () => {
  const [preferences, setPreferences] = useState({
    essential: true,
    analytics: false,
    marketing: false,
  });

  useEffect(() => {
    const loadPreferences = () => {
      const consent = localStorage.getItem(COOKIE_CONSENT_KEY);
      if (consent) {
        try {
          setPreferences(JSON.parse(consent));
        } catch (e) {}
      }
    };

    loadPreferences();

    const handleUpdate = (event) => {
      setPreferences(event.detail);
    };

    window.addEventListener('cookieConsentUpdated', handleUpdate);
    return () => window.removeEventListener('cookieConsentUpdated', handleUpdate);
  }, []);

  return preferences;
};

export default CookieConsent;
