import React, { ChangeEvent, useRef, useState } from 'react'
import { MediaInfoType } from '../../../api/models/Types'
import MediaInfoComponent, { MediaInfoModel } from '../view/MediaInfoComponent'
import { TfiCheck, TfiClose, TfiFile, TfiPencil, TfiTrash, TfiWorld } from 'react-icons/tfi'
import ErrorInput from '../error/ErrorInput'
import { InputType, MediaInfoEditModel } from './MediaInfoTypes'

export interface IMediaInfoComponentProps{
	mediaInfo?: MediaInfoEditModel | null,
	dataLoadingError: Error | null,
	//mediaInfoType?: MediaInfo | null
	
	inputTypeFilter?: InputType | null,

	classes?: string | null,
	
	setEditing: (mediaInfo: MediaInfoEditModel | null, value: boolean) => void,
	isEditing: boolean,
	editMediaInfo: (mediaInfo: MediaInfoEditModel | null, newUrl: string | null, newFile: File | null) => Promise<string | undefined>

	setDeleting: (mediaInfo: MediaInfoEditModel, value: boolean) => void,
	isDeleting: boolean,
	deleteMediaInfo: (mediaInfo: MediaInfoEditModel) => Promise<string | undefined>
	
	forceRefresh: () => void,
}



export default function MediaInfoEditComponent(props: IMediaInfoComponentProps) {
	// const [url, setUrlValue] = useState<string>(GetUrl(props.mediaInfo?.url));
	const [selectedInputType, setSelectedInputType] = useState<InputType>(InputType.Url);
	const fileInputRef = useRef<HTMLInputElement>(null);
	const [editMediaInfoError, SetEditMediaInfoError] = useState<string | null>(null);
	const [urlFileValue, setUrlFileValue] = useState<[url: string | null, file: File | null]>([null, null]);
	const [preview, setPreview] = useState<MediaInfoModel | null>(null);
	const setUrl = async (url?: string | null) => {
		if (url != null && url == urlFileValue?.[0]){
			return;
		}
		else{
			const urlValue = url != null && url.length > 0 ? url : null;
			// const contentType = urlValue == null ? null :  await GetContentType(urlValue) ?? null;
			if (fileInputRef.current?.value != null){
				fileInputRef.current.value = '';
			}
			setUrlFileValue( [ urlValue, null ] );
			setPreview(CreateMediaInfo(props.mediaInfo, urlValue));
		}
	};

	const setFile = async (file?: File | null) => {
		// setUrlContentTypeFileValue( [ urlContentTypeFileValue[0], urlContentTypeFileValue[1], file ] );
		setUrlFileValue( [ null, file ?? null ] );
		setPreview(await mediaInfoFromFile(file ?? null, props.mediaInfo ?? null));
	};

	React.useEffect(() => {
		// const url = (props.mediaInfo?.isNew == true) || (props.inputTypeFilter != InputType.File) ? '' : GetUrl(props.mediaInfo?.url);
		const url = (props.mediaInfo?.isNew == true) || (props.inputTypeFilter == InputType.Url) ? '' : GetUrl(props.mediaInfo?.url);
		// console.log(`url: ${url}`);
		setUrlFileValue([ url, props.mediaInfo?.data ?? null ]);
		if (props.mediaInfo?.data != null && props.inputTypeFilter != InputType.Url){
			mediaInfoFromFile(props.mediaInfo.data, props.mediaInfo ?? null)
			.then((mediaInfo) => setPreview(mediaInfo))
		}
		else{
			setPreview(CreateMediaInfo(props.mediaInfo, props.mediaInfo?.url));
		}
	}, [props]);

	// const [mediaInfo, setMediaInfoValue] = useState<MediaInfo | null | undefined>(props.mediaInfo)
	const onUrlChanged = (event : ChangeEvent<HTMLInputElement>) => setUrl(event.target.value ?? null);
	const onFileChanged = (event : ChangeEvent<HTMLInputElement>) => {
		const file = event.target.files?.[0] ?? null;
		setFile(file);
	};
	return(
		<>
			<br/>
			<div className='d-flex justify-content-center'>
				<MediaInfoComponent
					classes={props.classes}
					mediaInfo={preview}
					/>
			</div>
			{!props.isEditing &&
				<div className="input-group mt-2">
					{props.dataLoadingError == null &&
						<>
							<ErrorInput  error={editMediaInfoError}>
								<span className={'form-control user-select-all bg-light-subtle ' + (urlFileValue?.[1] != null ? 'text-primary' : (props.mediaInfo?.isNew == true ? 'text-warning' : 'text-secondary')) +
									(urlFileValue?.[1] != null || props.mediaInfo?.isNew == true ? ' text-center' : '')}>
									{urlFileValue?.[0] != null && urlFileValue?.[0] != '' && 
										GetUrl(urlFileValue?.[0])
									}
									{urlFileValue?.[1] != null && 
										<b>Файл</b>
									}
									{(urlFileValue?.[1] == null && props.mediaInfo?.isNew == true) &&
										<b>Сохранённый объект</b>
									}
								</span>
							</ErrorInput>

							{ShowErrorButtons(props, urlFileValue?.[0], urlFileValue?.[1], editMediaInfoError == undefined ? null : editMediaInfoError,
								SetEditMediaInfoError, selectedInputType, () => { setSelectedInputType(selectedInputType == InputType.Url ? InputType.File : InputType.Url) })}
						</>
					}
					{props.dataLoadingError != null &&
						<input type='text' className='form-control bg-danger' placeholder="Url" disabled={true} value={props.dataLoadingError.message ?? 'unknown'} />
					}
				</div>
			}
			{props.isEditing &&
				<>
						<div className='row mt-2'>
							<div className='col'>
								<ErrorInput  error={editMediaInfoError}>
									<>
										{props.inputTypeFilter != InputType.File &&
											<div className='row'>
												<div className='col'>
													<input type='text' className='form-control' placeholder="Url" onChange={onUrlChanged}
														disabled={!props.isEditing}
														value={GetUrl(urlFileValue?.[0])}/>
												</div>
											</div>
										}
										
										{props.inputTypeFilter != InputType.Url &&
											<div className='row'>
												<div className='col'>
													<input type='file' className='form-control' ref={fileInputRef} onChange={onFileChanged} disabled={!props.isEditing}/>
												</div>
											</div>
										}
									</>
								</ErrorInput>
							</div>
							<div className='col-auto'>
								{/* {ShowButtons(props, urlContentTypeFileValue?.[1], urlContentTypeFileValue?.[0], urlContentTypeFileValue?.[2], editMediaInfoError == undefined ? null : editMediaInfoError,
								SetEditMediaInfoError, selectedInputType, () => { setSelectedInputType(selectedInputType == InputType.url ? InputType.file : InputType.url) })} */}
								<div className='input-group h-100'>
									<ErrorInput error={editMediaInfoError == undefined ? null : editMediaInfoError} errorClassses={'btn-outline-danger'}>
										{/* <button id={GetElementId('btn_edit_language_submit', props.name.id)} type="button" className='btn btn-success' disabled={isError} */}
										<div className={'btn btn-success' + ((!IsUrlValud(urlFileValue?.[0]) && urlFileValue?.[1] == null) ? ' disabled' : '')}
											onClick={() => 
													{
														const newUrl = urlFileValue?.[0];
														const newFile = urlFileValue?.[1];
														if (!IsUrlValud(newUrl) && newFile == null) return;
														if (newUrl != props.mediaInfo?.url || newFile != null){
															// props.editMediaInfo(props.mediaInfo ?? null, newContentType ?? null, newUrl ?? null)
															props.editMediaInfo(props.mediaInfo ?? null, newUrl ?? null, newFile ?? null)
															.then(() => {
																// console.log(`props.setEdited(${props.genre.id}, false)`)
																// setEditNameError(null);
																props.setEditing(props.mediaInfo ?? null, false);
																props.forceRefresh();
															})
															// .catch((error: unknown) => setEditNameError((error as Error)?.message));
														}
														else{
															props.setEditing(props.mediaInfo ?? null, false);
														}
														props.setEditing(props.mediaInfo ?? null, false);
													}
												}>
											<span><TfiCheck className='h-100' /></span>
										</div>
									</ErrorInput>

									<ErrorInput error={editMediaInfoError == undefined ? null : editMediaInfoError} errorClassses={'btn-outline-danger'}>
										{/* <button id={GetElementId('btn_edit_genre_reject', props.genre.id)} type="button" className='btn btn-primary' */}
										<div className='btn btn-primary h-100'
											onClick={() => {
												// console.log(`props.setEdited(${props.genre.id}, false)`)
												SetEditMediaInfoError(null);
												props.setEditing(props.mediaInfo ?? null, false);
											}}>
											<span><TfiClose className='h-100' /></span>
										</div>
									</ErrorInput>
								</div>
							</div>
						</div>
				</>
			}
		</>
	)
}

