import { ChangeEvent, useState } from 'react'
import { TfiCheck, TfiClose, TfiPencil, TfiTrash } from 'react-icons/tfi';
import { GenreProportion, Genre } from '../../../../api/models/Types';
import ErrorField from '../../../common/error/ErrorField';
import ErrorInput from '../../../common/error/ErrorInput';
import React from 'react';
import { GetNumericValue, GetPercentage } from '../../../../common/Helper';

export interface IGenreProportionItemEditComponentProps{
	genreProportion: GenreProportion,
	genres: Array<Genre>,
	enabled: boolean,
	
	valueMax: number,

	setEditing: (genreProportion: GenreProportion, value: boolean) => void,
	isEditing: boolean,
	editGenreProportion: (genreProportion: GenreProportion, proportionPercentage: number | null) => Promise<string | undefined>,
	
	setDeleting: (genreProportion: GenreProportion, value: boolean) => void,
	isDeleting: boolean,
	deleteGenreProportion: (genreProportion: GenreProportion) => Promise<string | undefined>,
	
	forceRefresh: () => void,
}

export default function GenreProportionItemEditComponent(props : IGenreProportionItemEditComponentProps) {
	const [editGenreProportionError, SetEditGenreProportionError] = useState<string | null>();
	const [genreProportionPercentage, setGenreIdProportionPercentage] = useState<number | null>();
	const onProportionPercentageChange = (event : ChangeEvent<HTMLInputElement>) => {
		const proportion = parseInt(event.target.value);
		setGenreIdProportionPercentage(!Number.isNaN(proportion) ? proportion : null);
	}
	React.useEffect(() => setGenreIdProportionPercentage(GetNumericValue(props.genreProportion.proportion, props.valueMax) ?? null), [props]);

	return(
		<ErrorField error={editGenreProportionError}>
			<ErrorInput error={editGenreProportionError}>
				<div className="input-group">
					
					<ErrorInput error={editGenreProportionError}>
						{/* <input className="form-select" aria-label="Язык названия" disabled={true} value={props.genreProportion.genre.name} /> */}
						<span className='form-control user-select-all bg-light-subtle'>{props.genreProportion.genre.name}</span>
					</ErrorInput>
					
					<ErrorInput error={editGenreProportionError}>
						<>
							{!props.isEditing &&
								<span className='form-control user-select-all bg-light-subtle'>{genreProportionPercentage ?? ''}</span>
							}
							{props.isEditing &&
								<input type="number" min={0} max={props.valueMax} className="form-control" id="newAnimeTitleName" placeholder="Доля жанра" onChange={onProportionPercentageChange}
									disabled={!props.isEditing}
									value={genreProportionPercentage ?? ''} />
							}
						</>
					</ErrorInput>

					{ ShowButtons(props, genreProportionPercentage, editGenreProportionError == undefined ? null : editGenreProportionError, SetEditGenreProportionError) }

				</div>
			</ErrorInput>
		</ErrorField>
	)
}

function ShowButtons(props: IGenreProportionItemEditComponentProps, genreProportion: number | null | undefined, editNameError: string | null, setEditGenreProportionError: (error: string | null) => void){
	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'
						onClick={() => 
								{
									if (genreProportion != props.genreProportion.proportion){
										props.editGenreProportion(props.genreProportion, genreProportion == null ? null : GetPercentage(genreProportion, props.valueMax))
										.then(() => {
											// console.log(`props.setEdited(${props.genre.id}, false)`)
											setEditGenreProportionError(null);
											props.setEditing(props.genreProportion, false);
											props.forceRefresh();
										})
										.catch((error: unknown) => setEditGenreProportionError((error as Error)?.message));
									}
									else{
										setEditGenreProportionError(null);
										props.setEditing(props.genreProportion, 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)`)
							setEditGenreProportionError(null);
							props.setEditing(props.genreProportion, 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.deleteGenreProportion(props.genreProportion)
									.then(() => {
										// console.log(`props.setEdited(${props.genre.id}, false)`)
										props.setDeleting(props.genreProportion, 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.genreProportion, 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.genreProportion, 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.genreProportion, true)}>
							<span><TfiTrash /></span>
					</button>
				</ErrorInput>
			</>
		);
	}
}

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