import React from 'react';
import { Header, Segment, Form, Button, Icon, Message, Dropdown, Input, TextArea } from 'semantic-ui-react';
import superagent from 'superagent';
import ExperimentalWrapper from './ExperimentalWrapper.jsx';

export default class KBUpload extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            sourceType: 'file',
            sourceId: '',
            sourceUrl: '',
            title: '',
            content: '',
            visibility: 'internal',
            loading: false,
            error: null,
            success: null
        };
    }

    async onSubmit(e) {
        e.preventDefault();
        const { sourceType, sourceId, sourceUrl, title, content, visibility } = this.state;

        if (!sourceId.trim()) {
            this.setState({ error: 'Source ID is required' });
            return;
        }

        if (!content.trim()) {
            this.setState({ error: 'Content is required' });
            return;
        }

        this.setState({ loading: true, error: null, success: null });

        try {
            const res = await superagent
                .post('/api/admin/kb/ingest/document')
                .set('Content-Type', 'application/json')
                .accept('json')
                .send({
                    sourceType,
                    sourceId: sourceId.trim(),
                    sourceUrl: sourceUrl.trim() || undefined,
                    title: title.trim() || undefined,
                    content: content.trim(),
                    visibility
                });

            if (!res.body || !res.body.documentId) {
                throw new Error('Invalid response from server');
            }

            this.setState({
                loading: false,
                success: {
                    documentId: res.body.documentId,
                    chunkCount: res.body.chunkCount
                },
                sourceId: '',
                sourceUrl: '',
                title: '',
                content: ''
            });
        } catch (error) {
            console.error('Upload failed:', error);
            const errorMsg = error.response?.body?.details
                || error.response?.body?.error
                || error.message
                || 'Unknown error occurred';
            this.setState({
                error: errorMsg,
                loading: false
            });
        }
    }

    render() {
        const { sourceType, sourceId, sourceUrl, title, content, visibility, loading, error, success } = this.state;

        const sourceTypeOptions = [
            { key: 'file', text: 'File', value: 'file' },
            { key: 'google_drive', text: 'Google Drive', value: 'google_drive' },
            { key: 'notion', text: 'Notion', value: 'notion' },
            { key: 'slack', text: 'Slack', value: 'slack' }
        ];

        const visibilityOptions = [
            { key: 'internal', text: 'Internal (all authenticated users)', value: 'internal' },
            { key: 'public', text: 'Public', value: 'public' },
            { key: 'restricted', text: 'Restricted (specific groups)', value: 'restricted' }
        ];

        return (
            <ExperimentalWrapper title="Upload Document">
                <Segment>
                    <Header as="h2">
                        <Icon name="cloud upload" />
                        <Header.Content>
                            Upload Document
                            <Header.Subheader>
                                Add a new document to the knowledge base
                            </Header.Subheader>
                        </Header.Content>
                    </Header>

                    {success && (
                        <Message positive>
                            <Message.Header>Document Uploaded Successfully</Message.Header>
                            <p>
                                Document ID: <code>{success.documentId}</code><br />
                                Chunks created: {success.chunkCount}
                            </p>
                            <Button
                                size="small"
                                onClick={() => this.setState({ success: null })}
                            >
                                Upload Another
                            </Button>
                        </Message>
                    )}

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

                    <Form onSubmit={this.onSubmit.bind(this)}>
                        <Form.Group widths="equal">
                            <Form.Field required>
                                <label>Source Type</label>
                                <Dropdown
                                    selection
                                    options={sourceTypeOptions}
                                    value={sourceType}
                                    onChange={(e, { value }) => this.setState({ sourceType: value })}
                                    disabled={loading}
                                />
                            </Form.Field>
                            <Form.Field required>
                                <label>Source ID</label>
                                <Input
                                    placeholder="Unique identifier for this document"
                                    value={sourceId}
                                    onChange={(e) => this.setState({ sourceId: e.target.value })}
                                    disabled={loading}
                                />
                            </Form.Field>
                        </Form.Group>

                        <Form.Group widths="equal">
                            <Form.Field>
                                <label>Title</label>
                                <Input
                                    placeholder="Document title (optional)"
                                    value={title}
                                    onChange={(e) => this.setState({ title: e.target.value })}
                                    disabled={loading}
                                />
                            </Form.Field>
                            <Form.Field>
                                <label>Source URL</label>
                                <Input
                                    placeholder="Original URL (optional)"
                                    value={sourceUrl}
                                    onChange={(e) => this.setState({ sourceUrl: e.target.value })}
                                    disabled={loading}
                                />
                            </Form.Field>
                        </Form.Group>

                        <Form.Field>
                            <label>Visibility</label>
                            <Dropdown
                                selection
                                options={visibilityOptions}
                                value={visibility}
                                onChange={(e, { value }) => this.setState({ visibility: value })}
                                disabled={loading}
                            />
                        </Form.Field>

                        <Form.Field required>
                            <label>Content</label>
                            <TextArea
                                placeholder="Paste the document content here..."
                                value={content}
                                onChange={(e) => this.setState({ content: e.target.value })}
                                disabled={loading}
                                rows={15}
                                style={{ fontFamily: 'monospace' }}
                            />
                        </Form.Field>

                        <Button primary size="large" loading={loading} disabled={loading || !sourceId.trim() || !content.trim()}>
                            <Icon name="cloud upload" />
                            Upload Document
                        </Button>

                        <Button as="a" href="/experimental/kb/documents" style={{ marginLeft: '1em' }}>
                            <Icon name="list" />
                            View Documents
                        </Button>
                    </Form>
                </Segment>
            </ExperimentalWrapper>
        );
    }
}
