import React, { Fragment } from 'react';
import ReactDOM from 'react-dom';
import { getMemory } from '../../memory';
import { useEmitter, getshorthost } from '../../util';
import browserAPI from '../../lib/browser-api';

// Niezawodne pobieranie zakładki z ponawianiem prób
async function getCurrentTab(retries = 3, delay = 100): Promise<any> {
    for (let i = 0; i < retries; i++) {
        try {
            // Metoda 1: Zapytanie o aktywną zakładkę
            const tabs = await browserAPI.tabs.query({
                active: true,
                currentWindow: true,
            });
            
            if (tabs && tabs[0] && tabs[0].url) {
                return tabs[0];
            }

            // Metoda 2: Użycie lastFocusedWindow
            const tabsLastFocused = await browserAPI.tabs.query({
                active: true,
                lastFocusedWindow: true,
            });
            
            if (tabsLastFocused && tabsLastFocused[0] && tabsLastFocused[0].url) {
                return tabsLastFocused[0];
            }
        } catch (error) {
            console.warn(`Próba ${i + 1} zapytania o zakładkę nie powiodła się:`, error);
        }

        // Czekanie przed ponowieniem próby
        if (i < retries - 1) {
            await new Promise(resolve => setTimeout(resolve, delay));
        }
    }

    return undefined;
}

function isDomainHighlySuspicious(domain: string) {
    return (
        domain.includes('facebook') ||
        domain.includes('twitter') ||
        domain.includes('linkedin') ||
        false
    );
}

