"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { Button, EmptyState, useToast } from "@/components/ui";
import { useSession } from "@/components/session-provider";
import { api } from "@/lib/api-client";
import type { Playlist } from "@/db/schema";

export default function PlaylistsPage() {
  const { user } = useSession();
  const { toast, toastNode } = useToast();
  const [items, setItems] = useState<Playlist[] | null>(null);
  const [title, setTitle] = useState("");
  const [visibility, setVisibility] = useState<"public" | "private" | "unlisted">("public");
  const [collaborative, setCollaborative] = useState(false);

  const load = async () => {
    const data = await api<{ items: Playlist[] }>("/api/playlists").catch(() => null);
    setItems(data?.items ?? []);
  };

  useEffect(() => {
    if (user) void load();
    else setItems([]);
  }, [user]);

  const create = async () => {
    if (!title.trim()) return;
    await api("/api/playlists", { method: "POST", json: { title, visibility, isCollaborative: collaborative } }).catch((e) => toast(e.message));
    setTitle("");
    await load();
    toast("Playlist created");
  };

  return (
    <div className="mx-auto max-w-5xl px-4 py-6">
      <h1 className="text-2xl font-bold">Your playlists</h1>
      {user ? (
        <div className="mt-4 flex flex-wrap items-center gap-2 rounded-xl border border-line p-3">
          <input value={title} onChange={(event) => setTitle(event.target.value)} placeholder="New playlist title" className="min-w-[200px] flex-1 rounded-lg border border-line bg-surface px-3 py-2 text-sm" />
          <select value={visibility} onChange={(event) => setVisibility(event.target.value as typeof visibility)} className="rounded-lg border border-line bg-surface px-3 py-2 text-sm">
            <option value="public">Public</option>
            <option value="unlisted">Unlisted</option>
            <option value="private">Private</option>
          </select>
          <label className="flex items-center gap-2 text-sm">
            <input type="checkbox" checked={collaborative} onChange={(event) => setCollaborative(event.target.checked)} />
            Collaborative
          </label>
          <Button onClick={() => void create()}>Create</Button>
        </div>
      ) : (
        <p className="mt-3 text-sm text-muted">
          <Link href="/login" className="font-semibold text-brand">Sign in</Link> to build playlists.
        </p>
      )}

      <div className="mt-6 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {items === null
          ? Array.from({ length: 4 }).map((_, i) => <div key={i} className="skeleton aspect-video rounded-xl" />)
          : items.map((playlist) => (
              <Link key={playlist.id} href={`/playlist/${playlist.id}`} className="group">
                <div className="aspect-video overflow-hidden rounded-xl bg-surface">
                  {playlist.thumbnailUrl ? (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img src={playlist.thumbnailUrl} alt="" className="h-full w-full object-cover" />
                  ) : (
                    <div className="grid h-full place-items-center text-3xl">📁</div>
                  )}
                </div>
                <p className="mt-2 text-sm font-semibold">{playlist.title}</p>
                <p className="text-xs text-muted">
                  {playlist.itemCount} videos · {playlist.visibility}
                  {playlist.isCollaborative ? " · collaborative" : ""}
                </p>
              </Link>
            ))}
      </div>

      {items !== null && items.length === 0 ? (
        <EmptyState icon="📁" title="No playlists yet" hint="Create your first playlist and add videos from any card menu." />
      ) : null}
      {toastNode}
    </div>
  );
}
