import React, { useState } from 'react';
import { searchSpotifyTracks, isLoggedIn } from '../utils/spotifyAuth.js';

function AddSongModal({ onClose }) {
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');

  const handleBackdropClick = (e) => {
    if (e.target === e.currentTarget) {
      onClose();
    }
  };

  const handleSearch = async (e) => {
    const query = e.target.value;
    setSearchQuery(query);
    setError('');
    
    if (query.length > 2) {
      if (!isLoggedIn()) {
        setError('Please login to Spotify to search for songs');
        return;
      }

      setIsLoading(true);
      try {
        const results = await searchSpotifyTracks(query);
        setSearchResults(results);
      } catch (err) {
        setError(err.message === 'Token expired' ? 'Session expired. Please login again.' : 'Search failed. Please try again.');
        setSearchResults([]);
        if (err.message === 'Token expired') {
          setTimeout(() => window.location.reload(), 2000);
        }
      } finally {
        setIsLoading(false);
      }
    } else {
      setSearchResults([]);
    }
  };

  const handleKeyPress = async (e) => {
    if (e.key === 'Enter' && searchQuery.trim() && searchQuery.length > 2) {
      if (!isLoggedIn()) {
        setError('Please login to Spotify to search for songs');
        return;
      }

      setIsLoading(true);
      try {
        const results = await searchSpotifyTracks(searchQuery);
        setSearchResults(results);
        setError('');
      } catch (err) {
        setError(err.message === 'Token expired' ? 'Session expired. Please login again.' : 'Search failed. Please try again.');
        setSearchResults([]);
      } finally {
        setIsLoading(false);
      }
    }
  };

  return (
    <div className="add-song-modal-backdrop" onClick={handleBackdropClick}>
      <div className="add-song-modal-content">
        <div className="add-song-modal-header">
          <h2>Add Song to Station</h2>
          <button className="add-song-close-btn" onClick={onClose}>
            <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
              <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
            </svg>
          </button>
        </div>
        
        <div className="add-song-modal-body">
          <div className="add-song-search-container">
            <div className="add-song-search-box">
              <svg className="search-icon" width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
              </svg>
              <input
                type="text"
                placeholder="Search for songs, artists, or albums..."
                value={searchQuery}
                onChange={handleSearch}
                onKeyPress={handleKeyPress}
                autoFocus
              />
              {isLoading && (
                <div className="search-loading">
                  <div className="loading-spinner"></div>
                </div>
              )}
            </div>
          </div>

          <div className="add-song-results-container">
            {error && (
              <div className="add-song-error">
                <p>{error}</p>
              </div>
            )}
            {searchQuery.length === 0 ? (
              <div className="add-song-placeholder">
                <svg width="48" height="48" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z"/>
                </svg>
                <p>Search for music to add to your station</p>
                <p className="placeholder-subtitle">Enter song title, artist, or album name</p>
              </div>
            ) : searchQuery.length <= 2 ? (
              <div className="add-song-placeholder">
                <p>Type at least 3 characters to search</p>
              </div>
            ) : searchResults.length === 0 && !isLoading && !error ? (
              <div className="add-song-placeholder">
                <p>No results found for "{searchQuery}"</p>
                <p className="placeholder-subtitle">Try different keywords</p>
              </div>
            ) : (
              <div className="add-song-results-list">
                {searchResults.map(song => (
                  <div key={song.id} className="add-song-result-item">
                    <img src={song.coverUrl} alt={`${song.title} cover`} className="result-song-cover" />
                    <div className="result-song-info">
                      <h4>{song.title}</h4>
                      <p className="result-artist">{song.artist}</p>
                      <p className="result-album">{song.album}</p>
                    </div>
                    <button className="add-song-btn" onClick={() => console.log('Adding song:', song)}>
                      <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
                      </svg>
                      Add
                    </button>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

export default AddSongModal;
