import { useCallback, useContext, useEffect, useState } from 'react';
import { Row, Col, Alert, Toast, Card, Button } from 'react-bootstrap';
import { Project } from '../../../core/project';
import { ClientContext } from '../../../contexts/clientProvider';
import PathImage from '../../bootstrap/PathImage';
import Assets from '../../bootstrap/Assets';
import { cutLongString } from '../../../utils/helpers';

export default function Overview({
    project = {
        deployedProject: {},
    } as any,
    selectComponent,
    selectTab,
}: {
    project: Project;
    selectComponent: (component: string) => void;
    selectTab: (tab: string, props?: any) => void;
}) {
    const client = useContext(ClientContext);

    const [totalMints, setTotalMints] = useState(0);
    const [totalMintsUpdated, setTotalMintsUpdated] = useState(new Date());
    const [totalSupply, setTotalSupply] = useState(0);
    const [tokenPrice, setTokenPrice] = useState('0.0');
    const [totalPaths, setTotalPaths] = useState(8); //draw 16 paths
    const [web3Error, setWeb3Error] = useState(null);
    const [showPaths, setShowPaths] = useState(false);
    const [showAssets, setShowAssets] = useState(false);

    const getTotalMints = useCallback(async () => {
        if (!client.loaded) return;
        if (!project) return;
        const totalMints = await project.totalMints();
        setTotalMints(parseInt(totalMints.toString()));
        setTotalMintsUpdated(new Date());
    }, [project, client]);

    const getTotalSupply = useCallback(async () => {
        if (!project) return;
        if (!client.loaded) return;
        const supply = await project.maxSupply();
        setTotalSupply(parseInt(supply.toString()));
    }, [project, client]);

    const getTokenPrice = useCallback(async () => {
        if (!project) return;
        if (!client.loaded) return;
        const price = await project.getTokenPrice();
        setTokenPrice(price.toString());
    }, [project, client]);

    useEffect(() => {
        setWeb3Error(null);
        setTokenPrice('0.0');
        setTotalPaths(8);
        setTotalMints(0);
        setTotalSupply(0);

        getTotalMints().catch((e) => {
            console.error(e);
            setWeb3Error(e);
        });
        getTotalSupply().catch((e) => {
            console.error(e);
            setWeb3Error(e);
        });
        getTokenPrice().catch((e) => {
            console.error(e);
            setWeb3Error(e);
        });
    }, [getTotalMints, getTotalSupply, getTokenPrice]);

    let assetSections = project?.getAssetSections() || {};

    return (
        <>
            <Row>
                <Col>
                    <Alert variant="danger" hidden={!web3Error}>
                        <Alert.Heading>Web3 Error</Alert.Heading>
                        <p>{web3Error?.message}</p>
                    </Alert>
                </Col>
            </Row>
            <Row>
                <Col className="m-3 border-bottom">
                    <h2>Overview</h2>
                    <p>Last updated {new Date(Date.now()).toString()}</p>
                </Col>
            </Row>
            <Row className="gy-4 justify-content-center">
                <Col>
                    <Toast className="mx-auto">
                        <Toast.Header closeButton={false}>
                            <img
                                src="holder.js/20x20?text=%20"
                                className="rounded me-2"
                                alt=""
                            />
                            <strong className="me-auto">Mints</strong>
                            <small>
                                last updated at{' '}
                                {totalMintsUpdated.toLocaleTimeString()}
                            </small>
                        </Toast.Header>
                        <Toast.Body>
                            <Row>
                                <Col lg={4}>
                                    <p className="display-3">⭐</p>
                                </Col>
                                <Col>
                                    <p className="display-3">{totalMints}</p>
                                </Col>
                            </Row>
                        </Toast.Body>
                    </Toast>
                </Col>
                <Col>
                    <Toast className="mx-auto">
                        <Toast.Header closeButton={false}>
                            <img
                                src="holder.js/20x20?text=%20"
                                className="rounded me-2"
                                alt=""
                            />
                            <strong className="me-auto">Supply</strong>
                        </Toast.Header>
                        <Toast.Body>
                            <Row>
                                <Col lg={4}>
                                    <p className="display-3">🗃️</p>
                                </Col>
                                <Col>
                                    <p className="display-3">
                                        {cutLongString(
                                            totalSupply.toString(),
                                            8
                                        )}
                                    </p>
                                </Col>
                            </Row>
                        </Toast.Body>
                    </Toast>
                </Col>
                <Col>
                    <Toast className="mx-auto">
                        <Toast.Header closeButton={false}>
                            <img
                                src="holder.js/20x20?text=%20"
                                className="rounded me-2"
                                alt=""
                            />
                            <strong className="me-auto">Paths</strong>
                        </Toast.Header>
                        <Toast.Body>
                            <Row>
                                <Col lg={4}>
                                    <p className="display-3">👁️</p>
                                </Col>
                                <Col>
                                    <p className="display-3">
                                        {
                                            project?.deployedProject?.paths
                                                ?.length
                                        }
                                    </p>
                                </Col>
                            </Row>
                        </Toast.Body>
                    </Toast>
                </Col>
                <Col>
                    <Toast className="mx-auto">
                        <Toast.Header closeButton={false}>
                            <img
                                src="holder.js/20x20?text=%20"
                                className="rounded me-2"
                                alt=""
                            />
                            <strong className="me-auto">Price</strong>
                        </Toast.Header>
                        <Toast.Body>
                            <Row>
                                <Col lg={4}>
                                    <p className="display-3">🤑</p>
                                </Col>
                                <Col>
                                    <p className="display-3">{tokenPrice}</p>
                                </Col>
                            </Row>
                        </Toast.Body>
                    </Toast>
                </Col>
                <Col>
                    <Toast className="mx-auto">
                        <Toast.Header closeButton={false}>
                            <img
                                src="holder.js/20x20?text=%20"
                                className="rounded me-2"
                                alt=""
                            />
                            <strong className="me-auto">Assets</strong>
                        </Toast.Header>
                        <Toast.Body>
                            <Row>
                                <Col lg={4}>
                                    <p className="display-3">🎨</p>
                                </Col>
                                <Col>
                                    <p className="display-3">
                                        {
                                            Object.values(
                                                project?.deployedProject
                                                    ?.assets || {}
                                            )?.length
                                        }
                                    </p>
                                </Col>
                            </Row>
                        </Toast.Body>
                    </Toast>
                </Col>
                <Col>
                    <Toast className="mx-auto">
                        <Toast.Header closeButton={false}>
                            <img
                                src="holder.js/20x20?text=%20"
                                className="rounded me-2"
                                alt=""
                            />
                            <strong className="me-auto">Gems</strong>
                        </Toast.Header>
                        <Toast.Body>
                            <Row>
                                <Col lg={4}>
                                    <p className="display-3">💎</p>
                                </Col>
                                <Col>
                                    <p className="display-3">
                                        {
                                            Object.values(
                                                project?.deployedProject
                                                    ?.gems || {}
                                            )?.length
                                        }
                                    </p>
                                </Col>
                            </Row>
                        </Toast.Body>
                    </Toast>
                </Col>
            </Row>
            <Row className="mt-2">
                <Col className="m-3">
                    <h2>
                        Paths{' '}
                        <span className="badge bg-info">
                            {project?.deployedProject?.paths?.length}
                        </span>
                        <span
                            className="badge bg-success"
                            style={{
                                float: 'right',
                                cursor: 'pointer',
                            }}
                        >
                            New Path ➕
                        </span>
                    </h2>
                    <hr />
                </Col>
            </Row>
            {showPaths ? (
                <>
                    <Row className="row-cols-4 gy-4">
                        {project?.deployedProject?.paths
                            .slice(0, totalPaths)
                            .map((path, index) => (
                                <>
                                    <Col>
                                        <Card className="h-100">
                                            <Card.Header>
                                                <h5
                                                    className="mt-1"
                                                    style={{
                                                        fontSize: '0.75rem',
                                                    }}
                                                >
                                                    {path.name}{' '}
                                                    <span
                                                        className="badge bg-info ms-2"
                                                        style={{
                                                            float: 'right',
                                                        }}
                                                    >
                                                        Rarity{' '}
                                                        {path?.rarity ||
                                                            Math.ceil(
                                                                Object.values(
                                                                    project
                                                                        ?.deployedProject
                                                                        ?.paths
                                                                ).length / 100
                                                            )}
                                                        %
                                                    </span>
                                                    <span
                                                        className="badge bg-secondary ms-2"
                                                        style={{
                                                            float: 'right',
                                                        }}
                                                    >
                                                        PathId {index}
                                                    </span>
                                                </h5>
                                            </Card.Header>
                                            <Card.Body>
                                                <div className="card-block h-100">
                                                    <PathImage
                                                        path={path}
                                                        project={project}
                                                    />
                                                </div>
                                            </Card.Body>
                                            <Card.Footer>
                                                <Button
                                                    variant="secondary"
                                                    onClick={() => {
                                                        selectTab('ViewPath', {
                                                            path,
                                                            project,
                                                        });
                                                    }}
                                                >
                                                    ✏️
                                                </Button>
                                                <Button
                                                    variant="danger"
                                                    style={{
                                                        float: 'right',
                                                    }}
                                                    onClick={() => {
                                                        selectTab('ViewPath', {
                                                            path,
                                                            project,
                                                        });
                                                    }}
                                                >
                                                    Disable Path
                                                </Button>
                                            </Card.Footer>
                                        </Card>
                                    </Col>

                                    {totalPaths <
                                        project.deployedProject.paths.length &&
                                    index === totalPaths - 1 ? (
                                        <Col>
                                            <Card.Body className="d-grid gap-2">
                                                <Button
                                                    variant="outline-primary"
                                                    onClick={() =>
                                                        setTotalPaths(
                                                            totalPaths + 8
                                                        )
                                                    }
                                                >
                                                    Show More
                                                </Button>
                                                <Button
                                                    hidden={totalPaths - 8 < 8}
                                                    variant="outline-primary"
                                                    onClick={() =>
                                                        setTotalPaths(
                                                            Math.abs(
                                                                totalPaths - 8
                                                            )
                                                        )
                                                    }
                                                >
                                                    Show Less
                                                </Button>
                                            </Card.Body>
                                        </Col>
                                    ) : null}
                                </>
                            ))}
                    </Row>
                    <Row className="mt-4">
                        <Col>
                            <Card>
                                <Card.Body className="d-grid gap-2">
                                    <Button
                                        variant="outline-primary"
                                        onClick={() => {
                                            setShowPaths(false);
                                            setTotalPaths(8);
                                        }}
                                    >
                                        Hide Paths
                                    </Button>
                                    <Button
                                        hidden={
                                            totalPaths - 8 < 8 ||
                                            totalPaths <
                                                project?.deployedProject?.paths
                                                    ?.length
                                        }
                                        variant="outline-primary"
                                        onClick={() =>
                                            setTotalPaths(
                                                Math.abs(totalPaths - 8)
                                            )
                                        }
                                    >
                                        Show Less
                                    </Button>
                                </Card.Body>
                            </Card>
                        </Col>
                    </Row>
                </>
            ) : (
                <Row>
                    <Col>
                        <Card>
                            <Card.Body className="d-grid">
                                <Button
                                    variant="outline-primary"
                                    onClick={() => setShowPaths(true)}
                                >
                                    Show Paths
                                </Button>
                            </Card.Body>
                        </Card>
                    </Col>
                </Row>
            )}
            <Row className="mt-2">
                <Col className="m-3">
                    <h2>
                        Assets{' '}
                        <span className="badge bg-info">
                            {
                                Object.values(
                                    project?.deployedProject?.assets || {}
                                ).length
                            }
                        </span>
                        <span
                            className="badge bg-success"
                            style={{
                                float: 'right',
                                cursor: 'pointer',
                            }}
                        >
                            New Asset ➕
                        </span>
                    </h2>
                    <hr />
                </Col>
            </Row>
            <Assets
                assetSections={assetSections}
                project={project}
                showArrows={true}
                hidden={!showAssets}
                selectText="✏️"
                onAssetSelected={() => {
                    selectTab('ViewAsset');
                }}
            >
                <Button variant="danger" style={{ float: 'right' }}>
                    Disable Asset
                </Button>
            </Assets>
            {Object.values(project?.deployedProject?.assets || {}).length !==
            0 ? (
                <Row className="mt-2">
                    <Col>
                        <Card>
                            <Card.Body className="d-grid">
                                <Button
                                    variant="outline-primary"
                                    onClick={() => {
                                        setShowAssets(!showAssets);
                                    }}
                                >
                                    {showAssets ? 'Hide Assets' : 'Show Assets'}
                                </Button>
                            </Card.Body>
                        </Card>
                    </Col>
                </Row>
            ) : (
                <Row>
                    <Col>
                        <Alert variant="warning">
                            You have no assets defined in this project.
                        </Alert>
                    </Col>
                </Row>
            )}
            <br />
        </>
    );
}
