"use client";
import { useState, useEffect, useCallback } from "react";
import type { Song, Playlist, QueueState } from "@/lib/types";

export function useMusic() {
  const [songs, setSongs] = useState<Song[]>([]);
  const [playlists, setPlaylists] = useState<Playlist[]>([]);
  const [queue, setQueue] = useState<QueueState | null>(null);
  const [selectedPlaylist, setSelectedPlaylist] = useState<(Playlist & { songs: Song[] }) | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [songSearch, setSongSearch] = useState("");

  const fetchSongs = useCallback(async (search?: string) => {
    try {
      const qs = search ? `?search=${encodeURIComponent(search)}` : "";
      const res = await fetch(`/api/music/songs${qs}`);
      if (!res.ok) throw new Error("Failed to fetch songs");
      setSongs(await res.json());
    } catch (e: any) {
      setError(e.message);
    }
  }, []);

  const fetchPlaylists = useCallback(async () => {
    try {
      const res = await fetch("/api/music/playlists");
      if (!res.ok) throw new Error("Failed to fetch playlists");
      setPlaylists(await res.json());
    } catch (e: any) {
      setError(e.message);
    }
  }, []);

  const fetchQueue = useCallback(async () => {
    try {
      const res = await fetch("/api/music/queue");
      if (!res.ok) throw new Error("Failed to fetch queue");
      setQueue(await res.json());
    } catch (e: any) {
      setError(e.message);
    }
  }, []);

  const fetchPlaylistDetail = useCallback(async (id: number) => {
    try {
      const res = await fetch(`/api/music/playlists/${id}`);
      if (!res.ok) throw new Error("Failed to fetch playlist");
      setSelectedPlaylist(await res.json());
    } catch (e: any) {
      setError(e.message);
    }
  }, []);

  const importPlaylist = useCallback(async (url: string) => {
    const res = await fetch("/api/music/playlists/import", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ url }),
    });
    if (!res.ok) {
      const data = await res.json();
      throw new Error(data.error || "Import failed");
    }
    await fetchPlaylists();
    return res.json();
  }, [fetchPlaylists]);

  const createPlaylist = useCallback(async (name: string, description?: string) => {
    const res = await fetch("/api/music/playlists", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name, description }),
    });
    if (!res.ok) throw new Error("Failed to create playlist");
    await fetchPlaylists();
    return res.json();
  }, [fetchPlaylists]);

  const deletePlaylist = useCallback(async (id: number) => {
    await fetch(`/api/music/playlists/${id}`, { method: "DELETE" });
    await fetchPlaylists();
    if (selectedPlaylist?.id === id) setSelectedPlaylist(null);
  }, [fetchPlaylists, selectedPlaylist]);

  const queueSongs = useCallback(async (isrcs: string[], playlistId?: number) => {
    const res = await fetch("/api/music/queue", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ isrcs, playlist_id: playlistId }),
    });
    if (!res.ok) throw new Error("Failed to queue songs");
    await fetchQueue();
    return res.json();
  }, [fetchQueue]);

  const removeFromQueue = useCallback(async (isrc: string) => {
    await fetch(`/api/music/queue/${encodeURIComponent(isrc)}`, { method: "DELETE" });
    await fetchQueue();
  }, [fetchQueue]);

  // Initial load
  useEffect(() => {
    Promise.all([fetchSongs(), fetchPlaylists(), fetchQueue()]).then(() => setLoading(false));
  }, [fetchSongs, fetchPlaylists, fetchQueue]);

  // Poll queue every 10s when there are active items
  useEffect(() => {
    if (!queue?.current && !queue?.stats?.remaining) return;
    const interval = setInterval(fetchQueue, 10000);
    return () => clearInterval(interval);
  }, [queue, fetchQueue]);

  // Debounced song search
  useEffect(() => {
    const timer = setTimeout(() => fetchSongs(songSearch || undefined), 300);
    return () => clearTimeout(timer);
  }, [songSearch, fetchSongs]);

  return {
    songs, playlists, queue, selectedPlaylist,
    loading, error,
    songSearch, setSongSearch,
    fetchSongs, fetchPlaylists, fetchQueue, fetchPlaylistDetail,
    importPlaylist, createPlaylist, deletePlaylist,
    queueSongs, removeFromQueue,
    setSelectedPlaylist,
  };
}
