import React, { useState } from 'react'
import { CreateMediaInfoModel, CreateNameModel, Language, MediaInfoType, NameItem, Season, AnimeTitleCreateModel, AnimeSeasonCreateModel, CreateGenreProportionModel, CreateDescriptionModel } from '../../../../../api/models/Types';
import { MediaInfoEditModel } from '../../../../common/edit/MediaInfoTypes';
import MediaInfoEditComponent from '../../../../common/edit/MediaInfoEditComponent';
import NamesEditComponent from '../../Names/NamesEditComponent';
import DateEditComponent from '../../../../common/edit/DateEditComponent';
import { GetDate } from '../../../../../common/Helper';
import { TfiPlus } from 'react-icons/tfi';
import { UserInfo } from '../../../../../api/models/AccountTypes';
import AnimeItemShortComponent from './AnimeItemShortComponent';

export interface IAnimeSeasonAddComponentProps{
	titleId: string,
	seasons: Array<Season>,
	user: UserInfo,
}

export default function AnimeSeasonAddComponent(props : IAnimeSeasonAddComponentProps) {
	const [ names, setNames ] = useState<Array<NameItem>>([]);
	const addName = (nameItem: NameItem) => {
		if (names.find(q => q.language.id == nameItem.language.id && q.type == nameItem.type && q.value == nameItem.value)){
			return 'Name already exists';
		}
		else {
			const obj = names;
			names.push(nameItem);
			setNames(obj);
			return '';
		}
	}
	const editName = (nameItem: NameItem, newValue: string | null, newLanguage: Language | null) => {
		const obj = names;
		const name = obj.find(q => q.language == nameItem.language && q.type == nameItem.type && q.value == nameItem.value);
		if (name != null){
			if (newValue != null) name.value = newValue;
			if (newLanguage != null) name.language = newLanguage;
			setNames(obj);
		}
	}
	const deleteName = (nameItem: NameItem) => {
		const obj = names;
		setNames(obj.filter(q => !(q.language == nameItem.language && q.type == nameItem.type && q.value == nameItem.value)));
	}

	const [ preview, setPreview ] = useState<MediaInfoEditModel | null>(null);

	const [ announcementDate, setAnnouncementDate ] = useState<string | null>(null);
	const [ estimatedReleaseDate, setEstimatedReleaseDate ] = useState<string | null>(null);
	const setAnnouncementDate = (date: Date | null) => setAnnouncementDate(date == null ? null : date.toISOString());
	const setEstimatedReleaseDate = (date: Date | null) => setEstimatedReleaseDate(date == null ? null : date.toISOString());
	const [ number, setNumber ] = useState<number | null>(null);

	const [ isEditing, setIsEditingValue ] = useState<Array<string>>([]);
	const setEditing = (elementName: string, value: boolean) => {
		const alreadyEditing = isEditing.find(q => q == elementName) != null;
		if (value){
			if (!alreadyEditing){
				setIsEditingValue(isEditing.concat([elementName]))
			}
		}
		else{
			if (alreadyEditing){
				setIsEditingValue(isEditing.filter(q => q != elementName))
			}
		}
	};

	const [ isDeleting, setIsDeletingValue ] = useState<Array<string>>([]);
	const setDeleting = (elementName: string, value: boolean) => {
		const alreadyDeleting = isDeleting.find(q => q == elementName) != null;
		if (value){
			if (!alreadyDeleting){
				setIsDeletingValue(isDeleting.concat([elementName]))
			}
		}
		else{
			if (alreadyDeleting){
				setIsDeletingValue(isDeleting.filter(q => q != elementName))
			}
		}
	};

	const addSeason = async () => {
		const model = {
			animeTitleId: props.titleId,
			preview: preview == null ? null : {
				newType: preview.type,
				// newUrl: preview.objectId,
				newUrl: preview.url,
				newFile: preview.data
			} as CreateMediaInfoModel,
			names: names.map(q => {
				return {
					languageId: q.language.id,
					value: q.value,
					type: q.type,
				} as CreateNameModel
			}),
			descriptions: descriptions.map(q => {
				return {
					languageId: q.language.id,
					isOriginal: q.isOriginal,
					value: q.value,
				} as CreateDescriptionModel
			}),
			// relatedContent: relatedContent.map(q => {
			// 	return {
			// 		type: q.type,
			// 		contentType: q.contentType,
			// 		url: q.url,
			// 	} as CreateMediaInfoModel
			// }),
			relatedContent: [],
			genres: genres.map(q => {
				return {
					genreId: q.genre.id,
					proportion: q.proportion,
				} as CreateGenreProportionModel
			}),
			announcementDate: announcementDate,
			estimatedReleaseDate: estimatedReleaseDate,
			number: number,
		} as AnimeSeasonCreateModel
	};

	return (
		<div className='card p-0 bg-body-secondary'>
			<div className='card-header p-0'>
				<h3 className='card-title ms-2'>Сезоны</h3>

				<div className='row m-0 border py-2 border border-3 border-bottom-0'>
					<div className='col-2'>
						<MediaInfoEditComponent 
							mediaInfo={preview}
							classes={'card-img-top rounded-3 border border-5 border-secondary'}
							
							isEditing={isEditing.find(q => q == 'preview') != null}
							setEditing={(_, value) => setEditing('preview', value)}
							// editMediaInfo={(mediaInfo, newUrl, newFile) =>{
							editMediaInfo={(_, newUrl, newFile) =>{
								// console.log(`new url: ${newUrl}`)
								// SetPreview(mediaInfo == null ? null :
								setPreview((newUrl == null && newFile == null) ? null :
									{
										// type: mediaInfo?.type ?? MediaInfoType.Image,
										type: MediaInfoType.Image,
										url: newUrl,
										data : newFile,
										objectId: null,
										// isNew: false,
									} as MediaInfoEditModel);
								return Promise.resolve('');
							}}
							
							isDeleting={isDeleting.find(q => q == 'preview') != null}
							setDeleting={(_, value) => setDeleting('preview', value)}
							
							deleteMediaInfo={() => {
								setPreview(null);
								return Promise.resolve('');
							}}
							dataLoadingError={null}
							forceRefresh={Plug}
							/>
					</div>
					<div className='col'>
						<NamesEditComponent
							names={names}
							createName={(name) => {
								const error = addName({
									language: name.language,
									value: name.value,
									type: name.type
								} as NameItem);
								return error.length == 0 ? Promise.resolve('') : Promise.reject({ message: error} as Error);
							}}

							editName={(name, newValue, newLanguage) => {
								editName({
									language: name.language,
									value: name.value,
									type: name.type
								} as NameItem, newValue, newLanguage);
								return Promise.resolve('');
							}}

							deleteName={(name) => {
								deleteName({
									language: name.language,
									value: name.value,
									type: name.type
								} as NameItem);
								return Promise.resolve('');
							}}
							dataLoadingError={null}
							forceRefresh={Plug}
							/>

						<div className='card p-0 mt-2'>
							<div className='card-body p-0'>
								<div className='table-responsive'>
									<table className="table m-0">
										<tbody>
											<tr>
												<th>Дата анонса</th>
												<td className='text-end'>
													<DateEditComponent
														placeholder={'Дата анонса'}
														required={true}
														isEditing={isEditing.find(q => q == 'announcementDate') != null}
														enabled={true}
														date={GetDate(announcementDate)}
														editDate={(value: Date | null) => {
															setAnnouncementDate(value);
															return Promise.resolve();
														}}
														setEditing={(value: boolean) => setEditing('announcementDate', value)}
														// setDeleting: (genreId: string, value: boolean) => void,
														dataLoadingError={null}
														forceRefresh={Plug}
														/>
												</td>
											</tr>
											<tr>
												<th>Предполагаемая дата выхода</th>
												<td className='text-end'>
													<DateEditComponent
														placeholder={'Предполагаемая дата выхода'}
														required={true}
														isEditing={isEditing.find(q => q == 'estimatedReleaseDate') != null}
														enabled={true}
														
														date={estimatedReleaseDate != null ? new Date(estimatedReleaseDate) : null}
														editDate={(value: Date | null) => {
															setEstimatedReleaseDate(value);
															return Promise.resolve();
														}}
														setEditing={(value: boolean) => setEditing('estimatedReleaseDate', value)}
														// setDeleting: (genreId: string, value: boolean) => void,
														dataLoadingError={null}
														forceRefresh={Plug}
														/>
												</td>
											</tr>
										</tbody>
									</table>
								</div>
							</div>
						</div>

					</div>
				</div>
				<div className='row border border-3 border-top-0 m-0'>
					<div className='col text-center'>
						<div className='btn btn-primary w-25'>
							<TfiPlus />
						</div>
					</div>
				</div>

			</div>
			<div className='card-body'>
				{
					React.Children.toArray(
						props.seasons.sort(q => q.order).map((season) => 
							<AnimeItemShortComponent user={props.user} animeItem={season}
													 goToDetailPage={() => n}/>
						))
				}
			</div>
		</div>
	)
}

function Plug(){

}