import React, { ChangeEvent, useState } from 'react'
import { TfiPlus } from 'react-icons/tfi';
import { Language } from '../../../../api/models/Types';
import { QueryClient, useQuery, useQueryClient } from 'react-query';
import LanguageItemEditComponent, { IsLanguageCodeValid, IsLanguageNameValid } from './LanguageItemEditComponent';
import ErrorInput from '../../../common/error/ErrorInput';
import ErrorField from '../../../common/error/ErrorField';
import { CreateLanguage, GetLanguageList } from '../../../../api/LanguageApi';

export const languageQueryKey = 'languages';

export default function LanguageListEditComponent() {
	const [newLanguageCode, SetNewLanguageCode] = useState<string>(''); 
	const OnNewLanguageCodeChange = (event : ChangeEvent<HTMLInputElement>) => SetNewLanguageCode(event.target.value);
	const [newLanguageName, SetNewLanguageName] = useState<string>(''); 
	const OnNewLanguageNameChange = (event : ChangeEvent<HTMLInputElement>) => SetNewLanguageName(event.target.value);
	const [createNewLanguageError, SetCreateNewLanguageError] = useState<string | null>(null);

	const [editingLanguageId, SetEditingLanguageId] = 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'}`)
		SetEditingLanguageId(value ? genreId : null)
	};

	const [deletingLanguageId, SetDeletingLanguageId] = useState<string | null>(null);
	const SetDeleting = (genreId: string, value: boolean) => {
		// console.log(`deleting [${genreId}]: ${value ? 'true' : 'false'}`)
		SetDeletingLanguageId(value ? genreId : null)
	};
	
	const { data, isLoading, isError, error } = useQuery(languageQueryKey, GetLanguageList);
	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={createNewLanguageError}>
					<ErrorInput error={createNewLanguageError}>
						<div className="input-group">
							<ErrorInput error={createNewLanguageError} errorClassses={'border-danger'} >
								<input className="form-control" type="text" required={true} placeholder="Код ISO 639.2 Alpha-3" onChange={OnNewLanguageCodeChange} value={newLanguageCode} minLength={3} maxLength={3} />
							</ErrorInput>

							<ErrorInput error={createNewLanguageError} errorClassses={'border-danger'} >
								<input className="form-control w-25" type="text" required={true} placeholder="Название языка" onChange={OnNewLanguageNameChange}  value={newLanguageName} />
							</ErrorInput>

							{/* <ErrorInput error={createNewLanguageError} errorClassses={'btn-outline-danger'}> */}
							<ErrorInput error={createNewLanguageError} errorClassses={'btn-danger'}>
								<button id='btn_add_language' type="submit" className='btn btn-primary'
									disabled={!IsLanguageNameValid(newLanguageName) || !IsLanguageCodeValid(newLanguageCode)}
									onClick={() => {
										if (IsLanguageNameValid(newLanguageName) && IsLanguageCodeValid(newLanguageCode)){
											CreateLanguage(newLanguageCode!, newLanguageName!).then(() => {
												SetCreateNewLanguageError(null)
												SetNewLanguageCode('');
												SetNewLanguageName('');
												InvalidateLanguages(queryClient);
											})
											.catch((error) =>{
												SetCreateNewLanguageError((error as Error)?.message)
												//console.error(error);
											});
										}
									}}>
									<span><TfiPlus /></span>
								</button>
							</ErrorInput>
						</div>
					</ErrorInput>
				</ErrorField>

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

			</div>

		</div>
  )
}

type ShowLanguagesProps = {
	data: Array<Language>,
	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 ShowLanguages(props: ShowLanguagesProps){
	if (props.isLoading){
		return (
			<>	
				<li className="list-group-item placeholder rounded">1. SomeLanguage</li>
				<li className="list-group-item placeholder rounded">2. SomeLanguage</li>
				<li className="list-group-item placeholder rounded">3. SomeLanguage</li>
			</>
		)
	}
	else if (props.isError){
		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: Language) => {
				return (
					<li className="list-group-item card p-0">
						<LanguageItemEditComponent language={item}
							isDeleting={props.isDeleting(item.id)}
							isEditing={props.isEdited(item.id)}
							enabled={!item.deleted}
							setDeleting={props.setDeleting}
							setEditing={props.setEdited}
							forceRefresh={() => InvalidateLanguages(props.queryClient)}
							/>
					</li>
				);
			})
		)
	}
}

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