import { ChangeEvent, useState } from 'react'
import { TfiCheck, TfiClose, TfiPencil, TfiTrash } from 'react-icons/tfi';
import { NameItem, Language } from '../../../../api/models/Types';
import ErrorField from '../../../common/error/ErrorField';
import ErrorInput from '../../../common/error/ErrorInput';
import React from 'react';

export interface INameItemEditComponentProps{
	// name: NameItem | null | undefined,
	name: NameItem,
	languages: Array<Language>,
	enabled: boolean,
	
	setEditing: (nameItem: NameItem, value: boolean) => void,
	isEditing: boolean,
	editName: (name: NameItem, newValue: string | null, newLanguage: Language | null) => Promise<string | undefined>,
	
	setDeleting: (nameItem: NameItem, value: boolean) => void,
	isDeleting: boolean,
	deleteName: (name: NameItem) => Promise<string | undefined>,
	
	forceRefresh: () => void,
}

export default function NameItemEditComponent(props : INameItemEditComponentProps) {
	const [editNameError, SetEditNameError] = useState<string | null>();
	const [nameLanguageIdValue, setNameLanguageIdValue] = useState<[languageId: string | null, name: string | null]>();
	const selectLanguage = (id?: string | null) => setNameLanguageIdValue( [ (id == nameLanguageIdValue?.[0] ? null : id) ?? null, nameLanguageIdValue?.[1] ?? null, ] );
	const onNameChange = (event : ChangeEvent<HTMLInputElement>) => setNameLanguageIdValue( [ nameLanguageIdValue?.[0] ?? null, event.target.value ?? null, ] );
	React.useEffect(() => setNameLanguageIdValue([ props.name.language.id, props.name.value, ]), [props]);

	return(
		<ErrorField error={editNameError}>
			<ErrorInput error={editNameError}>
				<div className="input-group">
					
					<ErrorInput error={editNameError}>
						<>
							{!props.isEditing &&
								<span className='form-control bg-light-subtle'>
									{
										props.languages
												.map(q => { return {id:q.id, value:`${q.name} [${q.codeIso3}]`} })
												.find(q => q.id == nameLanguageIdValue?.[0])?.value ?? ''
									}
								</span>
							}
							{props.isEditing &&
								<select className="form-select" aria-label="Язык названия" onChange={(event) => selectLanguage(event.target.value)}
									disabled={!props.isEditing}
									value={nameLanguageIdValue?.[0] ?? ''}
									>
									<option value={''} >Выберите язык названия</option>
									{props.languages.length > 0 && ////WRONG!!!!
										React.Children.toArray(
											props.languages.map((language) => 
												<option value={language.id}>
													{language.name} [{language.codeIso3}]
												</option>
											))
									}
								</select>
							}
						</>
					</ErrorInput>
					
					<ErrorInput error={editNameError}>
						<>
							{!props.isEditing &&
								<span className='form-control user-select-all bg-light-subtle'>{nameLanguageIdValue?.[1] ?? ''}</span>
							}
							{props.isEditing &&
								<input type="text" className={'form-control' + (!props.isEditing ? ' user-select-all' : '')} id="newAnimeTitleName" placeholder="Название" onChange={onNameChange}
									disabled={!props.isEditing}
									value={nameLanguageIdValue?.[1] ?? ''} />
							}
						</>
					</ErrorInput>

					{/* <ErrorInput error={editNameError} errorClassses={'btn-danger'}>
						<button type="submit" className='btn btn-primary'
							disabled={!IsLanguageValid(nameLanguageIdValue?.[0]) || !IsNameValid(nameLanguageIdValue?.[1])}
							onClick={() => {
								if (nameLanguageIdValue != undefined && nameLanguageIdValue != null && IsNameValid(nameLanguageIdValue[1])){
									props.createName({
										languageId: nameLanguageIdValue[0],
										value: nameLanguageIdValue[1],
										type: nameTypeSelected
									} as TitleCreateNameModel).then(() => {
										setCreateNewNameError(null);
										// forseRes
										// props.ref(queryClient);
									})
									.catch((error: unknown) =>{
										setCreateNewNameError((error as Error)?.message);
										//console.error(error);
									});
									console.log(JSON.stringify({
											languageId: nameLanguageIdValue[0],
											value: nameLanguageIdValue[1],
											type: nameTypeSelected
										} as TitleCreateNameModel));
								}
							}}>
								<span><TfiPlus /></span>
						</button>
					</ErrorInput> */}
					{ ShowButtons(props, nameLanguageIdValue?.[1], nameLanguageIdValue?.[0], editNameError == undefined ? null : editNameError, SetEditNameError) }
				</div>
				{/* <div className="input-group">
					<ErrorInput error={editGenreError}>
					<input className="form-control" type="text" required={true} placeholder="Жанр" onChange={OnGenreNameChange} value={inputValue} readOnly={!props.isEditing} disabled={!props.enabled}/>
					</ErrorInput>

					{ ShowItem(props, inputValue, editGenreError == undefined ? null : editGenreError, SetEditGenreError) }
				</div> */}
			</ErrorInput>
		</ErrorField>
	)
}

