import { useEffect, useState } from 'react';
import { Button, Card, Col, ListGroup, Row } from 'react-bootstrap';
import Token from '../../Token';
import { Project } from '../../../core/project';
import Loading from '../../bootstrap/Loading';
import { cutLongString } from '../../../utils/helpers';
import Assets from '../../bootstrap/Assets';
import { Dictionary } from 'infinitymint/dist/app/helpers';
import { InfinityMintProjectAsset } from 'infinitymint/dist/app/interfaces';
import { load } from '../../../main';
import path from 'path';

export default function Preview({
    project = {
        deployedProject: {},
    } as any,
    defaultPathId = null,
    defaultAssets = null,
    defaultSeed = null,
    selectComponent,
    selectTab,
}: {
    project: Project;
    defaultPathId?: number;
    defaultAssets?: Dictionary<InfinityMintProjectAsset>;
    defaultSeed?: number;
    selectComponent: (component: string) => void;
    selectTab: (tab: string, props?: any) => void;
}) {
    const [pathId, setPathId] = useState(defaultPathId);
    const [assets, setAssets] =
        useState<Dictionary<InfinityMintProjectAsset>>(defaultAssets);
    const [seed, setSeed] = useState(
        defaultSeed || Math.floor(Math.random() * 64)
    );
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        if (!project) return;

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

        setLoading(true);
        setAssets({ ...new Array(Object.keys(assetSections).length) } as any);
        setLoading(false);
    }, [project]);

    useEffect(() => {
        setLoading(true);

        if (defaultPathId !== null && defaultPathId !== undefined)
            setPathId(defaultPathId);

        setLoading(false);
    }, [defaultPathId]);

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

    return (
        <>
            <Row>
                <Col className="m-3 border-bottom">
                    <h2>
                        Preview{' '}
                        <span
                            className="badge bg-success"
                            style={{
                                float: 'right',
                                cursor: 'pointer',
                            }}
                        >
                            Mint ➕
                        </span>
                    </h2>
                    <p>
                        Preview how a token might look on the blockchain using
                        this utility.
                    </p>
                </Col>
            </Row>
            <Row className="mb-2">
                <Col lg={4}>
                    <Card body>
                        {loading ? (
                            <Loading />
                        ) : (
                            <div
                                style={{
                                    maxHeight: '50vh',
                                    overflow: 'auto',
                                }}
                            >
                                <ListGroup>
                                    {project.deployedProject.paths.map(
                                        (path) => {
                                            return (
                                                <ListGroup.Item
                                                    onClick={() => {
                                                        setPathId(path.pathId);
                                                    }}
                                                    variant={
                                                        path.pathId === pathId
                                                            ? 'success'
                                                            : 'secondary'
                                                    }
                                                    style={{
                                                        cursor: 'pointer',
                                                    }}
                                                >
                                                    {cutLongString(path.name)}
                                                    <b
                                                        className="ms-2"
                                                        onClick={() => {
                                                            selectTab(
                                                                'ViewPath',
                                                                {
                                                                    path: path,
                                                                    project:
                                                                        project,
                                                                }
                                                            );
                                                        }}
                                                    >
                                                        ✏️
                                                    </b>
                                                    <span
                                                        className="badge bg-info"
                                                        style={{
                                                            float: 'right',
                                                        }}
                                                    >
                                                        Rarity{' '}
                                                        {path.rarity ||
                                                            (
                                                                (1 /
                                                                    Object.values(
                                                                        project
                                                                            ?.deployedProject
                                                                            ?.paths ||
                                                                            []
                                                                    ).length) *
                                                                100
                                                            ).toFixed(2)}
                                                        %
                                                    </span>
                                                    <span
                                                        className="badge bg-secondary"
                                                        style={{
                                                            float: 'right',
                                                            marginRight: '4px',
                                                        }}
                                                    >
                                                        PathId {path.pathId}
                                                    </span>
                                                </ListGroup.Item>
                                            );
                                        }
                                    )}
                                </ListGroup>
                            </div>
                        )}
                    </Card>
                </Col>
                <Col lg>
                    {loading ? (
                        <Loading />
                    ) : (
                        <>
                            {pathId !== null && pathId !== undefined ? (
                                <>
                                    <Token
                                        loadingComponent={Loading}
                                        project={project}
                                        className="bg-light p-2 border"
                                        settings={{
                                            useRandom: true,
                                            pathId: pathId,
                                            assets: Object.values(
                                                assets || {}
                                            ).map(
                                                (asset) => asset?.assetId || 0
                                            ),
                                            seed: seed,
                                        }}
                                    />
                                    <div className="d-grid mt-2 mb-2">
                                        <Button
                                            variant="secondary"
                                            onClick={() => {
                                                setSeed(
                                                    Math.ceil(
                                                        Math.random() * 1000000
                                                    )
                                                );
                                                setPathId(
                                                    Math.floor(
                                                        Math.random() *
                                                            project
                                                                .deployedProject
                                                                .paths.length
                                                    )
                                                );
                                            }}
                                        >
                                            Regenerate{' '}
                                            <span className="badge bg-success">
                                                Seed: {seed}
                                            </span>
                                        </Button>
                                    </div>
                                </>
                            ) : (
                                <>
                                    <p className="display-5">
                                        Select a path to preview
                                    </p>
                                    <hr />
                                    <Button
                                        variant="success"
                                        onClick={() => {
                                            setPathId(
                                                Math.floor(
                                                    Math.random() *
                                                        project.deployedProject
                                                            .paths.length
                                                )
                                            );
                                        }}
                                    >
                                        Pick A Random Path
                                    </Button>
                                </>
                            )}
                        </>
                    )}
                </Col>
            </Row>
            <Assets
                assetSections={assetSections}
                project={project}
                selectedAssets={Object.values(assets || {}).map(
                    (asset) => asset?.assetId || 0
                )}
                hidden={
                    Object.values(project?.deployedProject?.assets || {})
                        .length === 0
                }
                onAssetSelected={(asset, unselect = false) => {
                    let sectionIndex = Object.keys(assetSections).indexOf(
                        asset.section
                    );

                    let newAssets = { ...(assets || {}) };

                    if (!unselect) newAssets[sectionIndex] = asset;
                    else newAssets[sectionIndex] = null;

                    if (
                        Object.values(newAssets).filter((val) => val).length ===
                        0
                    )
                        setAssets(null);
                    else setAssets(newAssets);
                }}
            ></Assets>
            <br />
        </>
    );
}
