import React, { Fragment } from 'react';
import ReactDOM from 'react-dom';
import { getMemory } from '../../memory';
import { useEmitter } from '../../util';

import './report-window.scss';
import Questions from './questions';
import EmailContent from './email-content';
import { parseAnswers, ParsedAnswers } from './parse-answers';
import ScreenshotGenerator from './screenshot-generator';

function downloadFiles(link: string) {
    let a = document.createElement('a');
    a.setAttribute('href', link);
    a.setAttribute('download', '');
    a.setAttribute('target', '_blank');
    a.click();
}

function Report() {
    try {
        const url = new URL(document.location.toString());
        const origin = url.searchParams.get('origin');
        if (!origin) {
            return <div>Błąd: brak parametru "origin"</div>;
        }
        
        // Oczekiwanie na gotowość pamięci Chrome
        const [memoryReady, setMemoryReady] = React.useState(process.env.TARGET !== '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 dla okna raportu');
                    });
                } else {
                    setMemoryReady(true);
                }
            }
        }, []);
        
        const [counter] = useEmitter(getMemory());
        const rawAnswers = url.searchParams.get('answers');
        const [answers, setAnswers] = React.useState<ParsedAnswers>(
            rawAnswers ? JSON.parse(rawAnswers) : null
        );
        const [mode, setMode] = React.useState(url.searchParams.get('mode') || 'survey');
        const [scrRequestPath, setScrRequestPath] = React.useState('');

        // Pobieranie klastrów tylko gdy pamięć jest gotowa
        const clusters = memoryReady ? getMemory().getClustersForOrigin(origin || '') : {};

        React.useEffect(() => {
            if (!origin || !memoryReady) return;
            const url = new URL(document.location.toString());
            url.searchParams.set('origin', origin);
            url.searchParams.set('answers', JSON.stringify(answers));
            url.searchParams.set('mode', mode);
            history.pushState({}, 'Rentgen', url.toString());
        }, [mode, answers, origin, memoryReady]);
        
        // Wyświetlanie wczytywania w trakcie oczekiwania na pamięć
        if (!memoryReady) {
            return <div>Wczytywanie danych z rozszerzenia...</div>;
        }
        
        const visited_url = Object.values(clusters)
            .sort((a, b) => (a.lastModified > b.lastModified ? -1 : 1))
            .find((cluster) => !!cluster.lastFullUrl)?.lastFullUrl;

        // Jeśli nie znaleziono visited_url, próba skonstruowania z origin
        const finalVisitedUrl = visited_url || origin;
        
        if (!finalVisitedUrl) {
            return <div>Błąd: nie można znaleźć adresu strony</div>;
        }

        const result = (
            <div {...{ 'data-version': counter }}>
                {mode === 'survey' ? (
                    <Questions
                        clusters={Object.values(clusters).filter(
                            (cluster) => cluster.hasMarks()
                        )}
                        onComplete={(answers) => {
                            setAnswers(parseAnswers(answers));
                            setMode('screenshots');
                        }}
                    ></Questions>
                ) : (
                    ''
                )}
                {mode === 'screenshots' ? (
                    <ScreenshotGenerator
                        {...{
                            visited_url: finalVisitedUrl,
                            clusters,
                            setReportWindowMode: setMode,
                            setRequestPath: setScrRequestPath,
                            downloadFiles,
                            user_role: answers.user_role,
                        }}
                    />
                ) : (
                    ''
                )}
                {mode === 'preview' ? (
                    <EmailContent
                        {...{
                            answers,
                            visited_url: finalVisitedUrl,
                            clusters,
                            scrRequestPath,
                            downloadFiles,
                            user_role: answers.user_role,
                        }}
                    />
                ) : (
                    ''
                )}
            </div>
        );
        return result;
    } catch (e) {
        console.error(e);
        return (
            <div style={{ padding: 30 }}>
                <p>
                    <strong>Wystąpił błąd</strong>
                </p>
                <p>Najprawdopodobniej Rentgen napotkał stronę, której nie jest w stanie obsłużyć.</p>
                <p>{(e as Error).toString()}</p>
            </div>
        );
    }
}

ReactDOM.render(<Report />, document.getElementById('app'));