"use client";

import Link from "next/link";
import { useCallback, useEffect, useMemo, useState } from "react";
import { ArrowLeft, ArrowRight, ExternalLink, Radio, ShieldCheck, UsersRound } from "lucide-react";
import type { CommunityStreamerResponse } from "../lib/streamers";

const EMPTY: CommunityStreamerResponse = {
  ok: true,
  configured: false,
  count: 0,
  liveCount: 0,
  streamers: [],
};

export default function StreamerLiveShowcase() {
  const [data, setData] = useState<CommunityStreamerResponse>(EMPTY);
  const [index, setIndex] = useState(0);

  const load = useCallback(async () => {
    try {
      const response = await fetch("/api/streamers", { cache: "no-store" });
      const payload: CommunityStreamerResponse = await response.json();
      setData(payload);
    } catch {
      setData((current) => ({ ...current, ok: false }));
    }
  }, []);

  useEffect(() => {
    load();
    const timer = window.setInterval(load, 60_000);
    return () => window.clearInterval(timer);
  }, [load]);

  const live = useMemo(() => data.streamers.filter((streamer) => streamer.isLive), [data.streamers]);

  useEffect(() => {
    if (index >= live.length) setIndex(0);
  }, [index, live.length]);

  const current = live[index];
  const previous = () => setIndex((value) => (value - 1 + live.length) % live.length);
  const next = () => setIndex((value) => (value + 1) % live.length);

  return (
    <div className="live-window">
      <div className="live-window-bar">
        <span><i/> BEXOGAMES LIVE</span>
        <span><ShieldCheck size={14}/> COMMUNITY VERIFIED</span>
      </div>

      {current ? (
        <div className="live-stream-card">
          <div className="live-stream-preview">
            {current.thumbnailUrl && <img src={current.thumbnailUrl} alt={`Livestream von ${current.twitchDisplayName}`} />}
            <div className="live-stream-shade" />
            <div className="live-badge"><span/> LIVE</div>
            {current.viewerCount !== null && <div className="viewer-badge"><UsersRound size={14}/>{current.viewerCount.toLocaleString("de-DE")}</div>}
          </div>
          <div className="live-stream-info">
            <div className="live-stream-person">
              {current.profileImageUrl ? <img src={current.profileImageUrl} alt="" /> : <div className="streamer-avatar-fallback"><Radio size={20}/></div>}
              <div><small>{current.gameName || "Twitch"}</small><h3>{current.twitchDisplayName}</h3></div>
            </div>
            <p>{current.title || "BexoGames ist live auf Twitch."}</p>
            <div className="live-stream-actions">
              <a href={current.twitchUrl} target="_blank" rel="noopener noreferrer" className="button primary">Auf Twitch ansehen <ExternalLink size={16}/></a>
              <Link href="/streamer" className="button secondary">Alle Streamer</Link>
              {live.length > 1 && (
                <div className="live-carousel-controls" aria-label="Weitere Livestreams">
                  <button type="button" onClick={previous} aria-label="Vorheriger Stream"><ArrowLeft size={18}/></button>
                  <span>{index + 1} / {live.length}</span>
                  <button type="button" onClick={next} aria-label="Nächster Stream"><ArrowRight size={18}/></button>
                </div>
              )}
            </div>
          </div>
        </div>
      ) : (
        <div className="live-window-body">
          <div className="live-pulse"><Radio size={35}/></div>
          <h3>Gerade niemand live.</h3>
          <p>{data.configured ? "Sobald ein verifizierter BexoGames-Streamer startet, erscheint der Stream automatisch hier." : "Die Twitch-Anbindung ist noch nicht vollständig konfiguriert."}</p>
          <div className="live-rule"><span>DISCORD MEMBER</span><ArrowRight size={14}/><span>STREAMER ROLE</span><ArrowRight size={14}/><b>TWITCH LIVE</b></div>
          <Link href="/streamer" className="live-directory-link">Unsere Streamer ansehen <ArrowRight size={15}/></Link>
        </div>
      )}
    </div>
  );
}
