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

interface ManageDocsModalProps {
    visible: boolean;
    onHide: () => void;
}

interface ParseResult {
    rawHtml: string;
    aiOutput: any;
    restructured: any;
}

const LOCAL_STORAGE_KEY = 'apiDocUrls';

export function ManageDocsModal({ visible, onHide }: ManageDocsModalProps) {
    const [urls, setUrls] = useState<string[]>([]);
    const [selectedUrl, setSelectedUrl] = useState<string | null>(null);
    const [newUrl, setNewUrl] = useState('');
    const [editIndex, setEditIndex] = useState<number | null>(null);
    const [editValue, setEditValue] = useState('');
    const [parsing, setParsing] = useState(false);
    const [parseResult, setParseResult] = useState<ParseResult | null>(null);
    const [error, setError] = useState<string | null>(null);

    // Load URLs from localStorage
    useEffect(() => {
        const saved = localStorage.getItem(LOCAL_STORAGE_KEY);
        if (saved) setUrls(JSON.parse(saved));
    }, []);

    // Save URLs to localStorage
    useEffect(() => {
        localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(urls));
    }, [urls]);

    const addUrl = () => {
        if (newUrl && !urls.includes(newUrl)) {
            setUrls([...urls, newUrl]);
            setNewUrl('');
        }
    };

    const removeUrl = (url: string) => {
        setUrls(urls.filter(u => u !== url));
        if (selectedUrl === url) setSelectedUrl(null);
    };

    const startEdit = (idx: number) => {
        setEditIndex(idx);
        setEditValue(urls[idx]);
    };

    const saveEdit = () => {
        if (editIndex !== null && editValue) {
            const newUrls = [...urls];
            newUrls[editIndex] = editValue;
            setUrls(newUrls);
            setEditIndex(null);
            setEditValue('');
        }
    };

    const handleParse = async (url: string) => {
        setParsing(true);
        setError(null);
        setParseResult(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();
            setParseResult(data);
        } catch (e: any) {
            setError(e.message || 'Unknown error');
        } finally {
            setParsing(false);
        }
    };

    return (
        <Dialog visible={visible} onHide={onHide} header="Manage API Docs" style={{ width: '60vw' }}>
            <div className="flex gap-4">
                {/* URL List and Controls */}
                <div style={{ minWidth: 300 }}>
                    <h4>Documentation URLs</h4>
                    <ListBox
                        value={selectedUrl}
                        options={urls.map(u => ({ label: u, value: u }))}
                        onChange={e => setSelectedUrl(e.value)}
                        style={{ width: '100%', minHeight: 200 }}
                    />
                    <div className="flex gap-2 mt-2">
                        <InputText
                            value={newUrl}
                            onChange={e => setNewUrl(e.target.value)}
                            placeholder="Add new URL"
                            className="w-full"
                        />
                        <Button label="Add" onClick={addUrl} disabled={!newUrl} />
                    </div>
                    {selectedUrl && (
                        <div className="flex gap-2 mt-2">
                            <Button label="Parse" onClick={() => handleParse(selectedUrl)} loading={parsing} />
                            <Button label="Remove" className="p-button-danger" onClick={() => removeUrl(selectedUrl)} />
                            <Button label="Edit" onClick={() => startEdit(urls.indexOf(selectedUrl))} />
                        </div>
                    )}
                    {editIndex !== null && (
                        <div className="flex gap-2 mt-2">
                            <InputText value={editValue} onChange={e => setEditValue(e.target.value)} className="w-full" />
                            <Button label="Save" onClick={saveEdit} />
                            <Button label="Cancel" className="p-button-secondary" onClick={() => setEditIndex(null)} />
                        </div>
                    )}
                </div>
                {/* Parse Results */}
                <div style={{ flex: 1 }}>
                    {error && <div className="text-red-500 mb-2">{error}</div>}
                    {parseResult && (
                        <div>
                            <h4>Raw HTML (first 500 chars):</h4>
                            <pre style={{ maxHeight: 200, overflow: 'auto', background: '#f8f9fa', padding: 8 }}>{parseResult.rawHtml?.slice(0, 500)}...</pre>
                            <h4>AI Output:</h4>
                            <pre style={{ maxHeight: 200, overflow: 'auto', background: '#f8f9fa', padding: 8 }}>{JSON.stringify(parseResult.aiOutput, null, 2)}</pre>
                            <h4>Restructured Output:</h4>
                            <pre style={{ maxHeight: 200, overflow: 'auto', background: '#f8f9fa', padding: 8 }}>{JSON.stringify(parseResult.restructured, null, 2)}</pre>
                        </div>
                    )}
                </div>
            </div>
        </Dialog>
    );
}

export default ManageDocsModal; 