import { useState, useCallback, useMemo } from "react";
import { useNavigate } from "react-router-dom";
import { motion, AnimatePresence } from "framer-motion";
import {
  Search,
  Music,
  Plus,
  ChevronRight,
  Clock,
  Star,
  Globe,
  X,
  ExternalLink,
} from "lucide-react";
import debounce from "@utils/debounce";
import { useSongs } from "@hooks/useDataFetch";

function SongSearchPanel() {
  const navigate = useNavigate();
  const [searchQuery, setSearchQuery] = useState("");
  const [showOnlineModal, setShowOnlineModal] = useState(false);
  const [onlineSearchQuery, setOnlineSearchQuery] = useState("");

  // Use cached songs from global store
  const { songs, loading } = useSongs();

  // Get recent songs (most recently created)
  const recentSongs = useMemo(() => {
    return [...songs]
      .sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
      .slice(0, 5);
  }, [songs]);

  // Local search on cached songs (no API call)
  const results = useMemo(() => {
    if (!searchQuery.trim()) return [];
    const query = searchQuery.toLowerCase();
    return songs
      .filter(
        (song) =>
          song.title?.toLowerCase().includes(query) ||
          song.artist?.toLowerCase().includes(query) ||
          song.singer?.toLowerCase().includes(query),
      )
      .slice(0, 20);
  }, [searchQuery, songs]);

  const isSearching = loading && searchQuery.trim().length > 0;

  const handleSearch = (value) => {
    setSearchQuery(value);
  };

  const handleSelectSong = (songId) => {
    navigate(`/song/${songId}`);
  };

  const openOnlineSearch = () => {
    setShowOnlineModal(true);
    setOnlineSearchQuery(searchQuery);
  };

  const searchOnline = (service) => {
    const query = encodeURIComponent(onlineSearchQuery || searchQuery);
    const urls = {
      ultimate: `https://www.ultimate-guitar.com/search.php?search_type=title&value=${query}`,
      chordify: `https://chordify.net/search/${query}`,
      google: `https://www.google.com/search?q=${query}+chords+lyrics`,
    };
    window.open(urls[service], "_blank");
  };

  return (
    <div className="glass-card p-6 h-full">
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-2">
          <Search className="w-5 h-5 text-primary-600" />
          <h3 className="font-semibold text-gray-800">Search Songs</h3>
        </div>
        <button
          onClick={() => navigate("/database")}
          className="text-sm text-primary-600 hover:text-primary-700 font-medium flex items-center gap-1"
        >
          Browse All
          <ChevronRight className="w-4 h-4" />
        </button>
      </div>

      {/* Search Input */}
      <div className="relative mb-4">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
        <input
          type="text"
          value={searchQuery}
          onChange={(e) => handleSearch(e.target.value)}
          placeholder="Search by title, artist, or key..."
          className="input-glass pl-10"
        />
        {isSearching && (
          <div className="absolute right-3 top-1/2 -translate-y-1/2">
            <div className="w-4 h-4 border-2 border-primary-500 border-t-transparent rounded-full animate-spin" />
          </div>
        )}
      </div>

      {/* Search Results */}
      <AnimatePresence mode="wait">
        {searchQuery && results.length > 0 ? (
          <motion.div
            key="results"
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            className="space-y-2"
          >
            <p className="text-xs text-gray-500 mb-2">
              {results.length} results found
            </p>
            {results.map((song) => (
              <motion.div
                key={song.id}
                layout
                onClick={() => handleSelectSong(song.id)}
                className="flex items-center gap-3 p-3 rounded-xl hover:bg-gray-50 cursor-pointer transition-colors"
              >
                <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-primary-400 to-primary-600 flex items-center justify-center">
                  <Music className="w-5 h-5 text-white" />
                </div>
                <div className="flex-1 min-w-0">
                  <h4 className="font-medium text-gray-800 truncate">
                    {song.title}
                  </h4>
                  <p className="text-sm text-gray-500 truncate">
                    {song.artist}
                  </p>
                </div>
                <span className="px-2 py-1 bg-amber-100 text-amber-700 text-xs font-bold rounded-lg">
                  {song.key_chord || song.key || "—"}
                </span>
              </motion.div>
            ))}
          </motion.div>
        ) : searchQuery && !isSearching ? (
          <motion.div
            key="no-results"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="text-center py-6"
          >
            <p className="text-gray-500 mb-3">
              No songs found for "{searchQuery}"
            </p>
            <div className="flex flex-col gap-2">
              <button
                onClick={openOnlineSearch}
                className="px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white font-medium rounded-lg flex items-center justify-center gap-2 transition-colors"
              >
                <Globe size={16} />
                Search Online
              </button>
              <button
                onClick={() => navigate("/song/new")}
                className="px-4 py-2 text-primary-600 border border-primary-600 hover:bg-primary-50 font-medium rounded-lg flex items-center justify-center gap-2 transition-colors"
              >
                <Plus size={16} />
                Create New Song
              </button>
            </div>
          </motion.div>
        ) : (
          <motion.div
            key="recent"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
          >
            {/* Recent Songs */}
            <div className="flex items-center gap-2 mb-3">
              <Clock className="w-4 h-4 text-gray-400" />
              <span className="text-sm font-medium text-gray-600">
                Recent Songs
              </span>
            </div>
            <div className="space-y-2">
              {recentSongs.map((song) => (
                <div
                  key={song.id}
                  onClick={() => handleSelectSong(song.id)}
                  className="flex items-center gap-3 p-3 rounded-xl hover:bg-gray-50 cursor-pointer transition-colors"
                >
                  <div className="w-10 h-10 rounded-xl bg-gray-100 flex items-center justify-center">
                    <Music className="w-5 h-5 text-gray-500" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <h4 className="font-medium text-gray-800 truncate">
                      {song.title}
                    </h4>
                    <p className="text-sm text-gray-500 truncate">
                      {song.artist}
                    </p>
                  </div>
                  <span className="px-2 py-1 bg-amber-100 text-amber-700 text-xs font-bold rounded-lg">
                    {song.key_chord || song.key || "—"}
                  </span>
                </div>
              ))}
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Online Search Modal */}
      {showOnlineModal && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4">
          <motion.div
            initial={{ opacity: 0, scale: 0.9 }}
            animate={{ opacity: 1, scale: 1 }}
            className="max-w-md w-full bg-white rounded-2xl p-6 shadow-2xl"
          >
            <div className="flex justify-between items-center mb-4">
              <h2 className="text-xl font-bold text-gray-900 flex items-center gap-2">
                <Globe size={24} className="text-blue-500" />
                Search Online
              </h2>
              <button
                onClick={() => setShowOnlineModal(false)}
                className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
              >
                <X size={20} className="text-gray-500" />
              </button>
            </div>

            <div className="mb-6">
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Song to search
              </label>
              <input
                type="text"
                value={onlineSearchQuery}
                onChange={(e) => setOnlineSearchQuery(e.target.value)}
                placeholder="Enter song title or artist..."
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                autoFocus
              />
            </div>

            <div className="space-y-3">
              <p className="text-sm text-gray-600 mb-3">
                Choose where to search:
              </p>

              <button
                onClick={() => searchOnline("ultimate")}
                className="w-full px-4 py-3 bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600 text-white font-medium rounded-lg flex items-center justify-between transition-all shadow-lg hover:shadow-xl"
              >
                <span>Ultimate Guitar</span>
                <ExternalLink size={16} />
              </button>

              <button
                onClick={() => searchOnline("chordify")}
                className="w-full px-4 py-3 bg-gradient-to-r from-blue-500 to-purple-500 hover:from-blue-600 hover:to-purple-600 text-white font-medium rounded-lg flex items-center justify-between transition-all shadow-lg hover:shadow-xl"
              >
                <span>Chordify</span>
                <ExternalLink size={16} />
              </button>

              <button
                onClick={() => searchOnline("google")}
                className="w-full px-4 py-3 bg-gradient-to-r from-green-500 to-teal-500 hover:from-green-600 hover:to-teal-600 text-white font-medium rounded-lg flex items-center justify-between transition-all shadow-lg hover:shadow-xl"
              >
                <span>Google Search</span>
                <ExternalLink size={16} />
              </button>
            </div>

            <div className="mt-6 p-4 bg-blue-50 rounded-lg">
              <p className="text-xs text-gray-700">
                <strong>Tip:</strong> Copy the chords and lyrics from the
                website, then paste them into a new song. Our system will
                auto-detect the chords!
              </p>
            </div>
          </motion.div>
        </div>
      )}
    </div>
  );
}

export default SongSearchPanel;
