"use client";

import { useEffect, useState } from "react";
import { ExternalLink, Gamepad2, Headphones, MessageCircle, Music, Radio, WifiOff } from "lucide-react";
import BadgeIcon from "@/components/BadgeIcon";
import { badgesFromDiscordPublicFlags, DISCORD_INVITE_URL, type Profile } from "@/lib/constants";
import { card } from "./style";

type BotPresence = {
  ok: boolean;
  joined?: boolean;
  status?: "online" | "idle" | "dnd" | "offline" | string;
  activities?: { name: string; type: number; details?: string; state?: string; emoji?: string | null; emoji_url?: string | null }[];
  user?: {
    id: string;
    username: string;
    global_name?: string;
    avatar_url?: string;
    avatar_decoration_url?: string;
    public_badges?: string[];
  };
  member?: { server_booster?: boolean };
  error?: string;
};

const STATUS_COLOR: Record<string, string> = {
  online: "#ae3c3c",
  idle: "#faeeee",
  dnd: "#f0c1c1",
  offline: "#260d0d",
  invisible: "#260d0d",
};


function activityIcon(type?: number) {
  if (type === 2) return <Music size={15} />;
  if (type === 0) return <Gamepad2 size={15} />;
  if (type === 3) return <Radio size={15} />;
  if (type === 4) return <Headphones size={15} />;
  return <MessageCircle size={15} />;
}

function activityText(data?: BotPresence) {
  const first = data?.activities?.find((item) => item.type !== 4 && item.name);
  if (!first) return data?.status === "offline" ? "Offline" : "Doing nothing";
  const bottom = [first.details, first.state].filter(Boolean).join(" • ");
  return bottom ? `${first.name} — ${bottom}` : first.name;
}

