import React, { useState, useEffect, useRef } from 'react';
import {
  Search,
  X,
  Clock,
  ArrowUpRight,
  Music,
  User,
  Disc,
} from 'lucide-react';

interface SearchBarProps {
  initialQuery?: string;
  onSearch: (query: string) => void;
  placeholder?: string;
  className?: string;
}

// Mock Suggestions
const SUGGESTIONS = [
  { type: 'artist', label: 'Neon Pulse', id: 'u1' },
  { type: 'track', label: 'Neon Nights', id: 't1' },
  { type: 'genre', label: 'Synthwave', id: 'g1' },
  { type: 'track', label: 'Cyber City 2099', id: 't2' },
  { type: 'artist', label: 'Deadmau5', id: 'u4' },
];

export const SearchBar: React.FC<SearchBarProps> = ({
  initialQuery = '',
  onSearch,
  placeholder = 'Search tracks, artists, gear...',
  className,
}) => {
  const [query, setQuery] = useState(initialQuery);
  const [isFocused, setIsFocused] = useState(false);
  const [recentSearches, setRecentSearches] = useState<string[]>([
    'Techno',
    'Apollo Twin',
    'Serum Presets',
  ]);
  const wrapperRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        wrapperRef.current &&
        !wrapperRef.current.contains(event.target as Node)
      ) {
        setIsFocused(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const handleSubmit = (e?: React.FormEvent) => {
    e?.preventDefault();
    if (!query.trim()) return;
    onSearch(query);
    setIsFocused(false);
    if (!recentSearches.includes(query)) {
      setRecentSearches((prev) => [query, ...prev].slice(0, 5));
    }
  };

  const handleSuggestionClick = (text: string) => {
    setQuery(text);
    onSearch(text);
    setIsFocused(false);
  };

  const filteredSuggestions = query
    ? SUGGESTIONS.filter((s) =>
        s.label.toLowerCase().includes(query.toLowerCase()),
      )
    : [];

  const getIcon = (type: string) => {
    switch (type) {
      case 'artist':
        return <User className="w-3 h-3" />;
      case 'track':
        return <Music className="w-3 h-3" />;
      case 'album':
        return <Disc className="w-3 h-3" />;
      default:
        return <Search className="w-3 h-3" />;
    }
  };

  return (
    <div ref={wrapperRef} className={`relative w-full ${className}`}>
      <form onSubmit={handleSubmit} className="relative z-20">
        <div
          className={`flex items-center bg-kodo-ink border rounded-xl px-4 py-3 transition-all ${isFocused ? 'border-kodo-cyan shadow-neon-cyan/10 ring-1 ring-kodo-cyan/20' : 'border-kodo-steel'}`}
        >
          <Search
            className={`w-5 h-5 mr-3 transition-colors ${isFocused ? 'text-kodo-cyan' : 'text-gray-500'}`}
          />
          <input
            type="text"
            className="bg-transparent border-none text-white placeholder-gray-500 w-full focus:ring-0 outline-none text-base"
            placeholder={placeholder}
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            onFocus={() => setIsFocused(true)}
          />
          {query && (
            <button
              type="button"
              onClick={() => setQuery('')}
              className="text-gray-500 hover:text-white transition-colors"
            >
              <X className="w-4 h-4" />
            </button>
          )}
        </div>
      </form>

      {isFocused && (
        <div className="absolute top-full left-0 right-0 mt-2 bg-kodo-graphite border border-kodo-steel rounded-xl shadow-2xl z-50 overflow-hidden animate-slideUp">
          {query ? (
            <div>
              {filteredSuggestions.length > 0 ? (
                <div className="py-2">
                  <div className="px-4 py-2 text-[10px] font-bold text-gray-500 uppercase">
                    Top Results
                  </div>
                  {filteredSuggestions.map((item, i) => (
                    <div
                      key={i}
                      className="px-4 py-2 hover:bg-white/5 cursor-pointer flex items-center gap-3 transition-colors"
                      onClick={() => handleSuggestionClick(item.label)}
                    >
                      <div className="w-8 h-8 rounded bg-kodo-slate flex items-center justify-center text-gray-400">
                        {getIcon(item.type)}
                      </div>
                      <div>
                        <div className="text-sm font-bold text-white">
                          {item.label}
                        </div>
                        <div className="text-xs text-gray-500 capitalize">
                          {item.type}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="p-4 text-center text-gray-500 text-sm">
                  No results found for "{query}"
                </div>
              )}
            </div>
          ) : (
            <div className="py-2">
              <div className="px-4 py-2 flex justify-between items-center">
                <span className="text-[10px] font-bold text-gray-500 uppercase">
                  Recent Searches
                </span>
                <button
                  onClick={() => setRecentSearches([])}
                  className="text-[10px] text-kodo-red hover:underline"
                >
                  Clear
                </button>
              </div>
              {recentSearches.map((term, i) => (
                <div
                  key={i}
                  className="px-4 py-2 hover:bg-white/5 cursor-pointer flex items-center justify-between group transition-colors"
                  onClick={() => handleSuggestionClick(term)}
                >
                  <div className="flex items-center gap-3 text-gray-300 group-hover:text-white">
                    <Clock className="w-4 h-4 text-gray-500" />
                    <span className="text-sm">{term}</span>
                  </div>
                  <ArrowUpRight className="w-3 h-3 text-gray-600 opacity-0 group-hover:opacity-100" />
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
};
