import React from "react";
import { Link, useParams } from "react-router";
import CoinInfo from "../components/coin-info";
import { useCoinInfoStore, reset, fetchCoinInfos } from "../store/coin-info";
import { useEffect } from "react";
import CoinChart from "../components/coin-chart";
import Spinner from "../components/spinner";

const CoinDetail: React.FC = () => {

    const { id } = useParams<string>();

    const coin = useCoinInfoStore(state => state.coinInfo);
    const loading = useCoinInfoStore(state => state.loading);
    const error = useCoinInfoStore(state => state.error);

    useEffect(() => {
        reset();
    }, [])

    useEffect(() => {
        const fetch = async () => {
            fetchCoinInfos(String(id));
        }
        fetch();
    }, [id]);

    return (
        <div className="coin-details-container">
            <Link to="/">⬅️ Back to Home</Link>

            {loading && <Spinner color="#3b88c3" />}

            {error && <div>Server overloaded, try again in few seconds</div>}

            {!loading && coin && (
                <>
                    <CoinInfo coin={coin} />
                    <CoinChart coinId={coin.id} />
                </>
            )}

        </div>
    );
};

export default CoinDetail;