import React, {useState} from 'react'
import {
	AnimeEpisodeCreateModel,
	AnimeEpisodeDeleteModel,
	AnimeSeasonCreateModel,
	AnimeSeasonDeleteModel,
	Episode,
	Season
} from '../../../../../api/models/Types';
import {TfiPlus} from 'react-icons/tfi';
import {UserInfo} from '../../../../../api/models/AccountTypes';
import AnimeItemShortComponent from './AnimeItemShortComponent';
import {AddEpisode, AddSeason, DeleteEpisode, DeleteSeason} from '../../../../../api/AnimeTitleApi';
import {Link, useNavigate} from 'react-router-dom';
import TwoButtonModalWindowComponent from "../../../../common/ModalWindow/TwoButtonModalWindowComponent.tsx";
import {GetTitleNames} from "../../../../common/view/NameComponent.tsx";
import AddAnimeSeasonOrEpisodeModalWindowComponent, {
	AddAnimeItemModel,
	ItemType
} from "../AddAnimeSeasonOrEpisodeModalWindowComponent.tsx";
import {ModalWindowFullscreenMode, ModalWindowSize} from "../../../../common/ModalWindow/ModalWindowComponentBase.tsx";
import {FaArrowUpRightFromSquare} from "react-icons/fa6";

export interface IAnimeItemAddComponentProps{
	titleId: string,
	items: Array<Season | Episode>,
	user: UserInfo,
	forceRefresh?: () => void,
}



export default function AnimeItemsEditComponent(props : IAnimeItemAddComponentProps) {
	const navigate = useNavigate();

	const [animeItemSelected, setAnimeItemSelected] = useState<string | null>();
	const [createInEditorDropdownExpanded, setCreateInEditorDropdownExpanded] = useState<boolean>(false);
	const [addAnimeItemModalWindowShow, setAddAnimeItemModalWindowShow] = useState<boolean>(false);
	const [deleteItemError, setDeleteItemError] = useState<string | null>();
	
	// const addItem = () => new Promise<void>((resolve, reject) => {
	// 	const type = addItemType ?? ItemType.Season;
	// 	switch (+type) {
	// 		case ItemType.Season:
	// 			AddSeason({ animeTitleId: props.titleId, } as AnimeSeasonCreateModel)
	// 			.then(() => resolve())
	// 			.catch((err: Error | null | undefined) => reject(err ?? null));
	// 			break;
	// 		case ItemType.Episode:
	// 			AddEpisode({
	// 				animeTitleId: props.titleId,
	// 				type: addAnimeEpisodeType,
	// 				releaseDate: addEpisodeReleaseDate,
	// 				durationTicks: addEpisodeDuration ?? 0,
	// 			} as AnimeEpisodeCreateModel)
	// 			.then(() => resolve())
	// 			.catch((err: Error | null | undefined) => reject(err ?? null));
	// 			break;
	//	
	// 		default:
	// 			reject(new Error('Not implemented'));
	// 	}
	// });

	const deleteItem = (item: Season | Episode) => new Promise<void>((resolve, reject) => {
		const isSeason = item.$type.toLowerCase() == 'season';
		if (isSeason){
			DeleteSeason({ animeTitleId: props.titleId, animeSeasonId: item.id } as AnimeSeasonDeleteModel)
			.then(() => resolve())
			.catch((err: Error | null | undefined) => reject(err ?? null));
		}
		else{
			DeleteEpisode({ animeTitleId: props.titleId, animeEpisodeId: item.id } as AnimeEpisodeDeleteModel)
				.then(() => resolve())
				.catch((err: Error | null | undefined) => reject(err ?? null));
		}
	});

	return (
		<div className='card p-0 bg-body-secondary'>
			<div className='card-header p-0'>

				<div className='row m-0 py-2 justify-content-between'>
					<div className='col'><h3 className='card-title m-0'>Содержимое</h3></div>
					<div className='col-auto'>
						<div className='row justify-content-end'>
							<div className='col-auto'>
								<div className='input-group'>
									<div className="dropdown me-1">
										<button
											className={'btn btn-primary rounded-end-0 dropdown-toggle' + (createInEditorDropdownExpanded ? ' show rounded-bottom-0' : '')}
											type="button" data-bs-toggle="dropdown"
											aria-expanded={createInEditorDropdownExpanded}
											onClick={() => setCreateInEditorDropdownExpanded(!createInEditorDropdownExpanded)}
										>
											Создать в редакторе
										</button>
										<ul className={'dropdown-menu w-100' + (createInEditorDropdownExpanded ? ' show rounded-top-0' : '')}
										>
											<li>
												{/*<Link to='/' className='dropdown-item'>*/}
												<Link to={`/admin/library/anime/${props.titleId}/season/`}
													  className='dropdown-item-text link-light link-offset-2 link-body-emphasis link-underline-opacity-25 link-underline-opacity-75-hover'>
													<div className='row justify-content-between'>
														<div className='col-auto pe-0'>Добавить сезон</div>
														<div className='col-auto ps-0 text-info'><FaArrowUpRightFromSquare/></div>
													</div>
												</Link>
											</li>
											<li>
												{/*<Link to='/' className='dropdown-item'>*/}
												<Link to={`/admin/library/anime/${props.titleId}/episode/`}
													  className='dropdown-item-text link-light link-offset-2 link-body-emphasis link-underline-opacity-25 link-underline-opacity-75-hover'>
													<div className='row justify-content-between'>
														<div className='col-auto pe-0'>Добавить эпизод</div>
														<div className='col-auto ps-0 text-info'><FaArrowUpRightFromSquare/></div>
													</div>
												</Link>
											</li>
										</ul>
									</div>
									<button type='button'
											className={'btn btn-primary'}
											disabled={addAnimeItemModalWindowShow}
											onClick={() => setAddAnimeItemModalWindowShow(true)}>
										<TfiPlus/>
									</button>
								</div>

							</div>
						</div>
					</div>
				</div>

			</div>

			<div className='card-body'>
				{
					React.Children.toArray(
						props.items.sort((a, b) => a.order - b.order).map((item) =>
							<AnimeItemShortComponent user={props.user} animeItem={item}
													 goToDetailPage={() => navigate(`/library/anime/${props.titleId}/${(item.$type.toLowerCase() == 'season') ? 'season' : 'episode'}/${item.id}`)}
								// deleteItem={() => setAnimeItemSelected(item.id)}
													 deleteItem={() => {
														 setAnimeItemSelected(item.id);
														 console.log('d')
													 }}
													 goToEditPage={() => navigate(`/admin/library/anime/${props.titleId}/${(item.$type.toLowerCase() == 'season') ? 'season' : 'episode'}/${item.id}/edit`)}
							/>
						))
				}
			</div>

			{
				//Add item modal window
				<AddAnimeSeasonOrEpisodeModalWindowComponent show={addAnimeItemModalWindowShow}
					 	size={ModalWindowSize.Large}
					 	fullscreen_mode={ModalWindowFullscreenMode.BelowMedium}
					 	onExit={() => setAddAnimeItemModalWindowShow(false)}
						onItemAdd={(model : AddAnimeItemModel) => new Promise<void>((resolve, reject) => 
							{
								switch (model.itemType) {
									case ItemType.Episode:
										AddEpisode({
											animeTitleId: props.titleId,
											type: model.episodeType,
											releaseDate: model.releaseDate,
											durationTicks: model.durationTicks ?? 0,
										} as AnimeEpisodeCreateModel)
											.then(() => resolve())
											.catch((err: Error | null | undefined) => reject(err ?? null));
										break;
									case ItemType.Season:
										AddSeason({ animeTitleId: props.titleId, } as AnimeSeasonCreateModel)
											.then(() => resolve())
											.catch((err: Error | null | undefined) => reject(err ?? null));
										break;
									default:
										// reject(new Error('Not implemented'));
										break;
								}
							}).then(() => {
								// setAddEpisodeReleaseDate(null);
								setAddAnimeItemModalWindowShow(false)
								props.forceRefresh?.();
							})
							// .catch((err: Error | null | undefined) => SetAddItemError(err?.message))
						}								 
					/>
			}

			{
				DeleteItemModalWindow(props.items, animeItemSelected, deleteItemError ?? null,
					() => {
						setAnimeItemSelected(null);
						setDeleteItemError(null);
					},
					(item) => deleteItem(item)
						.then(() => {
							setDeleteItemError(null);
							// setAddEpisodeReleaseDate(null);
							setAnimeItemSelected(null);
							props.forceRefresh?.();
						})
						.catch((err: Error | null | undefined) => setDeleteItemError(err?.message ?? null)),
					props.user.languageId)
			}
			{
				//Edit button
				
			}

			
		</div>
	)
}

