import { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'
import { ClearAnimeTitlePreview, CreateAnimeTitleDescription, CreateAnimeTitleGenre, CreateAnimeTitleName, DeleteAnimeTitleDescription, DeleteAnimeTitleGenre, DeleteAnimeTitleName, EditAnimeTitleDescription, EditAnimeTitleGenre, EditAnimeTitleName, GetAnimeTitle, SetAnimeTitleAnnouncementDate, SetAnimeTitleEstimatedReleaseDate, SetAnimeTitlePreview, SetAnimeTitleReleaseDate } from '../../../api/AnimeTitleApi';
import { AnimeTitle, CreateDescriptionModel, CreateGenreProportionModel, CreateMediaInfoModel, CreateNameModel, DeleteDescriptionModel, DeleteGenreProportionModel, DeleteMediaInfoModel, DeleteNameModel, EditDateModel, EditDescriptionModel, EditGenreProportionModel, EditNameModel, MediaInfoType } from '../../../api/models/Types';
import MediaInfoEditComponent from '../../../components/common/edit/MediaInfoEditComponent';
import DateEditComponent from '../../../components/common/edit/DateEditComponent';
import NamesEditComponent from '../../../components/MediaContent/edit/Names/NamesEditComponent';
import DescriptionsEditComponent from '../../../components/MediaContent/edit/Descriptions/DescriptionsEditComponent';
import { GetDate } from '../../../common/Helper';
import GenreProportionEditComponent from '../../../components/MediaContent/edit/Genres/GenreProportionEditComponent';
import { MediaInfoEditModel } from '../../../components/common/edit/MediaInfoTypes';
import useUser from '../../../api/hooks/useUser';
import { useQuery } from 'react-query';
import { userQueryKey } from '../../../components/common/UserShortComponent';
import AnimeItemsEditComponent from '../../../components/MediaContent/edit/Anime/season/AnimeItemsEditComponent.tsx';

export default function AnimeTitleEdit() {
	// const client = axios.create();
	const client = null;
	
	const { getUser } = useUser();
	const { data: user } = useQuery(userQueryKey, getUser);
	
	const { id } = useParams();
	const [ data, setData ] = useState<AnimeTitle | null>(null);
	const [ dataLoadingError, setDataLoadingError ] = useState<Error | 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 fetchData = () => {
		GetAnimeTitle(id ?? '', client)
			.then((data) =>{
				setData(data ?? null);
				setDataLoadingError(null);
			})
			.catch((error) => {
				setData(null);
				console.log(error);
				setDataLoadingError(error);
			});
	}

	useEffect(fetchData, [ id ]);

	// const setPreview = (mediaInfo: MediaInfo | null | undefined) => {
	// 	// setAnimeTitlePreview(
	// 	// 	[
	// 	// 		languageIdNamePreview?.[0] ?? null,
	// 	// 		languageIdNamePreview?.[1] ?? null,
	// 	// 		mediaInfo ?? null
	// 	// 	]
	// 	// );
	// };

	// if ((id != undefined && id != null) && data == null) return (<h2>Не загрузилось чота"</h2>);
	// if ((id != undefined && id != null) && data == null) return (<h2>Не загрузилось чота"</h2>);
	return (
		<>
			{/* {data &&
				<AnimeTitleDetailComponent 
					animeTitle={data}
					userLanguageId = '2c16c758-bd85-42e9-9e0e-3bc4e382aa47'
					// setRate={props.setRate}
					// deleteRate={props.deleteRate}
					// forceRefresh={props.forceRefresh}
					setRate={async (rateObjectId: string, value: number | null) => {
						console.log(`Set rate (${value == null ? 'null' : value}) of [${rateObjectId}]`);
						return Promise.resolve();
					}}
					deleteRate={async (rateObjectId: string) => {
						console.log(`Delete rate of [${rateObjectId}]`);
						return Promise.resolve();
					}}
					forceRefresh={() => console.log(`Refresh title detail [${data.id}]`)}
					/>
			} */}
			{/* {data && */}
			{
				<>
					<div className='row overflow-x-hidden overflow-y-visible'>
						<div className='col-4'>
							<MediaInfoEditComponent 
								mediaInfo={data?.commonProperties.preview != null ? {
										type: data.commonProperties.preview.type,
										objectId: data.commonProperties.preview.objectId,
										data: null,
										// url: GetUrl(data?.commonProperties.preview.objectId),
										url: data?.commonProperties.preview.url,
										isNew: (data?.commonProperties.preview.url != null && data?.commonProperties.preview.url != ''),
									} as MediaInfoEditModel : null}
								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) =>
									data == null ? Promise.reject(dataLoadingError) : SetAnimeTitlePreview({
										animeTitleId: data.id,
										animeSeasonId: null,
										animeEpisodeId: null,
										newType: mediaInfo?.type ?? MediaInfoType.Image,
										newUrl: newUrl,
										newFile: newFile,
									} as CreateMediaInfoModel, client)}
								
								isDeleting={isDeleting.find(q => q == 'preview') != null}
								// setDeleting={(mediaInfo, value) => setDeleting('preview', value)}
								setDeleting={(_, value) => setDeleting('preview', value)}
								
								deleteMediaInfo={(mediaInfo) =>
									data == null ? Promise.reject(dataLoadingError) : ClearAnimeTitlePreview({
										animeTitleId: data.id,
										animeSeasonId: null,
										animeEpisodeId: null,
										objectId: mediaInfo.objectId,
									} as DeleteMediaInfoModel, client)}
								dataLoadingError={dataLoadingError}
								forceRefresh={fetchData}
								/>
		
							<div className='card p-0 mt-2'>
								{/* <div className='card-header'>
									<h3 className='card-heading'>Жанры</h3>
								</div> */}
								<div className='card-body p-0'>
									{/* {data.commonProperties.genres.length > 0 &&
										<GenreListView items={data.commonProperties.genres} />
									}
									{data.commonProperties.genres.length == 0 &&
										<span>— — // — —</span>
									} */}
									<div className='table-responsive'>
										{/* <table className="table m-0 table-bordered"> */}
										<table className="table m-0">
											{/* <thead>
												<tr>
													<th scope="col">#</th>
													<th scope="col">First</th>
													<th scope="col">Last</th>
													<th scope="col">Handle</th>
												</tr>
											</thead> */}
											<tbody>
												<tr>
													{/* <th className='text-nowrap'>Дата анонса</th>
													<td className='w-100 text-center'>{data.commonProperties.announcementDate?.toString() ?? '—//—'}</td> */}
													<th>Дата анонса</th>
													<td className='text-end'>
														<DateEditComponent
															placeholder={'Дата анонса'}
															required={true}
															isEditing={isEditing.find(q => q == 'announcementDate') != null}
															enabled={true}
															date={GetDate(data?.commonProperties.announcementDate)}
															editDate={(value: Date | null) => 
																data == null ? Promise.reject(dataLoadingError) : SetAnimeTitleAnnouncementDate({
																	animeTitleId: data.id,
																	animeSeasonId: null,
																	animeEpisodeId: null,
																	value: value
																} as EditDateModel, client)}
															setEditing={(value: boolean) => setEditing('announcementDate', value)}
															dataLoadingError={dataLoadingError}
															forceRefresh={fetchData}
															/>
														{/* {props.animeTitle.commonProperties.announcementDate?.toString() ?? '—//—'} */}
													</td>
												</tr>
												<tr>
													{/* <th className='text-nowrap'>Предполагаемая дата выхода</th>
													<td className='w-100 text-center'>{data.commonProperties.estimatedReleaseDate?.toString() ?? '—//—'}</td> */}
													<th>Предполагаемая дата выхода</th>
													<td className='text-end'>
														<DateEditComponent
															placeholder={'Предполагаемая дата выхода'}
															required={true}
															isEditing={isEditing.find(q => q == 'estimatedReleaseDate') != null}
															enabled={true}
															
															date={data?.commonProperties.estimatedReleaseDate != null ? new Date(data.commonProperties.estimatedReleaseDate) : null}
															editDate={(value: Date | null) =>
																data == null ? Promise.reject(dataLoadingError) : SetAnimeTitleEstimatedReleaseDate({
																	animeTitleId: data.id,
																	animeSeasonId: null,
																	animeEpisodeId: null,
																	value: value
																} as EditDateModel, client)}
															setEditing={(value: boolean) => setEditing('estimatedReleaseDate', value)}
															dataLoadingError={dataLoadingError}
															forceRefresh={fetchData}
															/>
														{/* {props.animeTitle.commonProperties.estimatedReleaseDate?.toString() ?? '—//—'} */}
													</td>
												</tr>
												<tr>
													{/* <th className='text-nowrap'>Предполагаемая дата выхода</th>
													<td className='w-100 text-center'>{data.commonProperties.estimatedReleaseDate?.toString() ?? '—//—'}</td> */}
													<th>Дата выхода</th>
													<td className='text-end w-100'>
														<DateEditComponent
															placeholder={'Дата выхода'}
															required={true}
															isEditing={isEditing.find(q => q == 'releaseDate') != null}
															enabled={true}
															date={data?.commonProperties.releaseDate != null ? new Date(data.commonProperties.releaseDate) : null}
															editDate={(value: Date | null) =>
																data == null ? Promise.reject(dataLoadingError) : SetAnimeTitleReleaseDate({
																	animeTitleId: data.id,
																	animeSeasonId: null,
																	animeEpisodeId: null,
																	value: value
																} as EditDateModel, client)}
															setEditing={(value: boolean) => setEditing('releaseDate', value)}
															dataLoadingError={dataLoadingError}
															forceRefresh={fetchData}
															/>
														{/* {props.animeTitle.commonProperties.estimatedReleaseDate?.toString() ?? '—//—'} */}
													</td>
												</tr>
											</tbody>
										</table>
									</div>
								</div>
							</div>
		
						</div>
						<div className='col p-0 pe-2'>
							<NamesEditComponent 
								names={data?.commonProperties.names ?? []}
								createName={(name) =>
									data == null ? Promise.reject(dataLoadingError) : CreateAnimeTitleName({
										animeTitleId: data.id,
										animeSeasonId: null,
										animeEpisodeId: null,
										languageId:name.language.id,
										value: name.value,
										type: name.type
									} as CreateNameModel, client)}

								editName={(name, newValue, newLanguage) =>
									data == null ? Promise.reject(dataLoadingError) : EditAnimeTitleName({
										animeTitleId: data.id,
										animeSeasonId: null,
										animeEpisodeId: null,
										
										languageId: name.language.id,
										value: name.value,
										type: name.type,
		
										newLanguageId: newLanguage?.id,
										newValue: newValue,
									} as EditNameModel, client)}

								deleteName={(name) =>
									data == null ? Promise.reject(dataLoadingError) : DeleteAnimeTitleName({
										animeTitleId: data.id,
										animeSeasonId: null,
										animeEpisodeId: null,
										
										languageId: name.language.id,
										value: name.value,
										type: name.type,
									} as DeleteNameModel, client)}
								dataLoadingError={dataLoadingError}
								forceRefresh={fetchData}
								/>
							{/* <DescriptionViewComponent descriptions={props.animeTitle.commonProperties.descriptions} userLanguageId={props.userLanguageId} /> */}
							<DescriptionsEditComponent 
								descriptions={data?.commonProperties.descriptions ?? []}
								createDescription={(description) =>
									data == null ? Promise.reject(dataLoadingError) : CreateAnimeTitleDescription({
										animeTitleId: data.id,
										animeSeasonId: null,
										animeEpisodeId: null,
										languageId:description.language.id,
										value: description.value,
										isOriginal: description.isOriginal
									} as CreateDescriptionModel, client)}

								editDescription={(description, newValue, newLanguageId) =>
									data == null ? Promise.reject(dataLoadingError) : EditAnimeTitleDescription({
										animeTitleId: data.id,
										animeSeasonId: null,
										animeEpisodeId: null,
										
										languageId: description.language.id,
										value: description.value,
										isOriginal: description.isOriginal,
		
										newLanguageId: newLanguageId,
										newValue: newValue,
									} as EditDescriptionModel, client)}

								deleteDescription={(description) =>
									data == null ? Promise.reject(dataLoadingError) : DeleteAnimeTitleDescription({
										animeTitleId: data.id,
										animeSeasonId: null,
										animeEpisodeId: null,
										
										languageId: description.language.id,
										value: description.value,
										isOriginal: description.isOriginal,
									} as DeleteDescriptionModel, client)}
								dataLoadingError={dataLoadingError}
								forceRefresh={fetchData}
								/>

							<div className='card p-0'>
								<div className='card-header'>
									<h3 className='card-heading'>Жанры</h3>
								</div>
								<div className='card-body'>
								<GenreProportionEditComponent
									genresProportions={data?.commonProperties.genres ?? []}
									createGenreProportionPercentage={(genreProportionItem) =>
										data == null ? Promise.reject(dataLoadingError) : CreateAnimeTitleGenre({
											animeTitleId: data.id,
											animeSeasonId: null,
											animeEpisodeId: null,
											genreId:genreProportionItem.genre.id,
											proportion: genreProportionItem.proportion,
										} as CreateGenreProportionModel, client)}
									editGenreProportionPercentage={(genreProportionItem, proportionPercentage) =>
										data == null ? Promise.reject(dataLoadingError) : EditAnimeTitleGenre({
											animeTitleId: data.id,
											animeSeasonId: null,
											animeEpisodeId: null,
											genreId:genreProportionItem.genre.id,
											proportion: proportionPercentage
										} as EditGenreProportionModel, client)}
									deleteGenreProportionPercentage={(genreProportionItem) =>
										data == null ? Promise.reject(dataLoadingError) : DeleteAnimeTitleGenre({
											animeTitleId: data.id,
											animeSeasonId: null,
											animeEpisodeId: null,
											genreId:genreProportionItem.genre.id,
											// proportion: genreProportionItem.proportion,
										} as DeleteGenreProportionModel, client)}
									dataLoadingError={dataLoadingError}
									forceRefresh={fetchData}
									/>
								</div>
							</div>
							
		
						</div>
					</div>

					{(data != null && user != null) &&
						<div className='mt-2'>
							<AnimeItemsEditComponent user={user} titleId={data?.id} items={data.items} forceRefresh={fetchData}  />
						</div>
						
					}
				</>
			}
		</>
  	)
}