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

export default class KBDocuments extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            documents: [],
            pagination: { limit: 20, offset: 0, total: 0 },
            loading: true,
            error: null,
            selectedDocument: null,
            documentDetails: null,
            detailsModalOpen: false,
            deleteModalOpen: false,
            documentToDelete: null,
            filterSourceType: '',
            searchQuery: ''
        };
    }

    componentDidMount() {
        this.loadDocuments();
    }

    async loadDocuments() {
        const { pagination, filterSourceType } = this.state;

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

        try {
            let url = `/api/admin/kb/documents?limit=${pagination.limit}&offset=${pagination.offset}`;
            if (filterSourceType) {
                url += `&sourceType=${filterSourceType}`;
            }

            const res = await superagent.get(url);

            this.setState({
                documents: res.body.documents || [],
                pagination: res.body.pagination || pagination,
                loading: false
            });
        } catch (error) {
            console.error('Failed to load documents:', error);
            this.setState({
                error: error.response?.body?.error || error.message,
                loading: false
            });
        }
    }

    async loadDocumentDetails(documentId) {
        this.setState({ detailsModalOpen: true, documentDetails: null });

        try {
            const res = await superagent.get(`/api/admin/kb/document/${documentId}`);
            this.setState({ documentDetails: res.body });
        } catch (error) {
            console.error('Failed to load document details:', error);
            this.setState({
                error: error.response?.body?.error || error.message,
                detailsModalOpen: false
            });
        }
    }

    async deleteDocument() {
        const { documentToDelete } = this.state;
        if (!documentToDelete) return;

        try {
            await superagent.delete(`/api/admin/kb/document/${documentToDelete.source_type}/${documentToDelete.source_id}`);
            this.setState({ deleteModalOpen: false, documentToDelete: null });
            this.loadDocuments();
        } catch (error) {
            console.error('Failed to delete document:', error);
            this.setState({
                error: error.response?.body?.error || error.message,
                deleteModalOpen: false
            });
        }
    }

    handlePageChange(e, { activePage }) {
        const { pagination } = this.state;
        this.setState({
            pagination: {
                ...pagination,
                offset: (activePage - 1) * pagination.limit
            }
        }, () => this.loadDocuments());
    }

    handleFilterChange(e, { value }) {
        this.setState({
            filterSourceType: value,
            pagination: { ...this.state.pagination, offset: 0 }
        }, () => this.loadDocuments());
    }

    handlePageSizeChange(e, { value }) {
        this.setState({
            pagination: { ...this.state.pagination, limit: value, offset: 0 }
        }, () => this.loadDocuments());
    }

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

    formatDate(dateString) {
        if (!dateString) return '-';
        const date = new Date(dateString);
        return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
    }

    renderDocumentDetailsModal() {
        const { detailsModalOpen, documentDetails } = this.state;

        return (
            <Modal
                open={detailsModalOpen}
                onClose={() => this.setState({ detailsModalOpen: false, documentDetails: null })}
                size="large"
            >
                <Modal.Header>
                    <Icon name="file alternate" />
                    Document Details
                </Modal.Header>
                <Modal.Content scrolling>
                    {!documentDetails ? (
                        <Segment loading placeholder>
                            <Header icon>Loading...</Header>
                        </Segment>
                    ) : (
                        <>
                            <Segment>
                                <Header as="h4">Metadata</Header>
                                <Table definition compact>
                                    <Table.Body>
                                        <Table.Row>
                                            <Table.Cell width={4}>ID</Table.Cell>
                                            <Table.Cell><code>{documentDetails.document.id}</code></Table.Cell>
                                        </Table.Row>
                                        <Table.Row>
                                            <Table.Cell>Title</Table.Cell>
                                            <Table.Cell>{documentDetails.document.title || '-'}</Table.Cell>
                                        </Table.Row>
                                        <Table.Row>
                                            <Table.Cell>Source Type</Table.Cell>
                                            <Table.Cell>
                                                <Label color={this.getSourceColor(documentDetails.document.source_type)}>
                                                    {documentDetails.document.source_type}
                                                </Label>
                                            </Table.Cell>
                                        </Table.Row>
                                        <Table.Row>
                                            <Table.Cell>Source ID</Table.Cell>
                                            <Table.Cell><code>{documentDetails.document.source_id}</code></Table.Cell>
                                        </Table.Row>
                                        <Table.Row>
                                            <Table.Cell>Source URL</Table.Cell>
                                            <Table.Cell>
                                                {documentDetails.document.source_url ? (
                                                    <a href={documentDetails.document.source_url} target="_blank" rel="noopener noreferrer">
                                                        {documentDetails.document.source_url}
                                                    </a>
                                                ) : '-'}
                                            </Table.Cell>
                                        </Table.Row>
                                        <Table.Row>
                                            <Table.Cell>Visibility</Table.Cell>
                                            <Table.Cell>{documentDetails.document.visibility || 'internal'}</Table.Cell>
                                        </Table.Row>
                                        <Table.Row>
                                            <Table.Cell>Indexed At</Table.Cell>
                                            <Table.Cell>{this.formatDate(documentDetails.document.indexed_at)}</Table.Cell>
                                        </Table.Row>
                                    </Table.Body>
                                </Table>
                            </Segment>

                            <Segment>
                                <Header as="h4">
                                    Chunks ({documentDetails.chunks?.length || 0})
                                </Header>
                                {documentDetails.chunks?.map((chunk, index) => (
                                    <Segment key={chunk.id} secondary>
                                        <Label attached="top left" size="small">
                                            Chunk {chunk.chunk_index + 1} ({chunk.content_tokens} tokens)
                                        </Label>
                                        <p style={{ whiteSpace: 'pre-wrap', marginTop: '1em' }}>
                                            {chunk.content}
                                        </p>
                                    </Segment>
                                ))}
                            </Segment>
                        </>
                    )}
                </Modal.Content>
                <Modal.Actions>
                    <Button onClick={() => this.setState({ detailsModalOpen: false, documentDetails: null })}>
                        Close
                    </Button>
                </Modal.Actions>
            </Modal>
        );
    }

    renderDeleteModal() {
        const { deleteModalOpen, documentToDelete } = this.state;

        return (
            <Modal
                open={deleteModalOpen}
                onClose={() => this.setState({ deleteModalOpen: false, documentToDelete: null })}
                size="small"
            >
                <Modal.Header>
                    <Icon name="trash" color="red" />
                    Delete Document
                </Modal.Header>
                <Modal.Content>
                    <p>Are you sure you want to delete this document?</p>
                    {documentToDelete && (
                        <Segment>
                            <strong>{documentToDelete.title || 'Untitled'}</strong>
                            <br />
                            <Label size="small">{documentToDelete.source_type}</Label>
                            {' '}
                            <code>{documentToDelete.source_id}</code>
                        </Segment>
                    )}
                    <Message warning>
                        <Icon name="warning" />
                        This will permanently delete the document and all its indexed chunks.
                    </Message>
                </Modal.Content>
                <Modal.Actions>
                    <Button onClick={() => this.setState({ deleteModalOpen: false, documentToDelete: null })}>
                        Cancel
                    </Button>
                    <Button negative onClick={() => this.deleteDocument()}>
                        <Icon name="trash" />
                        Delete
                    </Button>
                </Modal.Actions>
            </Modal>
        );
    }

    render() {
        const { documents, pagination, loading, error, filterSourceType } = this.state;

        const sourceTypeOptions = [
            { key: 'all', text: 'All Sources', value: '' },
            { key: 'file', text: 'File', value: 'file' },
            { key: 'github', text: 'GitHub', value: 'github' },
            { key: 'slack', text: 'Slack', value: 'slack' },
            { key: 'google_drive', text: 'Google Drive', value: 'google_drive' },
            { key: 'notion', text: 'Notion', value: 'notion' },
            { key: 'discord', text: 'Discord', value: 'discord' }
        ];

        const pageSizeOptions = [
            { key: '20', text: '20 per page', value: 20 },
            { key: '50', text: '50 per page', value: 50 },
            { key: '100', text: '100 per page', value: 100 }
        ];

        const totalPages = Math.ceil((pagination.total || documents.length) / pagination.limit);
        const currentPage = Math.floor(pagination.offset / pagination.limit) + 1;

        return (
            <ExperimentalWrapper title="KB Documents" loading={loading}>
                <Segment>
                    <Header as="h2">
                        <Icon name="file alternate" />
                        <Header.Content>
                            Knowledge Base Documents
                            <Header.Subheader>
                                View and manage indexed documents
                            </Header.Subheader>
                        </Header.Content>
                    </Header>

                    <div style={{ marginBottom: '1em', display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: '0.5em' }}>
                        <Button primary href="/experimental/kb/upload">
                            <Icon name="cloud upload" />
                            Upload Document
                        </Button>

                        <Dropdown
                            selection
                            options={sourceTypeOptions}
                            value={filterSourceType}
                            onChange={this.handleFilterChange.bind(this)}
                            placeholder="Filter by source"
                        />

                        <Dropdown
                            selection
                            options={pageSizeOptions}
                            value={pagination.limit}
                            onChange={this.handlePageSizeChange.bind(this)}
                        />

                        <Button icon onClick={() => this.loadDocuments()}>
                            <Icon name="refresh" />
                        </Button>

                        {pagination.total > 0 && (
                            <span style={{ marginLeft: 'auto', color: '#666' }}>
                                <Icon name="file" />
                                {pagination.total.toLocaleString()} documents
                            </span>
                        )}
                    </div>
                </Segment>

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

                <Segment>
                    <Table celled striped>
                        <Table.Header>
                            <Table.Row>
                                <Table.HeaderCell>Title</Table.HeaderCell>
                                <Table.HeaderCell width={2}>Source</Table.HeaderCell>
                                <Table.HeaderCell width={3}>Source ID</Table.HeaderCell>
                                <Table.HeaderCell width={3}>Indexed At</Table.HeaderCell>
                                <Table.HeaderCell width={2}>Actions</Table.HeaderCell>
                            </Table.Row>
                        </Table.Header>
                        <Table.Body>
                            {documents.length === 0 ? (
                                <Table.Row>
                                    <Table.Cell colSpan={5} textAlign="center">
                                        <Icon name="inbox" size="large" />
                                        <p>No documents found</p>
                                    </Table.Cell>
                                </Table.Row>
                            ) : (
                                documents.map(doc => (
                                    <Table.Row key={doc.id}>
                                        <Table.Cell>
                                            <a
                                                href="#"
                                                onClick={(e) => {
                                                    e.preventDefault();
                                                    this.loadDocumentDetails(doc.id);
                                                }}
                                            >
                                                {doc.title || 'Untitled'}
                                            </a>
                                        </Table.Cell>
                                        <Table.Cell>
                                            <Label color={this.getSourceColor(doc.source_type)} size="small">
                                                {doc.source_type}
                                            </Label>
                                        </Table.Cell>
                                        <Table.Cell>
                                            <code style={{ fontSize: '0.85em' }}>
                                                {doc.source_id.length > 30
                                                    ? doc.source_id.substring(0, 30) + '...'
                                                    : doc.source_id}
                                            </code>
                                        </Table.Cell>
                                        <Table.Cell>
                                            {this.formatDate(doc.indexed_at)}
                                        </Table.Cell>
                                        <Table.Cell>
                                            <Button.Group size="tiny">
                                                <Button
                                                    icon="eye"
                                                    onClick={() => this.loadDocumentDetails(doc.id)}
                                                    title="View Details"
                                                />
                                                <Button
                                                    icon="trash"
                                                    color="red"
                                                    onClick={() => this.setState({
                                                        deleteModalOpen: true,
                                                        documentToDelete: doc
                                                    })}
                                                    title="Delete"
                                                />
                                            </Button.Group>
                                        </Table.Cell>
                                    </Table.Row>
                                ))
                            )}
                        </Table.Body>
                    </Table>

                    {totalPages > 0 && (
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '1em' }}>
                            <span style={{ color: '#666' }}>
                                Showing {pagination.offset + 1} - {Math.min(pagination.offset + pagination.limit, pagination.total)} of {pagination.total}
                            </span>
                            {totalPages > 1 && (
                                <Pagination
                                    activePage={currentPage}
                                    totalPages={totalPages}
                                    onPageChange={this.handlePageChange.bind(this)}
                                    siblingRange={1}
                                    boundaryRange={1}
                                />
                            )}
                        </div>
                    )}
                </Segment>

                {this.renderDocumentDetailsModal()}
                {this.renderDeleteModal()}
            </ExperimentalWrapper>
        );
    }
}
