import React from 'react';
import { Header, Segment, Form, Button, Icon, Message, Card, Label, Divider, Accordion } from 'semantic-ui-react';
import superagent from 'superagent';
import ExperimentalWrapper from './ExperimentalWrapper.jsx';

// Simple markdown to HTML converter for basic formatting
function renderMarkdown(text) {
    if (!text) return '';

    let html = text
        // Escape HTML
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        // Code blocks (```...```)
        .replace(/```(\w*)\n([\s\S]*?)```/g, '<pre><code>$2</code></pre>')
        // Inline code (`...`)
        .replace(/`([^`]+)`/g, '<code>$1</code>')
        // Headers
        .replace(/^### (.+)$/gm, '<h4>$1</h4>')
        .replace(/^## (.+)$/gm, '<h3>$1</h3>')
        .replace(/^# (.+)$/gm, '<h2>$1</h2>')
        // Bold
        .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
        // Italic
        .replace(/\*([^*]+)\*/g, '<em>$1</em>')
        // Unordered lists
        .replace(/^[\-\*] (.+)$/gm, '<li>$1</li>')
        // Numbered lists
        .replace(/^\d+\. (.+)$/gm, '<li>$1</li>')
        // Links
        .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>')
        // Line breaks (double newline = paragraph)
        .replace(/\n\n/g, '</p><p>')
        // Single line breaks
        .replace(/\n/g, '<br/>');

    // Wrap consecutive <li> elements in <ul>
    html = html.replace(/(<li>.*?<\/li>)(\s*<br\/>)?(\s*<li>)/g, '$1$3');
    html = html.replace(/(<li>.*?<\/li>)+/g, '<ul>$&</ul>');

    return '<p>' + html + '</p>';
}

export default class KBQuery extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            query: '',
            answer: null,
            sources: [],
            metadata: null,
            loading: false,
            error: null,
            includeContext: true,
            useReranking: true,
            expandedSources: {}
        };
    }

    async onSubmit(e) {
        e.preventDefault();
        const { query, includeContext, useReranking } = this.state;

        if (!query.trim()) {
            this.setState({ error: 'Please enter a question' });
            return;
        }

        this.setState({ loading: true, error: null, answer: null, sources: [] });

        try {
            const res = await superagent
                .post('/api/admin/kb/query')
                .send({
                    query: query.trim(),
                    options: {
                        limit: 10,
                        includeContext: includeContext,
                        useReranking: useReranking
                    }
                });

            this.setState({
                answer: res.body.answer,
                sources: res.body.sources || [],
                metadata: res.body.metadata,
                loading: false
            });
        } catch (error) {
            console.error('Query failed:', error);
            this.setState({
                error: error.response?.body?.details || error.response?.body?.error || error.message,
                loading: false
            });
        }
    }

    toggleSource(index) {
        this.setState(prevState => ({
            expandedSources: {
                ...prevState.expandedSources,
                [index]: !prevState.expandedSources[index]
            }
        }));
    }

    renderAnswer() {
        const { answer, sources, metadata, expandedSources } = this.state;

        if (!answer) return null;

        return (
            <Segment>
                <Header as="h3">
                    <Icon name="lightbulb" color="yellow" />
                    Answer
                </Header>

                <Segment secondary style={{ lineHeight: '1.6' }} className="markdown-content">
                    <div dangerouslySetInnerHTML={{ __html: renderMarkdown(answer) }} />
                </Segment>

                {metadata && (
                    <Message size="small" info>
                        <Icon name="clock" />
                        Retrieval: {metadata.retrievalTimeMs}ms |
                        Generation: {metadata.generationTimeMs}ms |
                        Total: {metadata.totalTimeMs}ms
                    </Message>
                )}

                {sources.length > 0 && (
                    <>
                        <Divider />
                        <Header as="h4">
                            <Icon name="linkify" />
                            Sources ({sources.length})
                        </Header>

                        <Accordion styled fluid>
                            {sources.map((source, index) => (
                                <div key={index}>
                                    <Accordion.Title
                                        active={expandedSources[index]}
                                        onClick={() => this.toggleSource(index)}
                                    >
                                        <Icon name="dropdown" />
                                        <Label color={this.getSourceColor(source.sourceType)} size="small">
                                            {source.sourceType}
                                        </Label>
                                        {' '}
                                        {source.title || 'Untitled'}
                                        <Label size="mini" style={{ marginLeft: '10px' }}>
                                            {(source.relevance * 100).toFixed(0)}% relevant
                                        </Label>
                                    </Accordion.Title>
                                    <Accordion.Content active={expandedSources[index]}>
                                        {source.excerpt && (
                                            <Segment tertiary style={{ whiteSpace: 'pre-wrap' }}>
                                                {source.excerpt}...
                                            </Segment>
                                        )}
                                        {source.sourceUrl && (
                                            <p>
                                                <a href={source.sourceUrl} target="_blank" rel="noopener noreferrer">
                                                    <Icon name="external" /> View Original
                                                </a>
                                            </p>
                                        )}
                                    </Accordion.Content>
                                </div>
                            ))}
                        </Accordion>
                    </>
                )}
            </Segment>
        );
    }

    getSourceColor(sourceType) {
        const colors = {
            file: 'blue',
            slack: 'purple',
            google_drive: 'green',
            notion: 'orange'
        };
        return colors[sourceType] || 'grey';
    }

    render() {
        const { query, loading, error, includeContext, useReranking } = this.state;

        return (
            <ExperimentalWrapper title="Query Knowledge Base">
                <Segment>
                    <Header as="h2">
                        <Icon name="comment alternate" />
                        <Header.Content>
                            Query Knowledge Base
                            <Header.Subheader>
                                Ask questions and get AI-powered answers from indexed documents
                            </Header.Subheader>
                        </Header.Content>
                    </Header>

                    <Form onSubmit={this.onSubmit.bind(this)}>
                        <Form.Field>
                            <label>Your Question</label>
                            <Form.TextArea
                                placeholder="Ask a question about company policies, processes, documentation, or anything in the knowledge base..."
                                value={query}
                                onChange={(e) => this.setState({ query: e.target.value })}
                                disabled={loading}
                                rows={3}
                            />
                        </Form.Field>

                        <Form.Group inline>
                            <Form.Checkbox
                                label="Include source excerpts"
                                checked={includeContext}
                                onChange={(e, { checked }) => this.setState({ includeContext: checked })}
                                disabled={loading}
                            />
                            <Form.Checkbox
                                label="Use re-ranking"
                                checked={useReranking}
                                onChange={(e, { checked }) => this.setState({ useReranking: checked })}
                                disabled={loading}
                            />
                        </Form.Group>

                        <Button primary size="large" loading={loading} disabled={loading || !query.trim()}>
                            <Icon name="search" />
                            Ask Question
                        </Button>
                    </Form>
                </Segment>

                {error && (
                    <Message negative>
                        <Message.Header>Query Failed</Message.Header>
                        <p>{error}</p>
                    </Message>
                )}

                {this.renderAnswer()}
            </ExperimentalWrapper>
        );
    }
}
