import { useQuery, useQueryClient } from "@tanstack/react-query";
import { getQueue, toggleQueue } from "../api";
import VideoCard from "../components/VideoCard";

export default function QueuePage() {
  const qc = useQueryClient();
  const { data: videos = [], isLoading } = useQuery({
    queryKey: ["queue"],
    queryFn: () => getQueue().then((r) => r.data),
    staleTime: 30_000,
  });

  return (
    <div className="flex flex-col gap-6">
      <h1 className="font-display font-bold text-2xl text-zinc-100">Watch Later</h1>

      {isLoading ? (
        <div className="flex items-center justify-center py-24">
          <div className="w-8 h-8 border-2 border-accent border-t-transparent rounded-full animate-spin" />
        </div>
      ) : videos.length === 0 ? (
        <div className="flex flex-col items-center gap-4 py-24 text-center">
          <div className="w-16 h-16 rounded-full bg-zinc-800 flex items-center justify-center">
            <svg className="w-7 h-7 text-zinc-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
                d="M4 6h16M4 11h16M4 16h10m6-1l-4 2.5 4 2.5V15z" />
            </svg>
          </div>
          <div>
            <p className="text-zinc-500 text-sm">Queue is empty</p>
            <p className="text-zinc-500 text-sm mt-1">
              Hit the queue icon on any video to save it for later.
            </p>
          </div>
        </div>
      ) : (
        <>
          <p className="text-sm text-zinc-500 -mt-2">{videos.length} video{videos.length !== 1 ? "s" : ""} saved</p>
          <div className="flex flex-col gap-2">
            {videos.map((v) => (
              <VideoCard
                key={v.youtube_video_id}
                video={v}
                variant="list"
                onRemoveFromQueue={() => {
                  toggleQueue(v.id).then(() => qc.invalidateQueries({ queryKey: ["queue"] }));
                }}
              />
            ))}
          </div>
        </>
      )}
    </div>
  );
}
