import { useEffect, useState } from "react";
const actorDid = import.meta.env.PUBLIC_ACTOR_DID;

if (!actorDid) {
    console.error(
        "PUBLIC_ACTOR_DID is not defined. Please check your .env file.",
    );
}

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

    useEffect(() => {
        const fetchStatus = async () => {
            if (!actorDid) {
                setError("Configuration error: Actor DID is missing.");
                return;
            }
            try {
                const res = await fetch(
                    `https://public.api.bsky.app/xrpc/app.bsky.feed.getAuthorFeed?actor=${actorDid}&limit=1&filter=posts_no_replies`,
                );
                if (!res.ok) throw new Error(`HTTP ${res.status}`);

                const json = await res.json();
                const latestPost = json.feed[0].post;

                const status = {
                    text: latestPost.record.text,
                    createdAt: latestPost.record.createdAt,
                    link: `https://bsky.app/profile/${actorDid}/post/${
                        latestPost.uri.split("/")[4]
                    }`,
                };
                setData(status);
            } catch (err) {
                console.error("Fetch failed:", err);
                setError(err.message);
            }
        };

        fetchStatus();
    }, [actorDid]);

    if (error) {
        return (
            <span
                className="badge bg-dark"
                style={{
                    color: "#595959 !important",
                    //outline: "1px solid white",
                    //outlineOffset: "1px",
                }}
            >
                Error: {error}
            </span>
        );
    }
    if (!data) {
        return (
            <span
                className="badge bg-dark"
                style={{
                    color: "#595959 !important",
                    //outline: "1px solid white",
                    //outlineOffset: "1px",
                }}
            >
                Loading status...
            </span>
        );
    }

    const date = new Date(data.createdAt);
    const now = new Date();
    const diff = now.getTime() - date.getTime();

    const days = Math.floor(diff / (1000 * 60 * 60 * 24));

    if (days >= 2) {
        return null;
    }

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

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

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

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

    return (
        <a
            href={data.link}
            target="_blank"
            className={`badge bg-white ${oldStatusClasses}`}
            //style={{ outline: "1px solid white", outlineOffset: "1px" }}
        >
            I'm.. "{data.text}", {timeAgo}
        </a>
    );
}
