import { useEffect, useMemo, useRef, useState } from "react";
import { Maximize, RefreshCcw } from "lucide-react";
import { useWhepPlayer } from "@/hooks/useWhepPlayer";

type Props = {
  name: string;
  webrtcBaseUrl: string;
  isOnline: boolean;
};

function StatusDot({ online }: { online: boolean }) {
  return (
    <span
      className={[
        "inline-flex h-2.5 w-2.5 rounded-full",
        online ? "bg-emerald-400" : "bg-rose-400",
      ].join(" ")}
      aria-label={online ? "online" : "offline"}
      title={online ? "online" : "offline"}
    />
  );
}

export default function CameraTile({ name, webrtcBaseUrl, isOnline }: Props) {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const el = containerRef.current;
    if (!el) return;

    const io = new IntersectionObserver(
      (entries) => {
        const entry = entries[0];
        setVisible(Boolean(entry?.isIntersecting));
      },
      { threshold: 0.2 }
    );

    io.observe(el);
    return () => io.disconnect();
  }, []);

  const enabled = useMemo(() => visible, [visible]);
  const player = useWhepPlayer({ enabled, webrtcBaseUrl, streamName: name });

  const onFullscreen = async () => {
    const v = player.videoRef.current;
    if (!v) return;
    const anyV = v as HTMLVideoElement & { webkitRequestFullscreen?: () => Promise<void> | void };
    if (v.requestFullscreen) await v.requestFullscreen();
    else if (anyV.webkitRequestFullscreen) anyV.webkitRequestFullscreen();
  };

  return (
    <div
      ref={containerRef}
      className="group relative overflow-hidden rounded-lg border border-zinc-800 bg-zinc-900/30"
    >
      <div className="absolute left-0 top-0 z-10 flex w-full items-center justify-between gap-2 bg-gradient-to-b from-zinc-950/80 to-transparent px-3 py-2">
        <div className="flex items-center gap-2">
          <StatusDot online={isOnline} />
          <div className="text-xs font-medium text-zinc-100">{name}</div>
          <div className="text-[11px] text-zinc-400">
            {player.status === "playing" ? "webrtc" : player.status}
          </div>
        </div>

        <div className="flex items-center gap-1 opacity-100 transition md:opacity-0 md:group-hover:opacity-100">
          <button
            type="button"
            onClick={player.restart}
            className="inline-flex h-8 w-8 items-center justify-center rounded-md border border-zinc-700 bg-zinc-950/40 text-zinc-200 transition hover:bg-zinc-900"
            title="Reload"
          >
            <RefreshCcw className="h-4 w-4" />
          </button>
          <button
            type="button"
            onClick={onFullscreen}
            className="inline-flex h-8 w-8 items-center justify-center rounded-md border border-zinc-700 bg-zinc-950/40 text-zinc-200 transition hover:bg-zinc-900"
            title="Fullscreen"
          >
            <Maximize className="h-4 w-4" />
          </button>
        </div>
      </div>

      <div className="aspect-video w-full bg-black">
        <video
          ref={player.videoRef}
          className="h-full w-full object-contain"
          muted
          playsInline
        />
      </div>

      {player.status === "error" ? (
        <div className="border-t border-zinc-800 px-3 py-2 text-xs text-rose-300">
          {player.error ?? "error"}
        </div>
      ) : null}
    </div>
  );
}

