import { Link } from "react-router-dom";
import React, { useEffect } from 'react';
import { TfiPlus } from "react-icons/tfi";
import { GetAnimeTitleList, VoteAnimeTitle, UnvoteAnimeTitle } from "../../../api/AnimeTitleApi";
import { QueryClient, useQuery, useQueryClient } from "react-query";
import { AnimeTitleShort, VoteDeleteModel, VoteEditModel } from "../../../api/models/Types";
import AnimeTitleShortComponent from "../../../components/MediaContent/view/AnimeTitleShortComponent";
// import useAxiosWithAuth from "../../../api/hooks/useAxiosWithAuth";
import { libraryClient } from "../../../api/axios";
import { AxiosInstance } from "axios";
import useUser from "../../../api/hooks/useUser";
import { userQueryKey } from "../../../components/common/UserShortComponent";
import { UserInfo } from "../../../api/models/AccountTypes";

export interface IGreetingsComponentProps{
    name: string;
}


const queryKey = 'anime_titles';

export default function ListLatest(){
	const client = libraryClient;
	// useAxiosWithAuth(libraryClient);
	const { getUser } = useUser();
	const queryClient = useQueryClient();
	const { data: user } = useQuery(userQueryKey, getUser);
	const { data, isLoading, isError } = useQuery(queryKey, () => GetAnimeTitleList(client));
	// const [expandedRate, SetRateExpanded] = useState<titleId: string, expanded: boolean]>();
	// const user = null;

	useEffect(() => {
		InvalidateTitles(queryClient)
	},
	[user, queryClient])
    return (
		<>
        {(user !== null) &&
            <div className='row g-2 justify-content-end'>
                <div className="col-auto">
                    <Link to='/admin/library/anime/title' className='btn btn-primary w-100'><TfiPlus /></Link>
                </div>
            </div>
        }
        <div className='row g-2'>
			{isLoading &&
				<div>Загрузка...</div>
			}
			{isError &&
				<div>Ошибка загрузки данных</div>
			}
			{!isLoading && !isError &&
				ShowAnimeTitles(client, data, queryClient, user)
			}
		</div>
        </>
  	)
}

function ShowAnimeTitles(client: AxiosInstance, data: Array<AnimeTitleShort> | undefined, queryClient: QueryClient, user: UserInfo | null | undefined){
	// if (data) return React.Children.toArray(
	// 	data.map((item: AnimeTitle) => 
	// 	<div className='col-4'>
	// 		<AnimeTitleShortComponent item={item} />
	// 	</div>
	// 	)
	// );

	if (data) return React.Children.toArray(
		data.map((item: AnimeTitleShort) => 
		<>
			<div className='col-4'>
				<AnimeTitleShortComponent
					forceRefresh={() => InvalidateTitles(queryClient)}
					user={user}
					// item={TestRating(item)} />
					setRate={(value) => {
						// console.log(`Set rate (${value == null ? 'null' : value}) of [${rateObjectId}]`);
						if (value != null){
							return VoteAnimeTitle({
								animeTitleId: item.id,
								animeSeasonId: null,
								animeEpisodeId: null,
								ratingPercentage: value
							} as VoteEditModel);
						}
						else{
							return UnvoteAnimeTitle({
								animeTitleId: item.id,
								animeSeasonId: null,
								animeEpisodeId: null,
							} as VoteDeleteModel);
						}
					}}
					deleteRate={() => {
						// console.log(`Delete rate of [${rateObjectId}]`);
						return UnvoteAnimeTitle({
							animeTitleId: item.id,
							animeSeasonId: null,
							animeEpisodeId: null,
						} as VoteDeleteModel);
					}}
					item={item} />
			</div>
		</>
		)
	);
	else return (<div>Нет элементов</div>);
}

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