const Toolbar = () => {
    const [origin, setOrigin] = React.useState<string | null>(null);
    const [memoryReady, setMemoryReady] = React.useState(process.env.TARGET !== 'chrome');
    const [eventCounts] = useEmitter(getMemory());
    const [cookieDomainCopy, setCookieDomainCopy] = React.useState<string | null>(null);
    const [_, setMarksOccurrence] = React.useState(false);
    const [exposedOriginDomainCopy, setExposedOriginDomainCopy] = React.useState<string | null>(
        null
    );

    const first_sentence_cookie =
        'Strona dokonała zapisu i odczytu plików Cookie dla domen ';
    const first_sentence_history =
        'Część informacji o Twojej historii przeglądania została wysłana do ';

    // Oczekiwanie na gotowość pamięci Chrome
    React.useEffect(() => {
        if (process.env.TARGET === 'chrome') {
            const memory = getMemory();
            if (typeof (memory as any).waitUntilReady === 'function') {
                (memory as any).waitUntilReady().then(() => {
                    setMemoryReady(true);
                    console.log('✅ Memory gotowa, popup może wyświetlać dane');
                });
            } else {
                setMemoryReady(true);
            }
        }
    }, []);

    React.useEffect(() => {
        let isMounted = true;

        const listener = async () => {
            if (!isMounted) return;

            const tab = await getCurrentTab();
            
            if (!isMounted) return;
            
            if (tab && tab.url) {
                try {
                    const url = new URL(tab.url);
                    
                    // Pomijanie stron rozszerzenia
                    if (url.origin.startsWith('moz-extension') || 
                        url.origin.startsWith('chrome-extension') ||
                        url.protocol === 'chrome:' ||
                        url.protocol === 'about:') {
                        return;
                    }
                    
                    setOrigin(url.origin);
                } catch (error) {
                    console.warn('Nie udało się sparsować URL zakładki:', tab.url, error);
                }
            } else {
                // Tylko ostrzeżenie w trybie debug, nie błąd
                if (process.env.NODE_ENV === 'development') {
                    console.debug('Popup otwarty bez kontekstu aktywnej zakładki');
                }
            }
        };
        
        browserAPI.tabs.onUpdated.addListener(listener);
        
        // Początkowe wczytywanie z odpowiednim opóźnieniem
        if (process.env.TARGET === 'chrome') {
            // Chrome potrzebuje więcej czasu dla service worker + storage
            setTimeout(listener, 200);
        } else {
            // Firefox jest gotowy natychmiast
            listener();
        }
        
        return () => {
            isMounted = false;
            browserAPI.tabs.onUpdated.removeListener(listener);
        };
    }, []);

    React.useEffect(() => {
        if (!origin || !memoryReady) return;

        const exposedOriginDomains = Object.values(getMemory().getClustersForOrigin(origin))
            .filter((cluster) => cluster.exposesOrigin())
            .sort((cluster1, cluster2) =>
                isDomainHighlySuspicious(cluster1.id)
                    ? -1
                    : isDomainHighlySuspicious(cluster2.id)
                    ? 1
                    : 0
            )
            .map((cluster) => cluster.id);

        setExposedOriginDomainCopy('');

        switch (exposedOriginDomains.length) {
            case 0:
                break;
            case 1:
                setExposedOriginDomainCopy(`${exposedOriginDomains[0]}.`);
                break;
            case 2:
                setExposedOriginDomainCopy(
                    `${exposedOriginDomains[0]} oraz ${exposedOriginDomains[1]}.`
                );
                break;
            case 3:
                setExposedOriginDomainCopy(
                    `${exposedOriginDomains[0]}, ${exposedOriginDomains[1]} oraz ${exposedOriginDomains[2]}.`
                );
                break;
            default:
                setExposedOriginDomainCopy(
                    `${exposedOriginDomains[0]}, ${exposedOriginDomains[1]} (i ${
                        exposedOriginDomains.length - 2 < 2 ? 2 : exposedOriginDomains.length - 2
                    } innych).`
                );
                break;
        }
    }, [eventCounts['*'], origin, memoryReady]);

    React.useEffect(() => {
        if (!origin || !memoryReady) return;

        const cookieDomains = Object.values(getMemory().getClustersForOrigin(origin))
            .filter((cluster) => cluster.hasCookies())
            .sort((cluster1, cluster2) =>
                isDomainHighlySuspicious(cluster1.id)
                    ? -1
                    : isDomainHighlySuspicious(cluster2.id)
                    ? 1
                    : 0
            )
            .map((cluster) => cluster.id);

        setCookieDomainCopy('');

        switch (cookieDomains.length) {
            case 0:
                break;
            case 1:
                setCookieDomainCopy(`${cookieDomains[0]}.`);
                break;
            case 2:
                setCookieDomainCopy(`${cookieDomains[0]} oraz ${cookieDomains[1]}.`);
                break;
            case 3:
                setCookieDomainCopy(
                    `${cookieDomains[0]}, ${cookieDomains[1]} oraz ${cookieDomains[2]}.`
                );
                break;
            default:
                setCookieDomainCopy(
                    `${cookieDomains[0]}, ${cookieDomains[1]} (i ${
                        cookieDomains.length - 2 < 2 ? 2 : cookieDomains.length - 2
                    } innych).`
                );
                break;
        }
    }, [eventCounts['*'], origin, memoryReady]);

    const autoMark = () => {
        Object.values(getMemory().getClustersForOrigin(origin || '')).forEach((cluster) =>
            cluster.autoMark()
        );
        setMarksOccurrence(true);
    };

    return (
        <div className="toolbar">
            <header className={origin ? 'header' : 'header header--no-page'}>
                <img src="../../assets/icon-addon.svg" height="24" />
                <div className="webpage-metadata">
                    {origin ? (
                        <div className="webpage-metadata--hyperlink">{origin}</div>
                    ) : (
                        <div>Rentgen - wtyczka do przeglądania</div>
                    )}
                </div>
                {origin ? (
                    <button
                        onClick={() => {
                            window.close();
                        }}
                    >
                        <img src="../../assets/icons/x_thick.svg" width="12" height="12" />
                    </button>
                ) : (
                    <a href="https://internet-czas-dzialac.pl">
                        <img src="/assets/icons/info_circle_outline.svg" width="20" height="20" />
                    </a>
                )}
            </header>

            {origin ? (
                <Fragment>
                    {' '}
                    <section className="summary">
                        <div className="counters-wrapper">
                            <div className="counters">
                                <div className="counter counter--cookies">
                                    <img src="/assets/icons/cookie.svg#color" width="24" height="24" />
                                    <span data-event={`${eventCounts['*']}`}>
                                        {
                                            Object.values(getMemory().getClustersForOrigin(origin)).filter(
                                                (cluster) => cluster.hasCookies()
                                            ).length
                                        }
                                    </span>
                                </div>
                                <div className="counter counter--browser-history">
                                    <img src="/assets/icons/warning.svg#color" width="24" height="24" />
                                    <span data-event={`${eventCounts['*']}`}>
                                        {
                                            Object.values(getMemory().getClustersForOrigin(origin)).filter(
                                                (cluster) => cluster.exposesOrigin()
                                            ).length
                                        }
                                    </span>
                                </div>
                            </div>
                            <div className="big-counter" data-event={`${eventCounts['*']}`}>
                                {Object.values(getMemory().getClustersForOrigin(origin)).length}
                            </div>
                        </div>
                        <span className="notice">Liczba wykrytych domen podmiotów trzecich</span>
                    </section>
                    <section className="details">
                        {cookieDomainCopy ? (
                            <p
                                data-event={`${eventCounts['*']}`}
                                title={Object.values(getMemory().getClustersForOrigin(origin))
                                    .filter((cluster) => cluster.hasCookies())
                                    .map((domain) => domain.id)
                                    .join(', ')}
                            >
                                {first_sentence_cookie}
                                <strong>{cookieDomainCopy}</strong>
                            </p>
                        ) : null}
                        {exposedOriginDomainCopy ? (
                            <p
                                data-event={`${eventCounts['*']}`}
                                title={Object.values(getMemory().getClustersForOrigin(origin))
                                    .filter((cluster) => cluster.exposesOrigin())
                                    .map((domain) => domain.id)
                                    .join(', ')}
                            >
                                {first_sentence_history}
                                <strong>{exposedOriginDomainCopy}</strong>
                            </p>
                        ) : null}
                    </section>
                    {exposedOriginDomainCopy || cookieDomainCopy ? (
                        <Fragment>
                            <section className="about">
                                <p>
                                    Takie przetwarzanie danych może być niezgodne z&nbsp;prawem.
                                    Przejdź do analizy aby pomóc ustalić, czy ta strona nie narusza
                                    RODO lub ustawy Prawo Komunikacji Elektronicznej.
                                </p>
                            </section>
                            <section className="actions">
                                <button
                                    className="button button--report"
                                    onClick={() => {
                                        autoMark();
                                        window.open(
                                            `/components/sidebar/sidebar.html?origin=${origin}`,
                                            'new_tab'
                                        );
                                        window.close();
                                    }}
                                >
                                    Przejdź do analizy
                                </button>
                            </section>
                        </Fragment>
                    ) : (
                        <Fragment>
                            <section className="about about__no-errors">
                                <p>Nie znaleziono problemów na tej stronie.</p>
                            </section>
                        </Fragment>
                    )}
                </Fragment>
            ) : null}
        </div>
    );
};

ReactDOM.render(<Toolbar />, document.getElementById('toolbar'));