import { useState } from "react";
import { downloadSong } from "../services/api";

function Home() {
  const [query, setQuery] = useState("");
  const [status, setStatus] = useState("");
  const [loading, setLoading] = useState(false);

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

    setLoading(true);
    setStatus("");
    try {
      const result = await downloadSong(query);
      setStatus(`✅ Success: Downloaded "${result.query}"`);
    } catch (error) {
      setStatus(`❌ Error: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="p-4 max-w-md mx-auto">
      <h1 className="text-2xl font-bold mb-4">🎵 Tunedrop</h1>
      <input
        type="text"
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        placeholder="Search for a song..."
        className="w-full p-2 border rounded mb-2"
      />
      <button
        onClick={handleSearch}
        className="w-full bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600"
        disabled={loading}
      >
        {loading ? "Downloading..." : "Search & Download"}
      </button>

      {status && <p className="mt-4 text-center">{status}</p>}
    </div>
  );
}

export default Home;