function mediaInfoFromFile(file: Blob | null, propsMediainfo: MediaInfoEditModel | null) : Promise<MediaInfoModel | null>{
	//return  new Promise<MediaInfo | null>((resolve, reject) => {
	return 	new Promise<MediaInfoModel | null>((resolve) => {
			if (file == null) return resolve(null)
			const reader = new FileReader();
		  reader.readAsDataURL(file);
		  reader.onload = () =>
			typeof reader.result === "string" ? resolve({
				type: propsMediainfo?.type ?? MediaInfoType.Image,
				data: reader.result
			} as MediaInfoModel) : resolve(null);
		//   reader.onerror = error => reject(error);
		//   reader.onerror = error => console.error(error);
		});
}

function CreateMediaInfo(mediaInfo: MediaInfoEditModel | null | undefined, value: string | null | undefined) : MediaInfoModel | null{
	if (value != undefined && value != null && value.length){
		const isMediaInfoDefined = mediaInfo != undefined && mediaInfo != null;
		return {
			type: isMediaInfoDefined ? mediaInfo.type : MediaInfoType.Image,
			data: value,
		} as MediaInfoModel;
	}
	return null;	
}

function GetUrl(url: string | undefined | null){
	return url == undefined || url == null ? '' : url;
}

function ShowErrorButtons(props: IMediaInfoComponentProps, newUrl: string | null | undefined, newFile: File | null | undefined,
	editMediInfoError: string | null,
	setEditMediInfoError: (error: string | null) => void,
	selectedInputType: InputType,
	toggleSelectedInputType: () => void,
	){
	const isError = !IsUrlValud(newUrl) && newFile == null;
if (props.isDeleting){
		return (
			<>
				<ErrorInput error={editMediInfoError} 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' disabled={props.mediaInfo == undefined || props.mediaInfo == null}
						onClick={() => 
							{
								if (props.mediaInfo != undefined && props.mediaInfo != null){
									props.deleteMediaInfo(props.mediaInfo!)
										.then(() => {
											// console.log(`props.setEdited(${props.genre.id}, false)`)
											props.setDeleting(props.mediaInfo!, false);
											props.forceRefresh();
										});
								}
							}
						}>
							<span><TfiTrash /></span>
					</button>
				</ErrorInput>

				<ErrorInput error={editMediInfoError} 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' disabled={props.mediaInfo == undefined || props.mediaInfo == null}
						onClick={() => props.setDeleting(props.mediaInfo!, false)}>
							<span><TfiClose /></span>
					</button>
				</ErrorInput>
			</>
		);
	}
	else{
		return (
			<>

				<ErrorInput error={editMediInfoError} 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} */}
					<button type="button" className='btn btn-primary'
						onClick={() => props.setEditing(props.mediaInfo ?? null, true)}>
							<span><TfiPencil /></span>
					</button>
				</ErrorInput>

				<ErrorInput error={editMediInfoError} 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.mediaInfo == undefined || props.mediaInfo == null}
						onClick={() => props.setDeleting(props.mediaInfo!, true)}>
							<span><TfiTrash /></span>
					</button>
				</ErrorInput>
			</>
		);
	}
}

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