"use client";

import { useMemo, useState } from "react";
import { Pause, Play, Radio, SkipForward } from "lucide-react";
import { io } from "socket.io-client";
import { normalizeMediaUrl } from "@/lib/media";
import { StatusBadge } from "./status-badge";
import { Avatar } from "./avatar";
import { addMediaToRoom } from "@/lib/media-actions";

const socket = io({
  path: "/api/socket",
  autoConnect: false
});

type QueueItem = {
  id: string;
  title: string;
  provider: string;
  originalUrl: string;
  playbackUrl: string;
  by: string;
  createdAt: string;
};

type Participant = {
  id: string;
  name: string;
  role: string;
  status: string;
};

export function RoomConsole({
  roomId,
  roomSlug,
  currentUser,
  queue = [],
  participants = []
}: {
  roomId: string;
  roomSlug: string;
  currentUser: string;
  queue?: QueueItem[];
  participants?: Participant[];
}) {
  const [connected, setConnected] = useState(false);
  const [source, setSource] = useState("");
  const previewMedia = useMemo(() => (source ? normalizeMediaUrl(source) : null), [source]);
  const currentMedia = previewMedia || queue[0] || null;

  function connect() {
    if (!socket.connected) {
      socket.connect();
      socket.emit("room:join", { roomSlug, user: currentUser });
    }
    setConnected(true);
  }

  function emit(event: "media:set" | "playback:play" | "playback:pause" | "playback:seek") {
    connect();
    const media = previewMedia || queue[0];
    socket.emit(event, {
      provider: media?.provider,
      originalUrl: media?.originalUrl,
      playbackUrl: media?.playbackUrl,
      position: event === "playback:seek" ? 82 : undefined
    });
  }

  return (
    <div className="room-layout">
      <section className="panel">
        <div className="panel-header">
          <div>
            <h2>{roomSlug}</h2>
            <span className="eyebrow">Persistent room</span>
          </div>
          <StatusBadge tone={connected ? "good" : "warn"}>{connected ? "Online" : "Local preview"}</StatusBadge>
        </div>
        <div className="video-frame">
          {currentMedia ? (
            <MediaPreview
              provider={currentMedia.provider}
              playbackUrl={currentMedia.playbackUrl}
              title={currentMedia.title || currentMedia.originalUrl}
            />
          ) : (
            <div className="video-state">
              <StatusBadge>Idle</StatusBadge>
              <h2>No media queued</h2>
              <p>Add a YouTube, Twitch, or direct video URL to start this room.</p>
            </div>
          )}
        </div>
        <form className="controls" action={addMediaToRoom}>
          <input type="hidden" name="roomId" value={roomId} />
          <button className="button primary" type="button" onClick={() => emit("playback:play")}>
            <Play size={16} /> Play
          </button>
          <button className="button" type="button" onClick={() => emit("playback:pause")}>
            <Pause size={16} /> Pause
          </button>
          <input
            className="input"
            aria-label="Source URL"
            name="sourceUrl"
            value={source}
            onChange={(event) => setSource(event.target.value)}
            placeholder="Source URL"
          />
          <button className="button" type="submit" onClick={() => emit("media:set")} disabled={!source}>
            <Radio size={16} /> Add
          </button>
          <button className="button" type="button" onClick={() => emit("playback:seek")}>
            <SkipForward size={16} /> Seek
          </button>
        </form>
      </section>

      <aside className="stack">
        <Panel title="Queue">
          {queue.length === 0 ? (
            <div className="empty-state">No media queued yet.</div>
          ) : (
            queue.map((item) => (
              <div className="row" key={item.id}>
                <div className="row-title">
                  <strong>{item.title}</strong>
                  <span>
                    {item.provider} by {item.by}
                  </span>
                </div>
                <StatusBadge>{item.createdAt}</StatusBadge>
              </div>
            ))
          )}
        </Panel>
        <Panel title="Participants">
          {participants.length === 0 ? (
            <div className="empty-state">No participants listed yet.</div>
          ) : (
            participants.map((item) => (
              <div className="row" key={item.id}>
                <div className="row-main">
                  <Avatar name={item.name} />
                  <div className="row-title">
                    <strong>{item.name}</strong>
                    <span>{item.role}</span>
                  </div>
                </div>
                <StatusBadge tone={item.status === "Buffering" ? "warn" : "good"}>{item.status}</StatusBadge>
              </div>
            ))
          )}
        </Panel>
        <Panel title="Activity">
          {queue.length === 0 ? (
            <div className="empty-state">Room activity will appear after users add media.</div>
          ) : (
            queue.slice(0, 5).map((item) => (
              <div className="row" key={`activity-${item.id}`}>
                <div className="row-title">
                  <strong>{item.by} added {item.provider.toLowerCase()} media</strong>
                  <span>{item.createdAt}</span>
                </div>
              </div>
            ))
          )}
        </Panel>
      </aside>
    </div>
  );
}

function Panel({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <section className="panel">
      <div className="panel-header">
        <h3>{title}</h3>
      </div>
      <div className="panel-body">{children}</div>
    </section>
  );
}

function MediaPreview({ provider, playbackUrl, title }: { provider: string; playbackUrl: string; title: string }) {
  if (provider === "YOUTUBE" || provider === "TWITCH") {
    return (
      <iframe
        className="media-embed"
        src={playbackUrl}
        title={title}
        allow="autoplay; encrypted-media; fullscreen; picture-in-picture"
        allowFullScreen
      />
    );
  }

  if (provider === "DIRECT") {
    return <video className="media-embed" src={playbackUrl} controls playsInline />;
  }

  return (
    <div className="video-state">
      <StatusBadge tone="warn">Unsupported</StatusBadge>
      <h2>{title}</h2>
      <p>This URL is stored in the queue, but it cannot be embedded directly.</p>
      <p className="eyebrow">{playbackUrl}</p>
    </div>
  );
}