function DeleteItemModalWindow(items: Array<Season | Episode>, itemId: string | null | undefined, deleteItemError: string | null,
							   onCancelClicked: () => void,
							   onDeleteClicked: (item: Season | Episode) => void, languageId: string | null | undefined) {
	const item = GetSelectedItem(items, itemId);
	if (item == null) {
		return null;
	}
	const isSeason = item.$type.toLowerCase() == 'season';
	const name = `${isSeason ? 'Сезон' : 'Эпизод'} ${item.number}. ${item.commonProperties.names.length > 0 ? `[${GetTitleNames(item.commonProperties.names, languageId)?.titleElement}]` : ''}`;
	return (
		<TwoButtonModalWindowComponent title={`Удаление ${isSeason ? 'сезон' : 'эпизод'}а`}
			first_button_text={"Отмена"}
			first_button_classes={'btn-secondary'}
			on_first_button_clicked={onCancelClicked}

			second_button_text={"Удалить"}
			second_button_classes={'btn-danger'}
			on_second_button_clicked={() => { onDeleteClicked(item); }}
		   	onExit={onCancelClicked}
			show={true}>
			<>
				Удалить <span className={'text-primary'}>{name}</span>?
				{(deleteItemError != null && deleteItemError != '') &&
					<div className='text-danger mt-2'>{deleteItemError}</div>
				}
			</>
		</TwoButtonModalWindowComponent>
	);
}

function GetSelectedItem(items: Array<Season | Episode>, itemId: string | null | undefined) : Season | Episode | null {
	if (itemId == null || itemId == '') {
		return null;
	}
	return items.find(q => q.id == itemId) ?? null;
}