import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Disc3, Sparkles } from 'lucide-react';
import { genreService } from '../services/genreService';
import { vibeService } from '../services/vibeService';
import { usePlaybackStore } from '../store/usePlaybackStore';
import { useVibeStore } from '../store/useVibeStore';
import { TrackRow } from '../components/TrackRow';
import { PageContainer } from '../components/PageContainer';
import type { Genre, Track } from '../types';

export default function Discover() {
  const [selected, setSelected] = useState<Genre | null>(null);
  const { setQueue, playTrack } = usePlaybackStore();
  const { setActiveSession, setSeedTrackId, setBuffer } = useVibeStore();

  const genres = useQuery<Genre[]>({
    queryKey: ['genres'],
    queryFn: () => genreService.listGenres(),
  });

  const genreTracks = useQuery<Track[]>({
    queryKey: ['genre-tracks', selected?.id],
    queryFn: () => genreService.getGenreTracks(selected!.id),
    enabled: !!selected,
  });

  const startGenreVibe = async () => {
    const tracks = genreTracks.data;
    if (!tracks || tracks.length === 0) return;
    const seed = tracks[0];
    try {
      const { sessionId } = await vibeService.start(seed.id);
      setActiveSession({ sessionId, seedTrackId: seed.id });
      setSeedTrackId(seed.id);
      setBuffer(tracks);
      setQueue(tracks);
      playTrack(tracks[0]);
    } catch {
      setQueue(tracks);
      playTrack(tracks[0]);
    }
  };

  return (
    <PageContainer>
      <header className="space-y-1">
        <h1 className="text-3xl font-bold text-text">Discover</h1>
        <p className="text-muted">Browse by genre, then play tracks or start a vibe.</p>
      </header>

      {genres.isLoading ? (
        <p className="text-sm text-muted">Loading genres…</p>
      ) : genres.isError ? (
        <p className="text-sm text-muted">Couldn't load genres.</p>
      ) : (genres.data ?? []).length === 0 ? (
        <p className="text-sm text-muted">No genres available yet.</p>
      ) : (
        <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
          {(genres.data ?? []).map((genre) => {
            const active = selected?.id === genre.id;
            return (
              <button
                key={genre.id}
                onClick={() => setSelected(genre)}
                className={`flex flex-col gap-2 rounded-xl border p-4 text-left transition-colors ${
                  active
                    ? 'border-accent/60 bg-accent/10'
                    : 'border-border bg-surface0 hover:bg-surface1'
                }`}
              >
                <Disc3 size={22} className={active ? 'text-accent' : 'text-muted'} />
                <div className="truncate font-semibold text-text">{genre.name}</div>
                {typeof genre.track_count === 'number' && (
                  <div className="text-xs text-muted">{genre.track_count} tracks</div>
                )}
              </button>
            );
          })}
        </div>
      )}

      {selected && (
        <section className="space-y-3">
          <div className="flex items-center justify-between">
            <h2 className="text-xl font-semibold text-text">{selected.name}</h2>
            <button
              onClick={() => void startGenreVibe()}
              disabled={!genreTracks.data || genreTracks.data.length === 0}
              className="flex items-center gap-2 rounded-lg border border-accent/60 bg-accent/10 px-3 py-1.5 text-sm font-medium text-accent transition-colors hover:bg-accent/20 disabled:opacity-50"
            >
              <Sparkles size={16} />
              Start a vibe
            </button>
          </div>

          {genreTracks.isLoading ? (
            <p className="text-sm text-muted">Loading tracks…</p>
          ) : genreTracks.isError ? (
            <p className="text-sm text-muted">Couldn't load tracks for this genre.</p>
          ) : (genreTracks.data ?? []).length === 0 ? (
            <p className="text-sm text-muted">No tracks found for this genre.</p>
          ) : (
            <div className="space-y-1">
              {(genreTracks.data ?? []).map((track, i) => (
                <TrackRow
                  key={`${track.id}-${i}`}
                  track={track}
                  queue={genreTracks.data ?? []}
                  index={i}
                  showActions={false}
                />
              ))}
            </div>
          )}
        </section>
      )}
    </PageContainer>
  );
}
