import { Text, Group, Avatar, Box } from "@mantine/core";
import { SpotifyTrack } from "@/lib/spotify/types";
import Typeahead, { TypeaheadOption } from "@/components/typeahead";
import { useLingui } from "@lingui/react/macro";

interface SongSearchProps {
  onChange: (track: SpotifyTrack) => void;
  placeholder?: string;
}

const SongSearch = ({ onChange, placeholder }: SongSearchProps) => {
  const { t } = useLingui();
  const resolvedPlaceholder = placeholder ?? t`Search for songs...`;
  const searchSpotifyTracks = async (query: string): Promise<TypeaheadOption<SpotifyTrack>[]> => {
    try {
      // Use a default search term when query is empty to show popular tracks
      const searchTerm = query.trim() || 'top hits';
      const response = await fetch(`/api/spotify/search?q=${encodeURIComponent(searchTerm)}`);

      if (!response.ok) {
        throw new Error('Search failed');
      }

      const data = await response.json();
      const tracks = data.tracks || [];

      return tracks.map((track: SpotifyTrack) => ({
        id: track.id,
        data: track
      }));
    } catch (error) {
      console.error('Failed to search tracks:', error);
      return [];
    }
  };

  const handleSongSelect = (option: TypeaheadOption<SpotifyTrack>) => {
    onChange(option.data);
  };

  const formatTrack = (option: TypeaheadOption<SpotifyTrack>) => {
    const track = option.data;
    return `${track.name} - ${track.artists.map(a => a.name).join(', ')}`;
  };

  const renderOption = (option: TypeaheadOption<SpotifyTrack>) => {
    const track = option.data;
    return (
      <Box
        p="sm"
        style={{
          borderBottom: '1px solid var(--mantine-color-dimmed)'
        }}
      >
        <Group gap="sm">
          {track.album.images[2] && (
            <Avatar src={track.album.images[2].url} size={40} radius="sm" />
          )}
          <div>
            <Text size="sm" fw={500}>
              {track.name}
            </Text>
            <Text size="xs" c="dimmed">
              {track.artists.map(a => a.name).join(', ')} • {track.album.name}
            </Text>
          </div>
        </Group>
      </Box>
    );
  };

  return (
    <Typeahead
      onSelect={handleSongSelect}
      searchFn={searchSpotifyTracks}
      renderOption={renderOption}
      format={formatTrack}
      placeholder={resolvedPlaceholder}
    />
  )
};

export default SongSearch;