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

export default function Tealfm() {
    const [data, setData] = useState(null);
    const [error, setError] = useState(null);
    const [isCurrentlyPlaying, setIsCurrentlyPlaying] = useState(false);

    useEffect(() => {
        const fetchStatus = async () => {
            const repo = "did:plc:sfjxpxxyvewb2zlxwoz2vduw";
            const statusCollection = "fm.teal.alpha.actor.status";
            const lastPlayedCollection = "fm.teal.alpha.feed.play";

            try {
                const statusUrl =
                    `https://pds.indexx.dev/xrpc/com.atproto.repo.getRecord?repo=${repo}&collection=${statusCollection}&rkey=self`;
                const statusRes = await fetch(statusUrl);

                if (!statusRes.ok) {
                    throw new Error(`HTTP ${statusRes.status} on status fetch`);
                }

                const statusData = await statusRes.json();
                const statusValue = statusData?.value;
                const nowTimestamp = Math.floor(Date.now() / 1000);

                const isExpired = statusValue?.expiry &&
                    nowTimestamp > parseInt(statusValue.expiry, 10);
                const isItemEmpty = !statusValue?.item?.trackName;

                let status;

                if (statusValue && !isExpired && !isItemEmpty) {
                    const latest = statusValue.item;

                    status = {
                        song: latest.trackName,
                        artist: latest.artists.map((artist) =>
                            artist.artistName
                        ).join(", "),
                        createdAt: parseInt(statusValue.time, 10) * 1000,
                        link: latest.originUrl ?? "",
                    };
                    setData(status);
                    setIsCurrentlyPlaying(true);
                    return;
                }

                console.log(
                    "Status expired or empty. Falling back to last played record.",
                );

                const lastPlayedUrl =
                    `https://pds.indexx.dev/xrpc/com.atproto.repo.listRecords?repo=${repo}&collection=${lastPlayedCollection}&limit=1&reverse=false`;
                const lastPlayedRes = await fetch(lastPlayedUrl);

                if (!lastPlayedRes.ok) {
                    throw new Error(
                        `HTTP ${lastPlayedRes.status} on listRecords fetch`,
                    );
                }

                const lastPlayedData = await lastPlayedRes.json();

                if (
                    lastPlayedData.records && lastPlayedData.records.length > 0
                ) {
                    const latest = lastPlayedData.records[0].value;

                    status = {
                        song: latest.trackName,
                        artist: latest.artists.map((artist) =>
                            artist.artistName
                        ).join(", "),
                        albumArt:
                            `https://coverartarchive.org/release/${latest.releaseMbId}/front-500`,
                        createdAt: latest.playedTime,
                        link: latest.originUrl ?? "",
                    };
                    setData(status);
                    setIsCurrentlyPlaying(false);
                } else {
                    console.log("No records found in last played collection.");
                    setIsCurrentlyPlaying(false);
                }
            } catch (err) {
                console.error("Fetch failed:", err);
                setError(err.message);
                setIsCurrentlyPlaying(false);
            }
        };

        fetchStatus();
    }, []);

    if (error) return <span>Error: {error}</span>;
    if (!data) return null;

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

    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";

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

    return (
        <a
            id="now-playing"
            href={data.link}
            target="_blank"
            className={oldStatusClasses}
        >
            <AudioVisualizer isSilent={!isCurrentlyPlaying} />
            <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>
    );
}
