"use client";

import { usePoll } from "@/lib/use-poll";
import type { JellyfinStatus } from "@/lib/types";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { StatusBadge } from "./status-badge";
import { CardSkeleton } from "@/components/skeleton";
import { EmptyState } from "@/components/empty-state";

export function JellyfinCard() {
  const { data } = usePoll<JellyfinStatus>("/api/jellyfin/status", 30000);

  return (
    <Card>
      <CardHeader className="pb-2">
        <CardTitle className="text-base font-semibold">Jellyfin</CardTitle>
      </CardHeader>
      <CardContent className="space-y-3">
        {!data ? (
          <CardSkeleton lines={4} />
        ) : (
          <>
            <div>
              <p className="text-xs uppercase tracking-wider text-muted-foreground/70 mb-1.5">
                Now Playing
              </p>
              {data.active_sessions.length > 0 ? (
                <div className="space-y-2">
                  {data.active_sessions.map((s, i) => (
                    <div key={i} className="text-sm rounded-lg bg-white/[0.03] px-3 py-2">
                      <p className="text-foreground font-medium">{s.title}</p>
                      <p className="text-sm text-muted-foreground/70">
                        {s.user} &middot; {s.device}
                      </p>
                    </div>
                  ))}
                </div>
              ) : (
                <EmptyState icon={">"} title="Nothing playing" description="Start something on Jellyfin" />
              )}
            </div>
            <div className="h-px bg-white/[0.06]" />
            <div>
              <p className="text-xs uppercase tracking-wider text-muted-foreground/70 mb-1.5">
                Libraries
              </p>
              <div className="space-y-1">
                {data.libraries.map((lib) => (
                  <div
                    key={lib.name}
                    className="flex items-center justify-between text-sm"
                  >
                    <span className="text-foreground">{lib.name}</span>
                    <StatusBadge color="green" label={lib.type} />
                  </div>
                ))}
              </div>
            </div>
            {data.idle_sessions > 0 && (
              <p className="text-xs text-muted-foreground/60">
                {data.idle_sessions} idle session
                {data.idle_sessions > 1 ? "s" : ""}
              </p>
            )}
          </>
        )}
      </CardContent>
    </Card>
  );
}
