"use client";

import { useState, useMemo } from "react";
import { useApi } from "@/lib/api";
import { VideoPlayer, type VideoSource } from "../video-player";
import { Spinner, EmptyState } from "../skeleton";
import { cn } from "@/lib/utils";
import { toPersianDigits, formatViews } from "@/lib/poster";
import { Search, Radio, Users, Tv, Star } from "lucide-react";

interface Channel {
  id: string; slug: string; name: string; persianName: string;
  logoColors: [string, string]; streamUrl: string; quality: string;
  status: string; category: { name: string; persianName: string; slug: string } | null;
  country?: { name: string; persianName: string } | null;
  nowPlaying?: string | null; nextProgram?: string | null; viewers: number;
}
interface LiveData { categories: { id: string; name: string; slug: string; persianName: string }[]; channels: Channel[]; }

export function LiveView() {
  const { data, loading } = useApi<LiveData>("/api/live/channels");
  const [selected, setSelected] = useState<Channel | null>(null);
  const [cat, setCat] = useState<string>("");
  const [q, setQ] = useState("");

  const filtered = useMemo(() => {
    if (!data) return [];
    return data.channels.filter((c) =>
      (!cat || c.category?.slug === cat) &&
      (!q || c.persianName.includes(q) || c.name.toLowerCase().includes(q.toLowerCase()))
    );
  }, [data, cat, q]);

  if (loading || !data) return <div className="h-[60vh] flex items-center justify-center"><Spinner /></div>;

  const current = selected ?? filtered[0];
  const sources: VideoSource[] = current ? [{ quality: current.quality, url: current.streamUrl, isHls: true }] : [];

  return (
    <div className="px-4 md:px-8 py-6">
      <h1 className="text-2xl md:text-3xl font-black flex items-center gap-3 mb-6">
        <span className="h-8 w-1.5 rounded-full bg-destructive" />
        <Radio className="h-7 w-7 text-destructive animate-pulse" />
        تلویزیون زنده
      </h1>

      {/* Player */}
      {current && (
        <div className="mb-6">
          <div className="aspect-video rounded-2xl overflow-hidden bg-black">
            <VideoPlayer
              sources={sources}
              title={current.persianName}
              gradient={current.logoColors}
            />
          </div>
          <div className="mt-3 flex items-center justify-between flex-wrap gap-2">
            <div className="flex items-center gap-3">
              <div className="flex h-12 w-12 items-center justify-center rounded-xl text-white font-black" style={{ background: `linear-gradient(135deg, ${current.logoColors[0]}, ${current.logoColors[1]})` }}>
                {current.persianName.charAt(0)}
              </div>
              <div>
                <div className="font-bold">{current.persianName}</div>
                <div className="text-xs text-muted-foreground flex items-center gap-2">
                  <span className="inline-flex items-center gap-1 text-success"><span className="h-1.5 w-1.5 rounded-full bg-success animate-pulse" /> زنده</span>
                  {current.nowPlaying && <span>• {current.nowPlaying}</span>}
                </div>
              </div>
            </div>
            <div className="flex items-center gap-4 text-xs text-muted-foreground">
              <span className="flex items-center gap-1"><Users className="h-3.5 w-3.5" /> {formatViews(current.viewers)} بیننده</span>
              <span className="rounded bg-white/10 px-2 py-0.5">{current.quality === "2160p" ? "4K" : current.quality}</span>
            </div>
          </div>
        </div>
      )}

      {/* Search + filters */}
      <div className="flex flex-col md:flex-row gap-3 mb-6">
        <div className="flex items-center glass rounded-xl px-3 py-2 flex-1">
          <Search className="h-4 w-4 text-muted-foreground ml-2" />
          <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="جستجوی شبکه..." className="bg-transparent flex-1 px-2 text-sm outline-none placeholder:text-muted-foreground" />
        </div>
        <div className="flex gap-1.5 overflow-x-auto hide-scrollbar">
          <button onClick={() => setCat("")} className={cn("shrink-0 rounded-full px-3 py-1.5 text-xs font-medium transition", !cat ? "bg-primary text-white" : "glass text-muted-foreground hover:text-white")}>همه</button>
          {data.categories.map((c) => (
            <button key={c.id} onClick={() => setCat(c.slug)} className={cn("shrink-0 rounded-full px-3 py-1.5 text-xs font-medium transition", cat === c.slug ? "bg-primary text-white" : "glass text-muted-foreground hover:text-white")}>{c.persianName}</button>
          ))}
        </div>
      </div>

      {/* Channels grid */}
      {filtered.length === 0 ? (
        <EmptyState icon={Tv} title="شبکه‌ای یافت نشد" />
      ) : (
        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3 md:gap-4">
          {filtered.map((ch) => (
            <button
              key={ch.id}
              onClick={() => setSelected(ch)}
              className={cn("group relative rounded-xl overflow-hidden glass p-3 hover:scale-[1.03] transition text-right", current?.id === ch.id && "ring-2 ring-primary")}
            >
              <div className="flex items-center gap-2 mb-2">
                <div className="flex h-10 w-10 items-center justify-center rounded-lg text-white font-black text-sm shrink-0" style={{ background: `linear-gradient(135deg, ${ch.logoColors[0]}, ${ch.logoColors[1]})` }}>
                  {ch.persianName.charAt(0)}
                </div>
                <div className="min-w-0 flex-1">
                  <div className="text-sm font-bold truncate">{ch.persianName}</div>
                  <div className="text-[10px] text-muted-foreground truncate">{ch.category?.persianName}</div>
                </div>
              </div>
              <div className="flex items-center justify-between text-[10px] text-muted-foreground">
                <span className="inline-flex items-center gap-1 text-success"><span className="h-1.5 w-1.5 rounded-full bg-success animate-pulse" /> زنده</span>
                <span className="flex items-center gap-1"><Users className="h-2.5 w-2.5" /> {formatViews(ch.viewers)}</span>
              </div>
              {ch.nowPlaying && <div className="mt-1.5 text-[10px] text-white/70 truncate">▶ {ch.nowPlaying}</div>}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
