import React, { ChangeEvent, useState } from 'react'
import { TfiPlus } from 'react-icons/tfi';
import { Genre } from '../../../../api/models/Types';
import { GetGenreList, CreateGenre } from '../../../../api/GenreApi';
import { QueryClient, useQuery, useQueryClient } from 'react-query';
import GenreItemEditComponent, { IsGenreNameValid } from './GenreItemEditComponent';
import ErrorInput from '../../../common/error/ErrorInput';
import ErrorField from '../../../common/error/ErrorField';

export const genresQueryKey = 'genres';

export default function GenreListEditComponent() {
	const [newGenreName, SetNewGenreName] = useState<string>(''); 
	const OnNewGenreNameChange = (event : ChangeEvent<HTMLInputElement>) => SetNewGenreName(event.target.value);
	const [createNewGenreError, SetCreateNewGenreError] = useState<string | null>(null);

	const [editingGenreId, SetEditingGenreId] = useState<string | null>(null);
	//const SetEdited = (genreId: string, value: boolean) => SetEditedGenreId(value ? genreId : null);
	const SetEditing = (genreId: string, value: boolean) => {
		// console.log(`editing [${genreId}]: ${value ? 'true' : 'false'}`)
		SetEditingGenreId(value ? genreId : null)
	};

	const [deletingGenreId, SetDeletingGenreId] = useState<string | null>(null);
	//const SetEdited = (genreId: string, value: boolean) => SetEditedGenreId(value ? genreId : null);
	const SetDeleting = (genreId: string, value: boolean) => {
		// console.log(`deleting [${genreId}]: ${value ? 'true' : 'false'}`)
		SetDeletingGenreId(value ? genreId : null)
	};
	
	// const selectedGenreIds = new Set<string>();
	// // const [selectedGenreIds, SetSelectedGenreId] = useState<Set<string>>();
	// const SetSelected = (genreId: string, value: boolean) => {
	// 	if (value) selectedGenreIds?.add(genreId);
	// 	else selectedGenreIds?.delete(genreId);
	// }
	
	const { data, isLoading, isError, error } = useQuery(genresQueryKey, GetGenreList);
	const queryClient = useQueryClient();
	
	return (
		<div className='card bg-body-tertiary p-0'>
			<div className='card-header'>
				<h4 className='card-title'>Жанры</h4>
			</div>
			<div className='card-body'>

			<ErrorField error={createNewGenreError}>
					<ErrorInput error={createNewGenreError}>
						<div className="input-group">
							<ErrorInput error={createNewGenreError} errorClassses={'border-danger'} >
								<input className="form-control" type="text" required={true} placeholder="Жанр" onChange={OnNewGenreNameChange}  value={newGenreName} />
							</ErrorInput>

							<ErrorInput error={createNewGenreError} errorClassses={'btn-danger'}>
								<button id='btn_add_genre' type="submit" className='btn btn-primary'
									disabled={!IsGenreNameValid(newGenreName)}
									onClick={() => {
										if (IsGenreNameValid(newGenreName)){
											CreateGenre(newGenreName!).then(() => {
												SetCreateNewGenreError(null)
												SetNewGenreName('');
												InvalidateGenres(queryClient);
											})
											.catch((error) =>{
												SetCreateNewGenreError((error as Error)?.message)
												//console.error(error);
											});
										}
									}}>
										<span><TfiPlus /></span>
								</button>
							</ErrorInput>
						</div>
					</ErrorInput>
				</ErrorField>

				<hr />
				<ul className="list-group gap-2">
					{
						ShowGenres(
							{
								data: data ?? [],
								isLoading: isLoading,
								isError: isError,
								error: error as Error,
								queryClient: queryClient,
								setDeleting: SetDeleting,
								isDeleting: (genreId: string) => deletingGenreId == genreId,
								setEdited: SetEditing,
								isEdited: (genreId: string) => editingGenreId == genreId,
							}) 
					}
				</ul>

			</div>
		</div>
	)
}

type ShowGenresProps = {
	data: Array<Genre>,
	isLoading: boolean,
	isError: boolean,
	error: Error | undefined,
	queryClient: QueryClient,
	setDeleting: (genreId: string, value: boolean) => void,
	isDeleting: (genreId: string) => boolean,
	setEdited: (genreId: string, value: boolean) => void,
	isEdited: (genreId: string) => boolean,
}

function ShowGenres(props: ShowGenresProps){
	if (props.isLoading){
		return (
			<>
				<li className="list-group-item placeholder rounded">1. SomeGenre</li>
				<li className="list-group-item placeholder rounded">2. SomeGenre</li>
				<li className="list-group-item placeholder rounded">3. SomeGenre</li>
			</>
		)
	}
	else if (props.isError){
	// else if (true){
		return (
			<li className="list-group-item card p-0">
				<div className='card-header bg-danger'>
					<h4 className='card-heading'>{props.error?.name ?? 'Unknown error'}</h4>
				</div>
				<div className='card-body bg-danger bg-opacity-50'>
					{/* Error occured during fetching items: */}
					<span>{props.error?.message ?? 'unknown'}</span>
				</div>
			</li>
		)
	}
	else{
		return React.Children.toArray(
			props.data.map((item: Genre) => {
				return (
					<GenreItemEditComponent genre={item}
					isDeleting={props.isDeleting(item.id)}
					isEditing={props.isEdited(item.id)}
					enabled={!item.deleted}
					setDeleting={props.setDeleting}
					setEditing={props.setEdited}
					forceRefresh={() => InvalidateGenres(props.queryClient)}
					/>
					
				);
			})
		)
	}
}

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