import { useState, useEffect } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { searchApi } from '@/services/api/search';
import { SearchResults } from '@/types/search';
import { Card } from '@/components/ui/card';
import { Search, Music, User, X, Sparkles } from 'lucide-react';
import { LoadingSpinner } from '@/components/ui/loading-spinner';
import { useDebounce } from '@/hooks/useDebounce';
import { ErrorDisplay } from '@/components/ui/ErrorDisplay';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
import { Avatar } from '@/components/ui/avatar';
import { formatDistanceToNow } from 'date-fns';

export function SearchPage() {
  const [searchParams, setSearchParams] = useSearchParams();
  const navigate = useNavigate();
  const queryParam = searchParams.get('q') || '';

  const [query, setQuery] = useState(queryParam);
  const debouncedQuery = useDebounce(query, 500);

  const [results, setResults] = useState<SearchResults | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  // Sync state with URL
  useEffect(() => {
    setQuery(queryParam);
  }, [queryParam]);

  useEffect(() => {
    const performSearch = async () => {
      if (!debouncedQuery.trim()) {
        setResults(null);
        return;
      }

      setIsLoading(true);
      setError(null);

      try {
        const data = await searchApi.search(debouncedQuery);
        setResults(data);
      } catch (err) {
        setError(new Error('Search signal interrupted.'));
      } finally {
        setIsLoading(false);
      }
    };

    performSearch();
    // Update URL without reload
    if (debouncedQuery !== queryParam) {
      if (debouncedQuery) {
        setSearchParams({ q: debouncedQuery }, { replace: true });
      } else {
        setSearchParams({}, { replace: true });
      }
    }
  }, [debouncedQuery, setSearchParams, queryParam]);

  const clearSearch = () => {
    setQuery('');
    setSearchParams({});
    setResults(null);
  };

  const hasResults = results && (results.tracks.length > 0 || results.artists.length > 0 || results.playlists.length > 0);

  return (
    <div className="min-h-screen pb-24 container mx-auto px-4 py-8 max-w-6xl">
      {/* Search Header */}
      <div className="mb-12 text-center max-w-3xl mx-auto">
        <h1 className="text-4xl md:text-5xl font-display font-bold mb-6 text-white tracking-tight">
          Explore the <span className="text-transparent bg-clip-text bg-gradient-to-r from-cyan-400 to-magenta-500">Nebula</span>
        </h1>

        <div className="relative group">
          <div className="absolute -inset-1 bg-gradient-to-r from-cyan-500 to-magenta-500 rounded-2xl blur opacity-20 group-hover:opacity-40 transition duration-500" />
          <div className="relative flex items-center bg-black/50 backdrop-blur-xl border border-white/10 rounded-2xl overflow-hidden shadow-2xl">
            <Search className="w-5 h-5 ml-4 text-muted-foreground" />
            <input
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder="Search for tracks, artists, signals..."
              className="w-full bg-transparent border-none py-4 px-4 text-lg text-white placeholder:text-muted-foreground focus:outline-none focus:ring-0 font-sans"
              autoFocus
            />
            {query && (
              <button onClick={clearSearch} className="p-2 mr-2 hover:bg-white/10 rounded-full transition-colors text-muted-foreground hover:text-white">
                <X className="w-5 h-5" />
              </button>
            )}
          </div>
        </div>
      </div>

      {error && (
        <ErrorDisplay error={error} variant="card" severity="error" onRetry={() => window.location.reload()} />
      )}

      {isLoading ? (
        <div className="flex flex-col items-center justify-center py-20 opacity-50">
          <LoadingSpinner className="w-12 h-12 mb-4" />
          <p className="text-sm font-mono animate-pulse">Scanning frequencies...</p>
        </div>
      ) : !query ? (
        /* Empty State / Discovery Suggestions */
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6 opacity-80">
          <Card variant="glass" className="p-6 text-center hover:bg-white/5 transition-colors cursor-pointer group hover:-translate-y-1">
            <div className="w-12 h-12 rounded-full bg-cyan-500/10 flex items-center justify-center mx-auto mb-4 group-hover:bg-cyan-500/20 transition-colors">
              <Music className="w-6 h-6 text-cyan-500" />
            </div>
            <h3 className="font-bold text-lg mb-1">New Releases</h3>
            <p className="text-xs text-muted-foreground">Fresh signals from the void</p>
          </Card>
          <Card variant="glass" className="p-6 text-center hover:bg-white/5 transition-colors cursor-pointer group hover:-translate-y-1">
            <div className="w-12 h-12 rounded-full bg-magenta-500/10 flex items-center justify-center mx-auto mb-4 group-hover:bg-magenta-500/20 transition-colors">
              <Sparkles className="w-6 h-6 text-magenta-500" />
            </div>
            <h3 className="font-bold text-lg mb-1">Curated Mixes</h3>
            <p className="text-xs text-muted-foreground">Hand-picked by the algorithm</p>
          </Card>
          <Card variant="glass" className="p-6 text-center hover:bg-white/5 transition-colors cursor-pointer group hover:-translate-y-1">
            <div className="w-12 h-12 rounded-full bg-lime-500/10 flex items-center justify-center mx-auto mb-4 group-hover:bg-lime-500/20 transition-colors">
              <User className="w-6 h-6 text-lime-500" />
            </div>
            <h3 className="font-bold text-lg mb-1">Top Artists</h3>
            <p className="text-xs text-muted-foreground">Trending creators this week</p>
          </Card>
        </div>
      ) : !hasResults ? (
        <div className="text-center py-20">
          <div className="text-6xl mb-4">🔭</div>
          <h2 className="text-2xl font-bold mb-2">No signals found</h2>
          <p className="text-muted-foreground">Try adjusting your search frequency.</p>
        </div>
      ) : (
        /* Results */
        <Tabs defaultValue="all" className="w-full">
          <TabsList className="bg-transparent border-b border-white/10 w-full justify-start h-auto p-0 gap-8 mb-8">
            <TabsTrigger value="all" className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:text-primary py-3 px-0 text-lg font-display bg-transparent">All Results</TabsTrigger>
            <TabsTrigger value="tracks" className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:text-primary py-3 px-0 text-lg font-display bg-transparent">Tracks ({results?.tracks.length})</TabsTrigger>
            <TabsTrigger value="artists" className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:text-primary py-3 px-0 text-lg font-display bg-transparent">Artists ({results?.artists.length})</TabsTrigger>
            <TabsTrigger value="playlists" className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:text-primary py-3 px-0 text-lg font-display bg-transparent">Playlists ({results?.playlists.length})</TabsTrigger>
          </TabsList>

          <TabsContent value="all" className="space-y-12">
            {/* Top Tracks */}
            {results?.tracks.length! > 0 && (
              <section>
                <h3 className="text-xl font-bold mb-4 flex items-center gap-2"><Music className="w-5 h-5 text-primary" /> Top Tracks</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                  {results?.tracks.slice(0, 6).map(track => (
                    <Card key={track.id} variant="glass" className="p-3 flex items-center gap-4 hover:bg-white/5 transition-colors cursor-pointer group" onClick={() => navigate(`/tracks/${track.id}`)}>
                      <div className="w-16 h-16 rounded-lg bg-black/40 overflow-hidden flex-shrink-0">
                        {track.cover_art_path ? <img src={track.cover_art_path} className="w-full h-full object-cover group-hover:scale-110 transition-transform" /> : <Music className="w-full h-full p-4 text-white/20" />}
                      </div>
                      <div className="flex-1 min-w-0">
                        <h4 className="font-bold truncate group-hover:text-primary transition-colors">{track.title}</h4>
                        <p className="text-xs text-muted-foreground truncate">{track.artist}</p>
                      </div>
                    </Card>
                  ))}
                </div>
              </section>
            )}

            {/* Artists */}
            {results?.artists.length! > 0 && (
              <section>
                <h3 className="text-xl font-bold mb-4 flex items-center gap-2"><User className="w-5 h-5 text-primary" /> Artists</h3>
                <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4">
                  {results?.artists.slice(0, 5).map(artist => (
                    <Card key={artist.id} variant="glass" className="p-4 flex flex-col items-center text-center hover:bg-white/5 transition-colors cursor-pointer group" onClick={() => navigate(`/u/${artist.username}`)}>
                      <Avatar src={artist.avatar_url} fallback={artist.username[0]} className="w-24 h-24 mb-4 shadow-lg group-hover:scale-105 transition-transform" />
                      <h4 className="font-bold truncate w-full group-hover:text-primary transition-colors">{artist.username}</h4>
                      <p className="text-xs text-muted-foreground truncate">{artist.followers_count || 0} followers</p>
                    </Card>
                  ))}
                </div>
              </section>
            )}
          </TabsContent>

          {/* Detailed Tabs would mirror the implementation above with full Map */}
          <TabsContent value="tracks">
            <div className="grid grid-cols-1 gap-2">
              {results?.tracks.map(track => (
                <div key={track.id} className="flex items-center gap-4 p-4 rounded-xl border border-white/5 hover:bg-white/5 transition-colors cursor-pointer group bg-black/20" onClick={() => navigate(`/tracks/${track.id}`)}>
                  <div className="w-12 h-12 rounded bg-black/40 overflow-hidden">
                    {track.cover_art_path && <img src={track.cover_art_path} className="w-full h-full object-cover" />}
                  </div>
                  <div className="flex-1">
                    <h4 className="font-bold group-hover:text-primary">{track.title}</h4>
                    <p className="text-muted-foreground text-sm">{track.artist}</p>
                  </div>
                  <div className="text-xs font-mono text-muted-foreground">{formatDistanceToNow(new Date(track.created_at))} ago</div>
                </div>
              ))}
            </div>
          </TabsContent>

          <TabsContent value="artists">
            <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
              {results?.artists.map(artist => (
                <Card key={artist.id} variant="glass" className="p-6 flex flex-col items-center text-center hover:bg-white/5 cursor-pointer group" onClick={() => navigate(`/u/${artist.username}`)}>
                  <Avatar src={artist.avatar_url} fallback={artist.username[0]} className="w-32 h-32 mb-4 shadow-lg group-hover:scale-105 transition-transform" />
                  <h4 className="font-bold text-lg group-hover:text-primary">{artist.username}</h4>
                </Card>
              ))}
            </div>
          </TabsContent>

          <TabsContent value="playlists">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              {results?.playlists.map(playlist => (
                <Card key={playlist.id} variant="glass" className="p-0 overflow-hidden cursor-pointer group hover:-translate-y-1 transition-transform" onClick={() => navigate(`/playlists/${playlist.id}`)}>
                  <div className="h-32 bg-gradient-to-br from-purple-900 to-black relative">
                    {playlist.cover_url && <img src={playlist.cover_url} className="w-full h-full object-cover" />}
                    <div className="absolute inset-0 bg-black/20 group-hover:bg-transparent transition-colors" />
                  </div>
                  <div className="p-4">
                    <h4 className="font-bold group-hover:text-primary">{playlist.title}</h4>
                    <p className="text-xs text-muted-foreground line-clamp-2 mt-1">{playlist.description || 'No description'}</p>
                  </div>
                </Card>
              ))}
            </div>
          </TabsContent>
        </Tabs>
      )}
    </div>
  );
}
