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 { PageHeader } from '../components/PageHeader';
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>
      <PageHeader
        title="Search"
        subtitle={query.length > 0 ? `“${query}”` : 'Search your library from the bar above.'}
        meta={query.length > 0 ? (busy ? 'searching…' : `${tracks.length} results`) : undefined}
      />

      {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="track-list animate-rise rounded-lg border border-border bg-surface0/30 px-1 py-1">
          {tracks.map((t, i) => (
            <TrackRow key={t.id} track={t} queue={tracks} index={i} />
          ))}
        </section>
      )}
    </PageContainer>
  );
}
