import { useParams } from 'react-router-dom'
import { GetAnimeTitleDetail, VoteAnimeTitle, UnvoteAnimeTitle } from '../../../api/AnimeTitleApi';
import { QueryClient, useQuery, useQueryClient } from 'react-query';
import AnimeTitleDetailComponent from '../../../components/MediaContent/view/AnimeTitleDetailComponent';
import { VoteDeleteModel, VoteEditModel} from '../../../api/models/Types';
import { libraryClient } from '../../../api/axios';
import useUser from '../../../api/hooks/useUser';
import { userQueryKey } from '../../../components/common/UserShortComponent';


// let queryKey;
const queryKey = 'anime_title_detail';

export default function AnimeTitleDetail() {
	const client = libraryClient;
	//useAxiosWithAuth(libraryClient);
	const { getUser } = useUser();
	const queryClient = useQueryClient();
	const { data: user } = useQuery(userQueryKey, getUser);

	const { id } = useParams();
	const { data, isLoading, isError } = useQuery(queryKey, () => GetAnimeTitleDetail(id ?? '', client));
	if (id == undefined) return (<h2>Писюн (404)</h2>);
	return (
		<>
			{!isLoading && !isError && data &&
				<AnimeTitleDetailComponent 
					user={user}
					animeTitle={data}
					// setRate={props.setRate}
					// deleteRate={props.deleteRate}
					// forceRefresh={props.forceRefresh}
					setRate={(value: number | null) => {
						// console.log(`Set rate (${value == null ? 'null' : value}) of [${rateObjectId}]`);
						if (value != null){
							return VoteAnimeTitle({
								animeTitleId: data.id,
								animeSeasonId: null,
								animeEpisodeId: null,
								ratingPercentage: value
							} as VoteEditModel, client);
						}
						else{
							return UnvoteAnimeTitle({
								animeTitleId: data.id,
								animeSeasonId: null,
								animeEpisodeId: null,
							} as VoteDeleteModel, client);
						}
					}}
					deleteRate={() => {
						console.log(`Delete rate of [${data.id}]`);
						return UnvoteAnimeTitle({
							animeTitleId: data.id,
							animeSeasonId: null,
							animeEpisodeId: null,
						} as VoteDeleteModel, client);
					}}
					forceRefresh={() => InvalidateGenres(queryClient)}
					/>
			}
		</>
  	)
}


function InvalidateGenres(queryClient: QueryClient) {
	return queryClient.invalidateQueries({ queryKey: [queryKey] });
}