import { useState, useEffect } from "react";
import { downloadSong, fetchSongs } from "../services/api";
import SongCard from "../components/SongCard";

function Home() {
  const [query, setQuery] = useState("");
  const [result, setResult] = useState(null);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [songs, setSongs] = useState([]);

  const handleSearch = async () => {
    if (!query.trim()) return;

    setLoading(true);
    setError("");
    setResult(null);

    try {
      const res = await downloadSong(query);
      setResult(res);
      await loadSongs(); // refresh song list
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const loadSongs = async () => {
    try {
      const data = await fetchSongs();

      const parsed = data.map((path) => {
        const file = path.split("\\").pop().split("/").pop();
        const title = decodeURIComponent(file.replace(".mp3", ""));
        return {
          title,
          artist: "Unknown",
          path,
          cover: "/default-cover.jpg",
        };
      });

      setSongs(parsed);
    } catch (err) {
      console.error("❌ Failed to load songs:", err);
    }
  };


  useEffect(() => {
    loadSongs();
  }, []);

  return (
    <div className="p-4 max-w-xl mx-auto">
      <h1 className="text-3xl font-bold mb-4 text-center">🎵 Tunedrop</h1>

      <div className="flex mb-4">
        <input
          type="text"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="Search for a song..."
          className="flex-1 p-2 border rounded-l"
        />
        <button
          onClick={handleSearch}
          className="bg-green-600 text-white px-4 rounded-r hover:bg-green-700"
          disabled={loading}
        >
          {loading ? "Downloading..." : "Search & Download"}
        </button>
      </div>

      {error && <p className="mt-2 text-red-600 text-sm">{error}</p>}

      {result && (
        <div className="mt-4 text-center">
          <p className="text-green-600">✅ Success: Downloaded "{result.query}"</p>
          <p className="text-xs text-gray-500 mt-1">Navidrome rescan: {result.rescan_status}</p>
        </div>
      )}

      {songs.length > 0 && (
        <>
          <h2 className="mt-6 text-xl font-semibold text-center">🎶 My Songs</h2>
          <div className="grid grid-cols-2 gap-4 mt-4">
            {songs.map((song, idx) => (
              <SongCard key={idx} song={song} />
            ))}
          </div>
        </>
      )}
    </div>
  );
}

export default Home;
