import React, { createContext, useContext, useEffect, useState, useCallback } from "react";
import { api, STORAGE_BASE } from "../services/api";
import { useAuth } from "./AuthContext";

const LibraryContext = createContext(null);

function mapAlbum(album) {
  return {
    id: String(album.id),
    title: album.title,
    artist: album.artist?.name || (album.artists || []).map(a => a.name).join(", ") || "Unknown artist",
    date: album.release_date ? album.release_date.slice(0, 10) : "",
    label: album.label?.name || "",
    type: album.type || "album",
    cover: album.cover_path ? { uri: `${STORAGE_BASE}/${album.cover_path}` } : null,
    genres: (album.genres || []).map(g => g.name),
    tracks: (album.tracks || [])
      .sort((a, b) => a.position - b.position)
      .map((t) => ({
        id: String(t.id),
        title: t.title,
        duration: t.duration_seconds || 0,
        liked: false,
        artists: (t.artists || []).map(a => a.name),
        genres: (t.genres || []).map(g => g.name),
      })),
  };
}

export function LibraryProvider({ children }) {
  const { token } = useAuth();
  const [albums, setAlbums] = useState([]);
  const [likedTrackIds, setLikedTrackIds] = useState(new Set());
  const [loading, setLoading] = useState(true);

  const loadAlbums = useCallback(async () => {
    if (!token) return;
    try {
      const raw = await api.getAlbums();
      setAlbums(raw.map(mapAlbum));
    } catch (err) {
      console.error("Failed to load albums:", err);
    }
  }, [token]);

  const loadLikes = useCallback(async () => {
    if (!token) return;
    try {
      const liked = await api.getLikedTracks();
      setLikedTrackIds(new Set(liked.map((t) => String(t.id))));
    } catch (err) {
      console.error("Failed to load likes:", err);
    }
  }, [token]);

  useEffect(() => {
    if (!token) {
      setAlbums([]);
      setLikedTrackIds(new Set());
      setLoading(false);
      return;
    }
    setLoading(true);
    Promise.all([loadAlbums(), loadLikes()]).finally(() => setLoading(false));
  }, [token, loadAlbums, loadLikes]);

  const toggleLike = async (albumId, trackId) => {
    const isLiked = likedTrackIds.has(trackId);
    try {
      if (isLiked) {
        await api.unlikeTrack(trackId);
        setLikedTrackIds((prev) => {
          const next = new Set(prev);
          next.delete(trackId);
          return next;
        });
      } else {
        await api.likeTrack(trackId);
        setLikedTrackIds((prev) => new Set(prev).add(trackId));
      }
    } catch (err) {
      console.error("Failed to toggle like:", err);
    }
  };

  const likedTracks = albums.flatMap((album) =>
    album.tracks
      .filter((track) => likedTrackIds.has(track.id))
      .map((track) => ({
        ...track,
        albumId: album.id,
        albumTitle: album.title,
        artist: track.artists?.length > 0 ? track.artists.join(", ") : album.artist,
        cover: album.cover,
      }))
  );

  return (
    <LibraryContext.Provider value={{ albums, likedTracks, loading, toggleLike, reload: () => { loadAlbums(); loadLikes(); } }}>
      {children}
    </LibraryContext.Provider>
  );
}

export function useLibrary() {
  const ctx = useContext(LibraryContext);
  if (!ctx) throw new Error("useLibrary must be used inside LibraryProvider");
  return ctx;
}