import { useEffect, useState } from 'react';
import { useCookie } from '../../contexts/CookieContext';
import { useLanguage } from '../../contexts/LanguageContext';
import './cookie-banner.scss';
import { X } from 'lucide-react';

const CookieBanner = () => {
    const { showBanner, acceptAll, rejectAll, updateConsent, consent } = useCookie();
    const { language } = useLanguage();
    const [showSettings, setShowSettings] = useState(false);
    const [tempConsent, setTempConsent] = useState(consent);

    useEffect(() => {
        setTempConsent(consent);
    }, [consent, showBanner]);

    useEffect(() => {
        if (!showBanner) return;
        const previousOverflow = document.body.style.overflow;
        document.body.style.overflow = 'hidden';
        return () => {
            document.body.style.overflow = previousOverflow;
        };
    }, [showBanner]);

    const content = {
        fr: {
            title: 'Gestion des cookies 🍪',
            text: 'Nous utilisons des cookies pour sécuriser la connexion et améliorer le site.',
            accept: 'Tout accepter',
            reject: 'Tout refuser',
            settings: 'Personnaliser',
            save: 'Enregistrer',
            essential: 'Essentiels & Sécurité',
            essentialDesc: 'Toujours actifs: session de connexion, protection anti-abus, langue de base.',
            preferences: 'Préférences',
            preferencesDesc: 'Thème et préférences d’interface.',
            analytics: 'Analytiques',
            analyticsDesc: 'Mesure d’audience (Firebase Analytics).',
            selectAll: 'Tout cocher',
            details: 'Détails des données',
            detailsLine1: 'Essentiels: état de connexion et vérification de session.',
            detailsLine2: 'Préférences: thème clair/sombre.',
            detailsLine3: 'Analytiques: statistiques de fréquentation.',
        },
        en: {
            title: 'Cookie Management 🍪',
            text: 'We use cookies to secure sign-in and improve the site.',
            accept: 'Accept All',
            reject: 'Reject All',
            settings: 'Customize',
            save: 'Save Preferences',
            essential: 'Essential & Security',
            essentialDesc: 'Always active: sign-in session, anti-abuse protections, base language.',
            preferences: 'Preferences',
            preferencesDesc: 'Theme and UI preferences.',
            analytics: 'Analytics',
            analyticsDesc: 'Traffic measurement (Firebase Analytics).',
            selectAll: 'Select All',
            details: 'Data details',
            detailsLine1: 'Essential: sign-in state and session verification.',
            detailsLine2: 'Preferences: light/dark theme.',
            detailsLine3: 'Analytics: audience statistics.',
        }
    };

    const txt = content[language] || content.fr;

    if (!showBanner) return null;

    const handleSaveSettings = () => {
        updateConsent(tempConsent);
    };

    const togglePreference = (key: keyof typeof tempConsent) => {
        setTempConsent(prev => ({ ...prev, [key]: !prev[key] }));
    };

    const handleSelectAll = () => {
        setTempConsent(prev => ({
            ...prev,
            preferences: true,
            analytics: true
        }));
    };

    return (
        <div className="cookie-backdrop" role="dialog" aria-modal="true">
            <div className="cookie-banner">
                {!showSettings ? (
                    <div className="cookie-banner__content">
                        <div className="cookie-banner__text">
                            <h3>{txt.title}</h3>
                            <p>{txt.text}</p>
                            <div className="cookie-banner__details">
                                <strong>{txt.details}</strong>
                                <ul>
                                    <li>{txt.detailsLine1}</li>
                                    <li>{txt.detailsLine2}</li>
                                    <li>{txt.detailsLine3}</li>
                                </ul>
                            </div>
                        </div>
                        <div className="cookie-banner__actions">
                            <button className="cookie-banner__button cookie-banner__button--secondary" onClick={() => setShowSettings(true)}>
                                {txt.settings}
                            </button>
                            <button className="cookie-banner__button cookie-banner__button--secondary" onClick={rejectAll}>
                                {txt.reject}
                            </button>
                            <button className="cookie-banner__button cookie-banner__button--primary" onClick={acceptAll}>
                                {txt.accept}
                            </button>
                        </div>
                    </div>
                ) : (
                    <div className="cookie-banner__settings-view">
                        <div className="cookie-banner__content">
                            <div className="cookie-banner__text">
                                <h3>{txt.settings}</h3>
                            </div>
                            <button className="cookie-banner__button--text" onClick={() => setShowSettings(false)}>
                                <X size={20} />
                            </button>
                        </div>

                        <div className="cookie-banner__settings">
                            <div className="cookie-banner__header-actions">
                                <button className="cookie-banner__button--link" onClick={handleSelectAll}>
                                    {txt.selectAll}
                                </button>
                            </div>

                            <div className="cookie-banner__option">
                                <label>
                                    <strong>{txt.essential}</strong>
                                    <small>{txt.essentialDesc}</small>
                                </label>
                                <input type="checkbox" checked disabled />
                            </div>

                            <div className="cookie-banner__option">
                                <label htmlFor="pref-check">
                                    <strong>{txt.preferences}</strong>
                                    <small>{txt.preferencesDesc}</small>
                                </label>
                                <input
                                    id="pref-check"
                                    type="checkbox"
                                    checked={tempConsent.preferences}
                                    onChange={() => togglePreference('preferences')}
                                />
                            </div>

                            <div className="cookie-banner__option">
                                <label htmlFor="analytics-check">
                                    <strong>{txt.analytics}</strong>
                                    <small>{txt.analyticsDesc}</small>
                                </label>
                                <input
                                    id="analytics-check"
                                    type="checkbox"
                                    checked={tempConsent.analytics}
                                    onChange={() => togglePreference('analytics')}
                                />
                            </div>
                        </div>

                        <div className="cookie-banner__actions cookie-banner__actions--settings">
                            <button className="cookie-banner__button cookie-banner__button--secondary" onClick={rejectAll}>
                                {txt.reject}
                            </button>
                            <button className="cookie-banner__button cookie-banner__button--secondary" onClick={acceptAll}>
                                {txt.accept}
                            </button>
                            <button className="cookie-banner__button cookie-banner__button--primary" onClick={handleSaveSettings}>
                                {txt.save}
                            </button>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
};

export default CookieBanner;