export default function DiscordCard({ profile }: { profile: Profile }) {
  const accent = profile.accent || "#f5caca";
  const invite = DISCORD_INVITE_URL;
  const [data, setData] = useState<BotPresence | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!profile.discord_enabled || !profile.discord_id) return;
    let alive = true;
    let timer: number | undefined;
    const load = async () => {
      setLoading(true);
      try {
        const res = await fetch(`/api/discord/presence/${profile.discord_id}`, { cache: "no-store" });
        const json = await res.json();
        if (alive) setData(json);
        if (res.status === 404 && timer !== undefined) {
          window.clearInterval(timer);
          timer = undefined;
        }
      } catch {
        if (alive) setData({ ok: false, error: "Presence API offline" });
      } finally {
        if (alive) setLoading(false);
      }
    };
    load();
    timer = window.setInterval(load, 15000);
    return () => {
      alive = false;
      if (timer !== undefined) window.clearInterval(timer);
    };
  }, [profile.discord_enabled, profile.discord_id]);

  const status = data?.status || "offline";
  const avatar = data?.user?.avatar_url || "https://cdn.discordapp.com/embed/avatars/0.png";
  const name = data?.user?.global_name || data?.user?.username || "Discord user";
  const currentActivity = data?.activities?.find((activity) => activity.type !== 4);
  const customStatus = data?.activities?.find((activity) => activity.type === 4 && activity.state);
  const nitroBadge = profile.discord_premium_type && profile.discord_premium_type > 0
    ? [{ id: "discord-nitro", name: "Discord Nitro", icon: "💎", monoIcon: "◆", enabled: true }]
    : [];
  const serverBoosterBadge = data?.member?.server_booster
    ? [{ id: "discord-server-booster", name: "Server Booster", icon: "🚀", monoIcon: "✦", enabled: true }]
    : [];
  const discordBadges = [
    ...badgesFromDiscordPublicFlags(data?.user?.public_badges || []),
    ...nitroBadge,
    ...serverBoosterBadge,
  ];

  if (!profile.discord_enabled) return null;

  if (!profile.discord_id) {
    return (
      <a href={invite} target="_blank" rel="noreferrer" style={{ ...card(accent), display: "flex", alignItems: "center", gap: 14, color: "#580404", textDecoration: "none" }}>
        <div style={{ width: 52, height: 52, borderRadius: "50%", background: `${accent}22`, border: `1px solid ${accent}55`, display: "grid", placeItems: "center" }}>
          <MessageCircle size={25} style={{ color: accent }} />
        </div>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontWeight: 900, fontSize: 16 }}>Connect Discord activity</div>
          <div style={{ fontSize: 13, color: "#3a0606" }}>Join the community and connect Discord to show your status.</div>
        </div>
        <ExternalLink size={15} style={{ color: "#200606" }} />
      </a>
    );
  }

  if (!data?.ok || !data.joined) {
    return (
      <a href={invite} target="_blank" rel="noreferrer" style={{ ...card(accent), display: "flex", alignItems: "center", gap: 14, textDecoration: "none", color: "#580404" }}>
        <WifiOff size={27} style={{ color: accent }} />
        <div style={{ minWidth: 0 }}>
          <div style={{ fontWeight: 900 }}>{loading ? "Checking Discord..." : "Join Discord to show your status"}</div>
          <div style={{ fontSize: 13, color: "#3a0606" }}>{data?.error || "Join the community server and your activity can appear here."}</div>
        </div>
      </a>
    );
  }

  return (
    <div style={{ ...card(accent), display: "flex", alignItems: "center", justifyContent: "center", gap: 14, color: "#580404", width: "100%" }}>
      <div style={{ position: "relative", width: 62, height: 62, flex: "0 0 auto", display: "grid", placeItems: "center" }}>
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img src={avatar} alt="" style={{ width: 54, height: 54, borderRadius: "50%", objectFit: "cover", display: "block", position: "absolute", left: "50%", top: "50%", transform: "translate(-50%, -50%)" }} />
        {data.user?.avatar_decoration_url && (
          // eslint-disable-next-line @next/next/no-img-element
          <img
            src={data.user.avatar_decoration_url}
            alt=""
            style={{
              position: "absolute",
              left: "50%",
              top: "50%",
              transform: "translate(-50%, -50%)",
              width: 65,
              height: 65,
              maxWidth: "none",
              maxHeight: "none",
              objectFit: "contain",
              pointerEvents: "none",
              zIndex: 2,
            }}
          />
        )}
        <span style={{ position: "absolute", right: 3, bottom: 4, width: 16, height: 16, borderRadius: "50%", background: STATUS_COLOR[status] || STATUS_COLOR.offline, border: "3px solid #0d0d13", zIndex: 3 }} />
      </div>
      <div style={{ textAlign: "left", minWidth: 0, flex: 1 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <strong style={{ fontSize: 16, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{name}</strong>
          <span style={{ fontSize: 11, textTransform: "uppercase", color: STATUS_COLOR[status] || STATUS_COLOR.offline, fontWeight: 900 }}>{status}</span>
        </div>
        <div style={{ display: "grid", gap: 4, minWidth: 0, marginTop: 4 }}>
          {currentActivity && (
            <div style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 13, color: "#3a0606", minWidth: 0 }}>
              {activityIcon(currentActivity.type)}
              <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{activityText(data)}</span>
            </div>
          )}
          {customStatus?.state && (
            <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 13, color: "#3a0606", minWidth: 0 }}>
              {customStatus.emoji_url ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img src={customStatus.emoji_url} alt={customStatus.emoji || ""} style={{ width: 16, height: 16, objectFit: "contain" }} />
              ) : customStatus.emoji ? <span>{customStatus.emoji}</span> : null}
              <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{customStatus.state}</span>
            </div>
          )}
          {!currentActivity && !customStatus?.state && (
            <div style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 13, color: "#3a0606" }}>
              {activityIcon()}
              <span>{activityText(data)}</span>
            </div>
          )}
          {discordBadges.length > 0 && (
            <div aria-label="Discord account badges" style={{ display: "flex", alignItems: "center", gap: 7, flexWrap: "wrap", marginTop: 2 }}>
              {discordBadges.map((badge) => (
                <span key={badge.id} title={badge.name} aria-label={badge.name} style={{ display: "inline-grid", placeItems: "center", width: 18, height: 18 }}>
                  <BadgeIcon
                    badge={badge}
                    monochrome={profile.monochrome_icons !== false}
                    color={profile.icon_color || "#000000"}
                    glow={profile.badges_glow !== false}
                    size={16}
                  />
                </span>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
