"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { Avatar, Button, useToast } from "@/components/ui";
import { api } from "@/lib/api-client";
import { formatCount, formatDate } from "@/lib/format";
import type { LiveStream } from "@/db/schema";

type StreamWithChannel = LiveStream & { channel: { name: string; handle: string; avatarUrl: string | null } };

export function LiveBrowser({ live, scheduled, ended, canCreate }: { live: StreamWithChannel[]; scheduled: StreamWithChannel[]; ended: StreamWithChannel[]; canCreate: boolean }) {
  const router = useRouter();
  const { toast, toastNode } = useToast();
  const [tab, setTab] = useState<"live" | "scheduled" | "ended">("live");
  const [creating, setCreating] = useState(false);
  const [form, setForm] = useState({ title: "", description: "", categorySlug: "gaming", scheduledFor: "", playbackUrl: "" });

  const create = async (startNow: boolean) => {
    const payload: Record<string, unknown> = {
      title: form.title,
      description: form.description,
      categorySlug: form.categorySlug,
      startNow,
    };
    if (!startNow && form.scheduledFor) payload.scheduledFor = new Date(form.scheduledFor).toISOString();
    if (form.playbackUrl) payload.playbackUrl = form.playbackUrl;
    const data = await api<{ stream: LiveStream }>("/api/live", { method: "POST", json: payload }).catch((e) => {
      toast(e.message);
      return null;
    });
    if (data) {
      toast(startNow ? "You are live!" : "Stream scheduled");
      setCreating(false);
      router.push(`/live/${data.stream.id}`);
    }
  };

  const streams = tab === "live" ? live : tab === "scheduled" ? scheduled : ended;

  return (
    <div className="mt-5">
      <div className="flex flex-wrap items-center gap-2">
        {(["live", "scheduled", "ended"] as const).map((key) => (
          <button key={key} onClick={() => setTab(key)} className={`rounded-full px-4 py-1.5 text-sm font-semibold capitalize ${tab === key ? "bg-fg text-bg" : "bg-chip"}`}>
            {key === "live" ? `🔴 Live (${live.length})` : key === "scheduled" ? `Scheduled (${scheduled.length})` : `Replays (${ended.length})`}
          </button>
        ))}
        {canCreate ? (
          <Button className="ml-auto" onClick={() => setCreating((v) => !v)}>
            🎥 Create stream
          </Button>
        ) : null}
      </div>

      {creating ? (
        <div className="mt-4 space-y-3 rounded-xl border border-line p-4">
          <input value={form.title} onChange={(event) => setForm({ ...form, title: event.target.value })} placeholder="Stream title" className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm" />
          <textarea value={form.description} onChange={(event) => setForm({ ...form, description: event.target.value })} rows={2} placeholder="Description" className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm" />
          <div className="grid gap-3 sm:grid-cols-3">
            <input value={form.categorySlug} onChange={(event) => setForm({ ...form, categorySlug: event.target.value })} placeholder="Category slug" className="rounded-lg border border-line bg-surface px-3 py-2 text-sm" />
            <input value={form.scheduledFor} onChange={(event) => setForm({ ...form, scheduledFor: event.target.value })} type="datetime-local" className="rounded-lg border border-line bg-surface px-3 py-2 text-sm" />
            <input value={form.playbackUrl} onChange={(event) => setForm({ ...form, playbackUrl: event.target.value })} placeholder="Playback HLS URL (optional)" className="rounded-lg border border-line bg-surface px-3 py-2 text-sm" />
          </div>
          <div className="flex gap-2">
            <Button size="sm" onClick={() => void create(true)} disabled={!form.title.trim()}>Go live now</Button>
            <Button size="sm" variant="secondary" onClick={() => void create(false)} disabled={!form.title.trim()}>Schedule</Button>
          </div>
          <p className="text-xs text-muted">
            Push RTMP to <code className="rounded bg-chip px-1">rtmp://your-ingest/playtube</code> with your stream key from the stream page, or paste an HLS URL above.
          </p>
        </div>
      ) : null}

      <div className="mt-6 grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
        {streams.length === 0 ? <p className="text-sm text-muted">Nothing here yet.</p> : null}
        {streams.map((stream) => (
          <div key={stream.id} className="space-y-2">
            <Link href={`/live/${stream.id}`} className="block">
              <div className="relative aspect-video overflow-hidden rounded-xl bg-surface">
                {stream.thumbnailUrl ? (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img src={stream.thumbnailUrl} alt="" className="h-full w-full object-cover" />
                ) : (
                  <div className="grid h-full place-items-center text-3xl">📡</div>
                )}
                {stream.status === "live" ? (
                  <span className="absolute left-2 top-2 flex items-center gap-1 rounded bg-brand px-2 py-0.5 text-[11px] font-bold text-white">
                    <span className="h-1.5 w-1.5 rounded-full bg-white live-dot" /> LIVE
                  </span>
                ) : null}
                <span className="absolute bottom-2 right-2 rounded bg-black/80 px-1.5 py-0.5 text-[11px] text-white">
                  {stream.status === "live" ? `${formatCount(stream.currentViewers)} watching` : stream.status === "scheduled" ? formatDate(stream.scheduledFor ?? stream.createdAt) : `peak ${formatCount(stream.peakViewers)}`}
                </span>
              </div>
            </Link>
            <div className="flex gap-3">
              <Avatar name={stream.channel.name} src={stream.channel.avatarUrl} size={36} />
              <div className="min-w-0">
                <Link href={`/live/${stream.id}`} className="line-clamp-2 text-sm font-semibold">{stream.title}</Link>
                <Link href={`/channel/${stream.channel.handle}`} className="text-xs text-muted hover:text-fg">{stream.channel.name}</Link>
              </div>
            </div>
          </div>
        ))}
      </div>
      {toastNode}
    </div>
  );
}
