import React, { useState, useEffect } from 'react';
import './App.css';

function App() {
    const [file, setFile] = useState<File | null>(null);
    const [query, setQuery] = useState('');
    const [answer, setAnswer] = useState('');
    const [context, setContext] = useState<string[]>([]);
    const [loading, setLoading] = useState(false);
    const [uploadStatus, setUploadStatus] = useState('');

    const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files && e.target.files[0]) {
            setFile(e.target.files[0]);
            const formData = new FormData();
            formData.append('file', e.target.files[0]);

            setLoading(true);
            setUploadStatus('Uploading...');

            try {
                const response = await fetch('http://localhost:8000/upload', {
                    method: 'POST',
                    body: formData,
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.detail || 'Failed to upload file');
                }

                const data = await response.json();
                setUploadStatus(`Success! Processed ${data.chunks} chunks`);
            } catch (error) {
                console.error('Error:', error);
                setUploadStatus(error instanceof Error ? error.message : 'Error uploading file');
            }

            setLoading(false);
        }
    };

    const handleQuery = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!query.trim()) return;

        setLoading(true);
        try {
            const response = await fetch('http://localhost:8000/query', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ query: query.trim() }),
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.detail || 'Failed to get response');
            }

            const data = await response.json();
            console.log(data);
            setAnswer(data.response);
            setContext(data.context);
        } catch (error) {
            console.error('Error:', error);
            setAnswer(error instanceof Error ? error.message : 'Error getting response');
        }
        setLoading(false);
    };

    const checkStatus = async () => {
        try {
            const response = await fetch('http://localhost:8000/status');
            const data = await response.json();
            if (data.ready) {
                setUploadStatus('Session initialized. Ready for document upload.');
            }
        } catch (error) {
            console.error('Error checking status:', error);
        }
    };

    useEffect(() => {
        checkStatus();
    }, []);

    return (
        <div className="App">
            {loading && <div className="loader">
                <p>Processing your document...</p>
            </div>}
            <header className="App-header">
                <h1>Custom document Q&A System</h1>
            </header>

            <main className="App-main">
                <section className="upload-section">
                    <h2>Upload Document</h2>
                    <input
                        type="file"
                        accept=".txt,.pdf"
                        onChange={handleFileUpload}
                        disabled={loading}
                    />
                    {uploadStatus && <p className="status">{uploadStatus}</p>}
                </section>

                <section className="query-section">
                    <h2>Ask a Question</h2>
                    <form onSubmit={handleQuery}>
                        <input
                            type="text"
                            value={query}
                            onChange={(e) => setQuery(e.target.value)}
                            placeholder="Enter your question..."
                            disabled={loading || !uploadStatus.includes('Success')}
                        />
                        <button
                            type="submit"
                            disabled={loading || !uploadStatus.includes('Success')}
                        >
                            Ask
                        </button>
                    </form>
                </section>

                {answer && (
                    <section className="answer-section">
                        <h2>Answer</h2>
                        <p>{answer}</p>

                        <h3>Relevant Context</h3>
                        <div className="context">
                            {context.map((text, index) => (
                                <div key={index} className="context-item">
                                    {text}
                                </div>
                            ))}
                        </div>
                    </section>
                )}
            </main>
        </div>
    );
}

export default App;