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

export interface IDescriptionItemEditComponentProps{
	// name: NameItem | null | undefined,
	description: Description,
	languages: Array<Language>,
	enabled: boolean,

	setDeleting: (description: Description, value: boolean) => void,
	isDeleting: boolean,
	deleteDescription: (description: Description) => Promise<string | undefined>,

	setEditing: (description: Description, value: boolean) => void,
	isEditing: boolean,
	editDescription: (description: Description, newValue: string | null, newLanguage: Language | null) => Promise<string | undefined>,

	forceRefresh: () => void,
}

export function IsGenreNameValid(value: string | undefined){
	return !(value == undefined || value.trim().length == 0)
}

export default function DescriptionItemEditComponent(props : IDescriptionItemEditComponentProps) {
	const [editDescriptionError, SetEditDescriptionError] = useState<string | null>();
	const [descriptionLanguageIdValue, selectDescriptionLanguageIdValue] = useState<[languageId: string | null, name: string | null]>();
	const selectLanguage = (id?: string | null) => selectDescriptionLanguageIdValue( [ (id == descriptionLanguageIdValue?.[0] ? null : id) ?? null, descriptionLanguageIdValue?.[1] ?? null, ] );
	const onDescriptionChange = (event : ChangeEvent<HTMLTextAreaElement>) => selectDescriptionLanguageIdValue( [ descriptionLanguageIdValue?.[0] ?? null, event.target.value ?? null, ] );
	React.useEffect(() => selectDescriptionLanguageIdValue([ props.description.language.id, props.description.value, ]), [props]);

	return(
		<ErrorField error={editDescriptionError}>
			<div className='row'>
				{!props.isEditing &&
					<div className='col-9'>
						<div className='overflow-x-hidden overflow-y-auto bg-dark rounded rounded-end-0 border' style={{height:'10rem'}} >
							<div className='container py-2' style={{minHeight:'10rem'}}>
								{descriptionLanguageIdValue?.[1]}
							</div>
						</div>
					</div>
				}
				{props.isEditing &&
					<div className='col-9 overflow-x-hidden overflow-y-auto ' style={{height:'10rem'}}>
						<ErrorInput error={editDescriptionError}>
							{/* <textarea type="text" className="form-control" id="newAnimeTitleName" placeholder="Название" onChange={onNameChange} */}
							<textarea className="form-control" placeholder="Описание" style={{minHeight:'10rem'}} onChange={onDescriptionChange}
								disabled={!props.isEditing}
								value={descriptionLanguageIdValue?.[1] ?? ''}></textarea>
							{/* <input type="text" className="form-control" id="newAnimeTitleName" placeholder="Название" onChange={onNameChange}
								disabled={!props.isEditing}
								value={descriptionLanguageIdValue?.[1] ?? ''} /> */}
						</ErrorInput>
					</div>
				}
				<div className='col'>
					<ErrorInput error={editDescriptionError}>
						<div className="input-group">
							<ErrorInput error={editDescriptionError}>
								<>
									{!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 == descriptionLanguageIdValue?.[0])?.value ?? ''
											}
										</span>
									}
									{props.isEditing &&
										<select className="form-select" aria-label="Язык описания" onChange={(event) => selectLanguage(event.target.value)}
										disabled={!props.isEditing}
										value={descriptionLanguageIdValue?.[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>

							{ ShowButtons(props, descriptionLanguageIdValue?.[1], descriptionLanguageIdValue?.[0], editDescriptionError == undefined ? null : editDescriptionError, SetEditDescriptionError) }
						</div>
					</ErrorInput>					
				</div>
			</div>
		</ErrorField>
	)
}

function ShowButtons(props: IDescriptionItemEditComponentProps, newDescriptionValue: string | null | undefined, languageSelectedId: string | null | undefined, editDescriptionError: string | null, setEditDescriptionError: (error: string | null) => void){
	const isError = !IsLanguageValid(languageSelectedId) || !IsDescriptionValid(newDescriptionValue);
	if (props.isEditing){
		return (
			<>
				<ErrorInput error={editDescriptionError} 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) || !IsDescriptionValid(newDescriptionValue)) return;
									if (languageSelectedId != props.description.language.id || newDescriptionValue != props.description.value){
										props.editDescription(props.description, newDescriptionValue ?? null, languageSelectedId != null ? props.languages.find(q => q.id == languageSelectedId) ?? null : null)
										.then(() => {
											setEditDescriptionError(null);
											props.setEditing(props.description, false);
											props.forceRefresh();
										})
										.catch((error: unknown) => setEditDescriptionError((error as Error)?.message));
									}
									else{
										setEditDescriptionError(null);
										props.setEditing(props.description, false);
									}
								}
							}>
						<span><TfiCheck /></span>
					</button>
				</ErrorInput>

				<ErrorInput error={editDescriptionError} 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)`)
							setEditDescriptionError(null);
							props.setEditing(props.description, false);
						}}>
						<span><TfiClose /></span>
					</button>
				</ErrorInput>
			</>
		);
	}
	else if (props.isDeleting){
		return (
			<>
				<ErrorInput error={editDescriptionError} 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.deleteDescription(props.description)
									.then(() => {
										props.setDeleting(props.description, false);
										props.forceRefresh();
									});
							}
						}>
							<span><TfiTrash /></span>
					</button>
				</ErrorInput>

				<ErrorInput error={editDescriptionError} 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.description, false)}>
							<span><TfiClose /></span>
					</button>
				</ErrorInput>
			</>
		);
	}
	else{
		return (
			<>

				<ErrorInput error={editDescriptionError} 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.description, true)}>
							<span><TfiPencil /></span>
					</button>
				</ErrorInput>

				<ErrorInput error={editDescriptionError} 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.description, true)}>
							<span><TfiTrash /></span>
					</button>
				</ErrorInput>
			</>
		);
	}
}

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

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