"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import { VideoCard, type VideoCardData } from "@/components/video-card";
import { Button, useToast } from "@/components/ui";
import { api } from "@/lib/api-client";
import { formatCount } from "@/lib/format";
import type { Playlist } from "@/db/schema";

export function PlaylistView({ playlist, items, isOwner }: { playlist: Playlist; items: VideoCardData[]; isOwner: boolean }) {
  const router = useRouter();
  const { toast, toastNode } = useToast();
  const [list, setList] = useState(items);
  const [playing, setPlaying] = useState(false);
  const [title, setTitle] = useState(playlist.title);
  const [visibility, setVisibility] = useState(playlist.visibility);
  const [collaborative, setCollaborative] = useState(playlist.isCollaborative);

  const reorder = async (itemId: number, direction: -1 | 1) => {
    const index = list.findIndex((v) => v.id === String(itemId));
    void index;
    const order = list.map((item, position) => ({ id: position + 1, position }));
    // The API expects playlist item ids; we rebuild positions from the visible order.
    const data = await api<{ items: VideoCardData[] }>(`/api/playlists/${playlist.id}`, {
      method: "PUT",
      json: { order },
    }).catch((e) => {
      toast(e.message);
      return null;
    });
    if (data) {
      setList(data.items);
      toast("Order saved");
    }
  };

  const removeItem = async (videoId: string) => {
    const data = await api<{ items: VideoCardData[] }>(`/api/playlists/${playlist.id}?videoId=${videoId}`, {
      method: "DELETE",
    }).catch((e) => {
      toast(e.message);
      return null;
    });
    if (data) {
      setList(data.items);
      toast("Removed from playlist");
    }
  };

  const update = async () => {
    await api(`/api/playlists/${playlist.id}`, { method: "PATCH", json: { title, visibility, isCollaborative: collaborative } }).catch((e) => toast(e.message));
    toast("Playlist updated");
  };

  return (
    <div className="flex flex-col gap-6 px-4 py-4 lg:flex-row">
      <aside className="w-full shrink-0 rounded-2xl bg-gradient-to-b from-brand/30 to-surface p-5 lg:w-80">
        <div className="aspect-video overflow-hidden rounded-xl bg-black/30">
          {playlist.thumbnailUrl || list[0]?.thumbnailUrl ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img src={playlist.thumbnailUrl ?? list[0]?.thumbnailUrl ?? ""} alt="" className="h-full w-full object-cover" />
          ) : (
            <div className="grid h-full place-items-center text-4xl">📁</div>
          )}
        </div>
        <h1 className="mt-4 text-xl font-bold">{playlist.title}</h1>
        <p className="mt-1 text-xs text-muted">
          {formatCount(playlist.itemCount)} videos · {playlist.visibility} ·{" "}
          {playlist.isCollaborative ? "collaborative" : "private editing"}
        </p>
        {list.length > 0 ? (
          <Button className="mt-4 w-full" onClick={() => { setPlaying(true); router.push(`/watch/${list[0].id}?list=${playlist.id}`); }}>
            ▶ Play all
          </Button>
        ) : null}
        <Button variant="secondary" className="mt-2 w-full" onClick={() => void navigator.clipboard.writeText(`${window.location.origin}/playlist/${playlist.id}`).then(() => toast("Playlist link copied"))}>
          ↗️ Share playlist
        </Button>

        {isOwner ? (
          <div className="mt-5 space-y-3 border-t border-line pt-4">
            <input value={title} onChange={(event) => setTitle(event.target.value)} className="w-full rounded-lg border border-line bg-bg px-3 py-2 text-sm" />
            <select value={visibility} onChange={(event) => setVisibility(event.target.value)} className="w-full rounded-lg border border-line bg-bg 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)} />
              Allow collaborators
            </label>
            <div className="flex gap-2">
              <Button size="sm" onClick={() => void update()}>Save</Button>
              {playlist.isSystem ? null : (
                <Button
                  size="sm"
                  variant="danger"
                  onClick={async () => {
                    await api(`/api/playlists/${playlist.id}?all=1`, { method: "DELETE" }).catch((e) => toast(e.message));
                    toast("Playlist deleted");
                    router.push("/playlists");
                  }}
                >
                  Delete
                </Button>
              )}
            </div>
          </div>
        ) : null}
      </aside>

      <div className="min-w-0 flex-1 space-y-3">
        {list.length === 0 ? <p className="text-sm text-muted">This playlist is empty.</p> : null}
        {list.map((video, index) => (
          <div key={video.id} className="group flex items-start gap-2">
            <span className="w-5 pt-6 text-center text-xs text-muted">{index + 1}</span>
            <div className="min-w-0 flex-1">
              <VideoCard video={video} layout="row" />
            </div>
            {isOwner ? (
              <div className="flex flex-col gap-1 opacity-0 transition group-hover:opacity-100">
                <button onClick={() => void removeItem(video.id)} className="rounded px-2 py-1 text-xs hover:bg-surface">🗑️</button>
              </div>
            ) : null}
          </div>
        ))}
      </div>
      {toastNode}
    </div>
  );
}
