import React, { useState, useCallback, useEffect } from 'react';
import { Grommet } from 'grommet';
import { debounce } from 'lodash';
import { gql, useLazyQuery } from '@apollo/client';

import { Header } from './Header';
import { Search } from './Search';
import { Results } from './Results';
import { Artists, Artist } from '../interfaces';

const QUERY_ARTIST_ALBUMS = gql`
	query Artist($byName: String!) {
		queryArtists(byName: $byName) {
			name
			image
			id
			albums {
				name
				image
				id
			}
		}
	}
`;

export default function App() {
	const [inputValue, setInputValue] = useState('');
	const [getArtists, { data }] = useLazyQuery(QUERY_ARTIST_ALBUMS);
	const [artists, setArtists] = useState<Artists>(undefined);
	const [suggestions, setSuggestions] = useState<string[] | undefined>(
		undefined,
	);
	const [selected, setSelected] = useState(false);

	// Debounce the database query
	// Based on: https://archive.is/wip/6JDqb
	const updateQuery = () => {
		getArtists({ variables: { byName: inputValue } });
	};

	const delayedQuery = useCallback(debounce(updateQuery, 500), [inputValue]);

	const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
		setInputValue(e.target.value);
	};

	useEffect(() => {
		delayedQuery();
		// Cancel previous debounce calls during useEffect cleanup.
		return delayedQuery.cancel;
	}, [inputValue, delayedQuery]);

	const handleSelect = () => {
		setSelected(true);
	};

	useEffect(() => {
		// TODO optimize re-rendering, probably by using onCompleted instead of this useEffect
		// See https://github.com/apollographql/apollo-client/issues/5268#issuecomment-596950174
		if (data && data.queryArtists !== []) {
			// Limit artists to 5
			const updatedArtists = data.queryArtists.slice(0, 5);
			const updatedSuggestions: string[] = updatedArtists.map(
				(el: Artist) => {
					return el.name;
				},
			);
			setSuggestions(updatedSuggestions);
			setArtists(updatedArtists);
		}
	}, [data]);

	return (
		<Grommet theme={theme}>
			<Header>
				<h1>Spoti Search</h1>
			</Header>
			<Search
				inputValue={inputValue}
				handleChange={handleChange}
				suggestions={suggestions}
				handleSelect={handleSelect}
			/>
			<Results artists={artists} selected={selected} />
		</Grommet>
	);
}

const theme = {
	global: {
		font: {
			family: 'Roboto',
			size: '18px',
			height: '20px',
		},
	},
};
