import React, { useState, useEffect, useCallback, useContext } from 'react';
import {
    Row,
    Col,
    Container,
    Form,
    InputGroup,
    Image,
    Card,
    Button,
    Alert,
} from 'react-bootstrap';
import { apiFetch, getApiEndpoint } from '../../utils/helpers';
import { ClientContext } from '../../contexts/clientProvider';

function Imports() {
    const client = useContext(ClientContext);
    const [imports, setImports] = useState(null);
    const [pages, setPages] = useState(0);
    const [count, setCount] = useState(0);
    const [input, setInput] = useState('');
    const [loading, setLoading] = useState(false);

    const fetchImports = useCallback(
        async (page: number = 1, search: string = null) => {
            try {
                setLoading(true);

                const data = await apiFetch(
                    '/meta/imports/all?page=' +
                        page +
                        (search ? '&search=' + search : ''),
                    {
                        method: 'GET',
                    }
                );

                const { imports, pages, count } = data;

                setImports(imports);
                setPages(pages);
                setCount(count);
            } catch (err) {
                throw new Error(
                    "The data you're trying to fetch is undefined!"
                );
            } finally {
                setLoading(false);
            }
        },
        []
    );

    useEffect(() => {
        if (!client.loaded) return;
        if (client?.controller?.apiAccess) fetchImports();
    }, [fetchImports, client]);

    return (
        <Container fluid>
            <Row>
                <Col className="m-3 border-bottom">
                    <h2>
                        Imports{' '}
                        <span className="badge bg-success">{count}</span>
                    </h2>
                    <p>
                        Here are all the imports which have been picked up by
                        InfinityMint are being used in your projects
                    </p>
                </Col>
            </Row>

            {client?.controller?.apiAccess ? (
                <>
                    <Row>
                        <Col>
                            <InputGroup className="mb-3">
                                <InputGroup.Text id="basic-addon3">
                                    Search Term
                                </InputGroup.Text>
                                <Form.Control
                                    value={input}
                                    id="text"
                                    onKeyDown={(e) => {
                                        if (e.key === 'Enter') {
                                            if (input === '') return;
                                            fetchImports(0, input);
                                        }
                                    }}
                                    onChange={(e) => {
                                        setInput(e.target.value);

                                        if (e.target.value === '')
                                            fetchImports();
                                    }}
                                    aria-describedby="basic-addon3"
                                />
                                <Button
                                    variant="outline-secondary"
                                    onClick={() => {
                                        if (input === '') return;
                                        fetchImports(0, input);
                                    }}
                                >
                                    Search
                                </Button>
                            </InputGroup>
                        </Col>
                    </Row>
                    <Row>
                        <Col className="d-grid">
                            <Button variant="success">Add New Import</Button>
                        </Col>
                    </Row>
                    <Row className="row-cols-5 gy-4 mt-2">
                        {Object.keys(imports || {}).map((importName) => {
                            let importFile = imports[importName];
                            let extensions = [
                                '.png',
                                '.jpg',
                                '.jpeg',
                                '.gif',
                                '.svg',
                                '.bmp',
                            ];
                            return (
                                <Col>
                                    <Card className="h-100">
                                        <Card.Header>
                                            {importFile.base}
                                        </Card.Header>
                                        <Card.Body className="h-100">
                                            <div className="card-block">
                                                <Image
                                                    hidden={
                                                        !extensions.includes(
                                                            importFile.extension
                                                        )
                                                    }
                                                    src={
                                                        getApiEndpoint(
                                                            'meta/imports/get',
                                                            false
                                                        ) +
                                                        '?key=' +
                                                        importName
                                                    }
                                                    crossOrigin="anonymous"
                                                    rounded
                                                    className="mb-3 img-fluid"
                                                />
                                                <Image
                                                    hidden={extensions.includes(
                                                        importFile.extension
                                                    )}
                                                    src="http://vignette2.wikia.nocookie.net/clubpenguin/images/d/d7/Stage_Script_icon.png/revision/latest?cb=20120802103434"
                                                    crossOrigin="anonymous"
                                                    rounded
                                                    className="mb-3 img-fluid"
                                                />
                                            </div>
                                        </Card.Body>
                                    </Card>
                                </Col>
                            );
                        })}
                    </Row>
                </>
            ) : (
                <Row hidden={client?.controller?.apiAccess}>
                    <Col>
                        <Alert variant="danger">
                            <Alert.Heading>
                                InfinityMint API not available
                            </Alert.Heading>
                            <p>
                                You must have the InfinityMint API running
                                locally to view your imports
                            </p>
                        </Alert>
                    </Col>
                </Row>
            )}
            <br />
        </Container>
    );
}

export default Imports;
