"use client";

import { useEffect, useState, useSyncExternalStore } from "react";
import { createTvPlayerRuntimeCore } from "@/lib/tvs-player-runtime-core";
import type { ScreenManifest } from "@/lib/tvs-runtime";

type ScreenPlayerProps = {
  screenId: string;
  initialManifest: ScreenManifest;
};

export function ScreenPlayer({ screenId, initialManifest }: ScreenPlayerProps) {
  const [runtime] = useState(() =>
    createTvPlayerRuntimeCore({
      screenId,
      initialManifest,
    })
  );

  const snapshot = useSyncExternalStore(runtime.subscribe, runtime.getSnapshot, runtime.getSnapshot);
  const networkStatus = useSyncExternalStore(
    (callback) => {
      window.addEventListener("online", callback);
      window.addEventListener("offline", callback);
      return () => {
        window.removeEventListener("online", callback);
        window.removeEventListener("offline", callback);
      };
    },
    () => (navigator.onLine ? "online" : "offline"),
    () => "pending"
  );

  useEffect(() => {
    void runtime.syncCachedMedia();
  }, [runtime]);

  useEffect(() => {
    void runtime.sendHeartbeat();

    const interval = window.setInterval(() => {
      void runtime.sendHeartbeat();
    }, 30000);

    return () => {
      window.clearInterval(interval);
    };
  }, [runtime]);

  useEffect(() => {
    const interval = window.setInterval(() => {
      void runtime.refreshManifest();
    }, 60000);

    return () => window.clearInterval(interval);
  }, [runtime]);

  useEffect(() => {
    if (snapshot.manifest.creatives.length <= 1) {
      return;
    }

    const activeCreative = runtime.getActiveCreative();
    if (!activeCreative) {
      return;
    }

    const timeout = window.setTimeout(() => {
      runtime.rotateToNextCreative();
    }, Math.max(activeCreative.duration, 5) * 1000);

    return () => window.clearTimeout(timeout);
  }, [runtime, snapshot.activeIndex, snapshot.manifest]);

  useEffect(() => {
    void runtime.flushQueue();

    const activeCreative = runtime.getActiveCreative();
    const timeout = activeCreative
      ? window.setTimeout(() => {
          void runtime.queueImpressionForCreative(activeCreative.id);
        }, 1500)
      : null;

    const interval = window.setInterval(() => {
      void runtime.flushQueue();
    }, 15000);

    const handleOnline = () => {
      void runtime.flushQueue();
    };

    window.addEventListener("online", handleOnline);

    return () => {
      if (timeout) {
        window.clearTimeout(timeout);
      }
      window.clearInterval(interval);
      window.removeEventListener("online", handleOnline);
    };
  }, [runtime, snapshot.activeIndex, snapshot.manifest]);

  useEffect(() => {
    return () => {
      runtime.disposeRuntime();
    };
  }, [runtime]);

  const activeCreative = runtime.getActiveCreative();
  const activeSource = snapshot.mediaSyncPending
    ? "pending"
    : activeCreative && snapshot.cachedMediaSources[activeCreative.id]
      ? "blob"
      : "remote";

  if (!activeCreative) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-[#10130e] text-foreground">
        <div className="rounded-[2rem] border border-border/70 bg-card/90 px-8 py-10 text-center">
          <p className="text-xs uppercase tracking-[0.24em] text-primary">Screen runtime</p>
          <h1 className="mt-3 text-3xl font-semibold">Sin creatives asignadas</h1>
          <p className="mt-3 text-sm text-muted-foreground">La pantalla {screenId} no tiene contenido activo.</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-black text-white">
      <div className="grid min-h-screen lg:grid-cols-[1fr_360px]">
        <div className="relative flex min-h-[60vh] items-center justify-center overflow-hidden bg-black">
          <video
            key={activeCreative.id}
            src={snapshot.cachedMediaSources[activeCreative.id] ?? runtime.normalizeCreativeUrl(activeCreative.url)}
            autoPlay
            muted
            loop
            playsInline
            controls
            onError={() => {
              runtime.rotateToNextCreative();
            }}
            className="h-full w-full object-contain"
          />
          <div className="absolute left-6 top-6 rounded-full border border-white/20 bg-black/55 px-4 py-2 text-sm backdrop-blur">
            {screenId}
          </div>
        </div>

        <aside className="flex flex-col justify-between border-l border-white/10 bg-[linear-gradient(180deg,#141813,#0c0f0b)] p-6">
          <div>
            <p className="text-xs uppercase tracking-[0.24em] text-[#c4d600]">Now playing</p>
            <h1 className="mt-3 text-3xl font-semibold leading-tight">{activeCreative.campaignName}</h1>
            <p className="mt-3 text-sm text-white/65">Creative {snapshot.activeIndex + 1} de {snapshot.manifest.creatives.length}</p>

            <div className="mt-6 rounded-3xl border border-white/10 bg-white/5 p-4">
              <p className="text-xs uppercase tracking-[0.2em] text-white/45">Manifest</p>
              <p className="mt-3 text-sm text-white/80">Version: {snapshot.manifest.version}</p>
              <p className="mt-2 text-sm text-white/60">Generated: {new Date(snapshot.manifest.generatedAt).toLocaleString("es-AR")}</p>
              <p className="mt-2 text-sm text-white/60">Duration: {activeCreative.duration}s</p>
              <p className="mt-2 text-sm text-white/60">Playback: {snapshot.runtimeMode}</p>
              <p className="mt-2 text-sm text-white/60">Active source: {activeSource}</p>
              <p className="mt-2 text-sm text-white/60">Cache API: {snapshot.cacheApiAvailable ? "available" : "unavailable"}</p>
              <p className="mt-2 text-sm text-white/60">Cached creatives: {snapshot.cachedCreativeCount}</p>
              <p className="mt-2 text-sm text-white/60">Network: {networkStatus}</p>
              <p className="mt-2 text-sm text-white/60">
                Manifest refresh: {snapshot.lastManifestRefreshStatus}
                {snapshot.lastManifestRefreshAt ? ` (${new Date(snapshot.lastManifestRefreshAt).toLocaleString("es-AR")})` : ""}
              </p>
              <p className="mt-2 text-sm text-white/60">Last heartbeat: {snapshot.lastHeartbeatAt ? new Date(snapshot.lastHeartbeatAt).toLocaleString("es-AR") : "pending"}</p>
              <p className="mt-2 text-sm text-white/60">Last impression: {snapshot.lastImpressionId ?? "pending"}</p>
              <p className="mt-2 text-sm text-white/60">Queued impressions: {snapshot.queuedImpressions}</p>
            </div>
          </div>

          <div className="space-y-3">
            {snapshot.manifest.creatives.map((creative, index) => {
              const active = creative.id === activeCreative.id;
              return (
                <button
                  key={creative.id}
                  type="button"
                  onClick={() => runtime.setActiveIndex(index)}
                  className={`w-full rounded-2xl border px-4 py-3 text-left transition ${
                    active
                      ? "border-[#c4d600] bg-[#c4d600]/12 text-white"
                      : "border-white/10 bg-white/5 text-white/70 hover:border-white/25"
                  }`}
                >
                  <p className="font-medium">{creative.campaignName}</p>
                  <p className="mt-1 text-xs uppercase tracking-[0.16em] text-white/45">{creative.id}</p>
                </button>
              );
            })}
          </div>
        </aside>
      </div>
    </div>
  );
}
