import { useContext, useEffect, useState } from 'react';
import { ClientContext } from '../../contexts/clientProvider';
import { apiFetch, getAddressFromPrivateKey } from '../../utils/helpers';
import { Row, Col, ListGroup, Alert, Container } from 'react-bootstrap';
import Loading from '../bootstrap/Loading';

export default function Ganache() {
    const client = useContext(ClientContext);

    const [ganacheResponse, setGanacheResponse] = useState(null);
    const [showGanacheInformation, setShowGanacheInformation] = useState(false);
    const [copySuccess, setCopySuccess] = useState(false);

    useEffect(() => {
        if (!client.loaded) return;
        if (!client.controller?.apiAccess) {
            console.error('No API available');
            return;
        }

        const main = async () => {
            let result = await apiFetch('/meta/ganache');
            setGanacheResponse(result);
        };

        main().catch((error) => {
            console.error(error);
        });
    }, [client]);

    return (
        <Container fluid>
            {!client.loaded ? (
                <>
                    <Loading />
                </>
            ) : (
                <>
                    <Row>
                        <Col className="m-3 border-bottom">
                            <h2>Ganache</h2>
                            <p>
                                Here you can view your ganache mnemonic and keys
                                which are currently being used by the API
                                server. Note that these credentials will only be
                                valid if you've ran ganache locally on the same
                                machine the API has access too. Otherwise it
                                will fallback onto what ever is set in the
                                environent settings of InfinityMint
                            </p>
                        </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 current ganache information.
                                </p>
                            </Alert>
                        </Col>
                    </Row>
                    <Row hidden={!client?.controller?.apiAccess}>
                        <Col className="m-1">
                            <ListGroup>
                                <ListGroup.Item
                                    action
                                    onClick={() => {
                                        setShowGanacheInformation(
                                            !showGanacheInformation
                                        );
                                    }}
                                >
                                    Expose Ganache Information
                                </ListGroup.Item>
                                {showGanacheInformation && (
                                    <>
                                        <ListGroup.Item>
                                            <Alert
                                                variant="info"
                                                className="mt-2"
                                                hidden={!copySuccess}
                                            >
                                                Copied!
                                            </Alert>
                                            <ListGroup>
                                                <ListGroup.Item className="text-center">
                                                    {ganacheResponse.mnemonic}
                                                    <br />
                                                    <button
                                                        className="btn btn-sm btn-outline-primary mt-2"
                                                        onClick={() => {
                                                            navigator.clipboard.writeText(
                                                                ganacheResponse.mnemonic
                                                            );
                                                            setCopySuccess(
                                                                true
                                                            );
                                                            setTimeout(() => {
                                                                setCopySuccess(
                                                                    false
                                                                );
                                                            }, 2000);
                                                        }}
                                                    >
                                                        Copy
                                                    </button>
                                                </ListGroup.Item>
                                            </ListGroup>
                                            <ListGroup className="mt-2 mb-2">
                                                {ganacheResponse.keys.map(
                                                    (key, index) => (
                                                        <ListGroup.Item>
                                                            <span className="h4 badge bg-primary text-white me-2">
                                                                {index}
                                                            </span>
                                                            <span className="h4">
                                                                {key}
                                                            </span>
                                                            <br />
                                                            <span className="text-muted">
                                                                {getAddressFromPrivateKey(
                                                                    key
                                                                )}
                                                            </span>
                                                            <span
                                                                className="text-muted ms-2"
                                                                style={{
                                                                    float: 'right',
                                                                }}
                                                            >
                                                                <button
                                                                    className="btn btn-sm btn-outline-primary"
                                                                    onClick={() => {
                                                                        navigator.clipboard.writeText(
                                                                            key
                                                                        );
                                                                        setCopySuccess(
                                                                            true
                                                                        );
                                                                        setTimeout(
                                                                            () => {
                                                                                setCopySuccess(
                                                                                    false
                                                                                );
                                                                            },
                                                                            2000
                                                                        );
                                                                    }}
                                                                >
                                                                    Copy
                                                                </button>
                                                            </span>
                                                        </ListGroup.Item>
                                                    )
                                                )}
                                            </ListGroup>
                                            <Alert
                                                variant="success"
                                                className="mt-3"
                                            >
                                                The deployer of the current
                                                project ({client.project.name})
                                                is{' '}
                                                {ganacheResponse.keys.filter(
                                                    (key) =>
                                                        getAddressFromPrivateKey(
                                                            key
                                                        ) ===
                                                        client.project.deployedProject.deployer?.toLowerCase()
                                                )[0] ||
                                                    'not a ganache address!'}
                                            </Alert>
                                            <Alert
                                                variant="info"
                                                hidden={!copySuccess}
                                            >
                                                Copied!
                                            </Alert>
                                            <button
                                                className="btn btn-primary"
                                                onClick={() => {
                                                    navigator.clipboard.writeText(
                                                        ganacheResponse.mnemonic
                                                    );
                                                    setCopySuccess(true);
                                                    setTimeout(() => {
                                                        setCopySuccess(false);
                                                    }, 2000);
                                                }}
                                            >
                                                Copy Mnemonic
                                            </button>
                                            <button
                                                className="btn btn-primary ms-2"
                                                disabled={
                                                    ganacheResponse.keys.filter(
                                                        (key) =>
                                                            getAddressFromPrivateKey(
                                                                key
                                                            ) ===
                                                            client.project.deployedProject?.deployer?.toLowerCase()
                                                    )[0] === undefined
                                                }
                                                onClick={() => {
                                                    navigator.clipboard.writeText(
                                                        ganacheResponse.keys.filter(
                                                            (key) =>
                                                                getAddressFromPrivateKey(
                                                                    key
                                                                ).toLowerCase() ===
                                                                client.project.deployedProject?.deployer?.toLowerCase()
                                                        )[0] ||
                                                            'not a ganache address!'
                                                    );
                                                    setCopySuccess(true);
                                                    setTimeout(() => {
                                                        setCopySuccess(false);
                                                    }, 2000);
                                                }}
                                            >
                                                Copy Deployer Private Key
                                            </button>
                                        </ListGroup.Item>
                                    </>
                                )}
                            </ListGroup>
                        </Col>
                    </Row>
                </>
            )}
            <br />
        </Container>
    );
}
