import { useEffect, useState } from "react";
import AudioVisualizer from "./AudioVisualizer";

export default function Lastfm() {
    const [data, setData] = useState(null);
    const [error, setError] = useState(null);

    useEffect(() => {
        const fetchLastfmData = async () => {
            try {
                const res = await fetch(
                    "https://workers.indexx.dev/misc/lastfm",
                );
                if (!res.ok) throw new Error(`HTTP ${res.status}`);

                const json = await res.json();
                const status = {
                    song: json.track,
                    artist: json.artist,
                    albumArt: json.cover,
                    createdAt: json.createdAt,
                    link: json.url,
                    nowPlaying: !json.createdAt,
                };
                setData(status);
            } catch (err) {
                console.error("Fetch failed:", err);
                setError(err.message);
            }
        };

        fetchLastfmData();
    }, []);

    if (error || !data) return null;

    let timeAgo = "";
    let oldStatusClasses = "";

    if (!data.nowPlaying && data.createdAt) {
        const date = new Date(data.createdAt);
        const now = new Date();
        const diff = now.getTime() - date.getTime();

        const minutes = Math.floor(diff / 60000);
        const hours = Math.floor(minutes / 60);
        const days = Math.floor(hours / 24);

        if (days > 0) timeAgo = `${days} days ago`;
        else if (hours > 0) timeAgo = `${hours} hours ago`;
        else if (minutes > 0) timeAgo = `${minutes} minutes ago`;
        else timeAgo = "just now";

        if (days == 1) timeAgo = "1 day ago";

        oldStatusClasses = days > 3
            ? "opacity-75 text-decoration-line-through"
            : "";
    }

    return (
        <a
            id="now-playing"
            href={data.link}
            target="_blank"
            className={oldStatusClasses}
        >
            <AudioVisualizer isSilent={!data.nowPlaying} />
            <div
                style={{
                    display: "flex",
                    flexDirection: "column",
                    gap: "2px",
                    width: "100%",
                }}
            >
                <div style={{ fontWeight: "bold" }}>{data.song}</div>
                <div style={{ fontSize: "0.9em", marginTop: "-5px" }}>
                    {data.artist}
                </div>
                <div
                    style={{
                        fontSize: "0.8em",
                        opacity: 0.7,
                        marginTop: "-5px",
                    }}
                >
                    <small style={{ fontSize: "0.7rem" }}>
                        ^ what I'm listening (or last listened) to
                    </small>
                </div>
            </div>
        </a>
    );
}
