import { useQuery } from '@tanstack/react-query';
import { useSearch } from '@tanstack/react-router';
import { Search as SearchIcon, SearchX } from 'lucide-react';
import { searchService } from '../services/searchService';
import { TrackRow } from '../components/TrackRow';
import { PageContainer } from '../components/PageContainer';
import { EmptyState } from '../components/EmptyState';
import { LoadingState } from '../components/LoadingState';
import type { SearchResponse, Track } from '../types';

export default function Search() {
  // The query lives entirely in the URL; the top bar is the input (it pushes
  // ?q= live as you type). This page just reflects whatever's in the URL.
  const query = (useSearch({ from: '/search', select: (s) => s.q }) ?? '').trim();

  const { data, isLoading, isError, isFetching } = useQuery<SearchResponse>({
    queryKey: ['search', query],
    queryFn: () => searchService.search(query),
    enabled: query.length > 0,
  });

  const tracks: Track[] = (data?.hits ?? [])
    .map((h) => h.document)
    .filter((t): t is Track => Boolean(t));
  const busy = isLoading || isFetching;

  return (
    <PageContainer>
      <div className="animate-rise">
        <h1 className="text-gradient text-3xl font-extrabold tracking-tight sm:text-4xl">Search</h1>
        {query.length > 0 ? (
          <p className="mt-1.5 text-sm text-muted">
            {busy ? 'Searching' : `${tracks.length} ${tracks.length === 1 ? 'result' : 'results'}`} for{' '}
            <span className="font-semibold text-text">“{query}”</span>
          </p>
        ) : (
          <p className="mt-1.5 text-sm text-muted">Search your library from the bar above.</p>
        )}
      </div>

      {query.length === 0 ? (
        <EmptyState
          icon={<SearchIcon size={28} />}
          title="Start typing to search"
          subtitle="Find songs by title or artist — results appear as you type."
        />
      ) : busy ? (
        <LoadingState label="Searching…" />
      ) : isError ? (
        <EmptyState icon={<SearchX size={28} />} title="Search failed" subtitle="Something went wrong. Try again." />
      ) : tracks.length === 0 ? (
        <EmptyState icon={<SearchX size={28} />} title="No results" subtitle={`Nothing matched “${query}”.`} />
      ) : (
        <section className="space-y-1 rounded-2xl border border-border/70 bg-surface0/40 p-2 animate-rise">
          {tracks.map((t, i) => (
            <TrackRow key={t.id} track={t} queue={tracks} index={i} />
          ))}
        </section>
      )}
    </PageContainer>
  );
}