function ShowButtons(props: INameItemEditComponentProps, newNameValue: string | null | undefined, languageSelectedId: string | null | undefined, editNameError: string | null, setEditNameError: (error: string | null) => void){
	const isError = !IsLanguageValid(languageSelectedId) || !IsNameValid(newNameValue);
	if (props.isEditing){
		return (
			<>
				<ErrorInput error={editNameError} errorClassses={'btn-outline-danger'}>
					{/* <button id={GetElementId('btn_edit_language_submit', props.name.id)} type="button" className='btn btn-success' disabled={isError} */}
					<button type="button" className='btn btn-success' disabled={isError}
						onClick={() => 
								{
									if (!IsLanguageValid(languageSelectedId) || !IsNameValid(newNameValue)) return;
									if (languageSelectedId != props.name.language.id || newNameValue != props.name.value){
										props.editName(props.name, newNameValue ?? null, languageSelectedId != null ? props.languages.find(q => q.id == languageSelectedId) ?? null : null)
										.then(() => {
											// console.log(`props.setEdited(${props.genre.id}, false)`)
											setEditNameError(null);
											props.setEditing(props.name, false);
											props.forceRefresh();
										})
										.catch((error: unknown) => setEditNameError((error as Error)?.message));
									}
									else{
										setEditNameError(null);
										props.setEditing(props.name, false);
									}
								}
							}>
						<span><TfiCheck /></span>
					</button>
				</ErrorInput>

				<ErrorInput error={editNameError} errorClassses={'btn-outline-danger'}>
					{/* <button id={GetElementId('btn_edit_genre_reject', props.genre.id)} type="button" className='btn btn-primary' */}
					<button type="button" className='btn btn-primary'
						onClick={() => {
							// console.log(`props.setEdited(${props.genre.id}, false)`)
							setEditNameError(null);
							props.setEditing(props.name, false);
						}}>
						<span><TfiClose /></span>
					</button>
				</ErrorInput>
			</>
		);
	}
	else if (props.isDeleting){
		return (
			<>
				<ErrorInput error={editNameError} errorClassses={'btn-outline-danger'}>
					{/* <button id={GetElementId('btn_edit_genre_submit', props.genre.id)} type="button" className='btn btn-danger' */}
					<button type="button" className='btn btn-danger'
						onClick={() => 
							{
								props.deleteName(props.name)
									.then(() => {
										// console.log(`props.setEdited(${props.genre.id}, false)`)
										props.setDeleting(props.name, false);
										props.forceRefresh();
									});
							}
						}>
							<span><TfiTrash /></span>
					</button>
				</ErrorInput>

				<ErrorInput error={editNameError} errorClassses={'btn-outline-danger'}>
					{/* <button id={GetElementId('btn_edit_genre_reject', props.genre.id)} type="button" className='btn btn-primary' */}
					<button type="button" className='btn btn-primary'
						onClick={() => props.setDeleting(props.name, false)}>
							<span><TfiClose /></span>
					</button>
				</ErrorInput>
			</>
		);
	}
	else{
		return (
			<>

				<ErrorInput error={editNameError} errorClassses={'btn-outline-danger'}>
					{/* <button id={GetElementId('btn_switch_to_genre_edit_mode', props.genre.id)} type="button" className='btn btn-primary' disabled={!props.enabled} */}
					<button type="button" className='btn btn-primary' disabled={!props.enabled}
						onClick={() => props.setEditing(props.name, true)}>
							<span><TfiPencil /></span>
					</button>
				</ErrorInput>

				<ErrorInput error={editNameError} errorClassses={'btn-outline-danger'}>
					{/* <button id={GetElementId('btn_switch_to_genre_delete_mode', props.genre.id)} type="button" className='btn btn-danger' disabled={!props.enabled} */}
					<button type="button" className='btn btn-danger' disabled={!props.enabled}
						onClick={() => props.setDeleting(props.name, true)}>
							<span><TfiTrash /></span>
					</button>
				</ErrorInput>
			</>
		);
	}
}

export function IsLanguageValid(languageId: string | null | undefined){
	return languageId != null && languageId != undefined && languageId.length > 0;
}

export function IsNameValid(name: string | null | undefined){
	return name != null && name != undefined && name.length > 0;
}