import { useState } from 'react';
import { Dialog } from 'primereact/dialog';
import { InputText } from 'primereact/inputtext';
import { Button } from 'primereact/button';

interface ParseDocsModalProps {
    visible: boolean;
    onHide: () => void;
    onParsed?: (endpoints: any[]) => void;
}

export function ParseDocsModal({ visible, onHide, onParsed }: ParseDocsModalProps) {
    const [url, setUrl] = useState('');
    const [loading, setLoading] = useState(false);
    const [results, setResults] = useState<any>(null);
    const [error, setError] = useState<string | null>(null);

    const handleParse = async () => {
        setLoading(true);
        setError(null);
        setResults(null);
        try {
            const response = await fetch('/api/parse-docs', {
                method: 'POST',
                body: JSON.stringify({ url }),
                headers: { 'Content-Type': 'application/json' }
            });
            if (!response.ok) throw new Error('Failed to fetch or parse docs');
            const data = await response.json();
            setResults(data);
            if (onParsed && data.restructured) onParsed(data.restructured);
        } catch (e: any) {
            setError(e.message || 'Unknown error');
        } finally {
            setLoading(false);
        }
    };

    return (
        <Dialog visible={visible} onHide={onHide} header="Parse API Docs" style={{ width: '50vw' }}>
            <div>
                <InputText
                    value={url}
                    onChange={e => setUrl(e.target.value)}
                    placeholder="Enter documentation URL"
                    className="w-full mb-3"
                />
                <Button label="Parse" onClick={handleParse} loading={loading} disabled={!url} />
                {error && <div className="text-red-500 mt-2">{error}</div>}
            </div>
            {results && (
                <div className="mt-4">
                    <h4>Raw HTML (first 500 chars):</h4>
                    <pre style={{ maxHeight: 200, overflow: 'auto', background: '#f8f9fa', padding: 8 }}>{results.rawHtml?.slice(0, 500)}...</pre>
                    <h4>AI Output:</h4>
                    <pre style={{ maxHeight: 200, overflow: 'auto', background: '#f8f9fa', padding: 8 }}>{JSON.stringify(results.aiOutput, null, 2)}</pre>
                    <h4>Restructured Output:</h4>
                    <pre style={{ maxHeight: 200, overflow: 'auto', background: '#f8f9fa', padding: 8 }}>{JSON.stringify(results.restructured, null, 2)}</pre>
                </div>
            )}
        </Dialog>
    );
}

export default ParseDocsModal; 