import {useState} from "react";
import {ModalWindowFullscreenMode, ModalWindowSize} from "../../../common/ModalWindow/ModalWindowComponentBase";
import {DateToString, GetDate} from "../../../../common/Helper";
import TwoButtonModalWindowComponent from "../../../common/ModalWindow/TwoButtonModalWindowComponent.tsx";
import {AnimeEpisodeType} from "../../../../api/models/Types.tsx";
import TimespanComponent, {TimespanFromTicks, TimespanToTicks} from "../../../common/TimespanComponent.tsx";

export enum ItemType {
    Season,
    Episode
}

export type AddAnimeItemModel = {
    itemType: ItemType,
    episodeType: AnimeEpisodeType | null,
    releaseDate: Date | null,
    durationTicks: number | null,
}

export interface IAddAnimeSeasonOrEpisodeModalWindowComponentProps {
    
    size?: ModalWindowSize | undefined | null,
    fullscreen_mode?: ModalWindowFullscreenMode | undefined | null,
    show?: boolean | undefined | null,
    onExit?: () => void,
    onItemAdd?: (model: AddAnimeItemModel) => Promise<void>,
}
export default function AddAnimeSeasonOrEpisodeModalWindowComponent(props: IAddAnimeSeasonOrEpisodeModalWindowComponentProps){
    const id = Math.random().toString(36).substring(2, 9);

    const [addItemType, setAddItemType] = useState<ItemType>(ItemType.Season);

    const [addAnimeEpisodeType, setAddAnimeEpisodeType] = useState<AnimeEpisodeType>(AnimeEpisodeType.Regular);

    const [addEpisodeReleaseDate, setAddEpisodeReleaseDate] = useState<string | null>(null);
    const [addEpisodeDuration, setAddEpisodeDuration] = useState<number | null>(null);

    const [addItemError, setAddItemError] = useState<string | null>();
    
    const clearData = () => {
        setAddItemType(ItemType.Season);
        setAddAnimeEpisodeType(AnimeEpisodeType.Regular);
        setAddEpisodeReleaseDate(null);
        setAddEpisodeDuration(null);
    };
    
    return (
        <TwoButtonModalWindowComponent title={`Добавление содержимого`}
                show={props.show} id={id}
                size={ModalWindowSize.Large}
                fullscreen_mode={ModalWindowFullscreenMode.BelowLarge}
                // vertically_centered={false}
                first_button_text={"Отмена"}
                first_button_classes={'btn-secondary'}
                on_first_button_clicked={() => props.onExit?.()}

                second_button_text={`Добавить ${addItemType == ItemType.Season ? 'сезон' : 'эпизод'}`}
                second_button_classes={'btn-primary'}
                on_second_button_clicked={() => {
                        props.onItemAdd?.({
                            itemType: addItemType,
                            episodeType: addItemType == ItemType.Episode ? addAnimeEpisodeType : null,
                            releaseDate: addEpisodeReleaseDate != null ? GetDate(addEpisodeReleaseDate) : null,
                            durationTicks: addEpisodeDuration,
                            } as AddAnimeItemModel)
                        .then(() => {
                            setAddItemError(null);
                            clearData();
                        })
                        .catch((err: Error | null | undefined) => setAddItemError(err?.message)); 
                    }
                }
                second_button_disabled={addItemType == ItemType.Episode && 
                    ((addEpisodeReleaseDate == null || addEpisodeReleaseDate == '') || addEpisodeDuration == null)
                    }
                
                onExit={() => {
                    clearData();
                    setAddItemError(null);
                    props.onExit?.();
                }}
        >
            <>
                <ul className="nav nav-tabs mb-2">
                    <li className="nav-item">
                        <div className={'nav-link' + (addItemType == ItemType.Season ? ' active' : '')} 
                            onClick={() => setAddItemType(ItemType.Season)}>
                            Сезон
                        </div>
                    </li>
                    <li className="nav-item">
                        <div className={'nav-link' + (addItemType == ItemType.Episode ? ' active' : '')}
                             onClick={() => setAddItemType(ItemType.Episode)}>
                            Эпизод
                        </div>
                    </li>
                </ul>

                {addItemType == ItemType.Episode &&
                    <>
                        <div className='input-group mb-2'>
                            <span className="input-group-text">Дата выхода</span>
                            <input className="form-control" type="date"
                                   required={true}
                                   aria-placeholder={'Дата выхода'}
                                   onChange={(event) => setAddEpisodeReleaseDate(() => {
                                       const date = GetDate(event.target.value);
                                       return date == null ? null : date.toISOString();
                                   })}
                                   value={DateToString(GetDate(addEpisodeReleaseDate))}
                            />
                        </div>
                        <TimespanComponent
                            title="Продолжительность"
                            value={TimespanFromTicks(addEpisodeDuration)}
                            onChange={(ts) => setAddEpisodeDuration(TimespanToTicks(ts))}
                        />
                        <div className='input-group mt-2'>
                            <span className="input-group-text">Тип эпизода</span>
                            <select className="form-select" aria-label="Язык названия"
                                    aria-placeholder={"Тип эпизода"}
                                    onChange={(event) => setAddAnimeEpisodeType((event.target.value as unknown as AnimeEpisodeType) ?? AnimeEpisodeType.Regular)}
                                // disabled={!props.isEditing}
                                    value={addAnimeEpisodeType}
                            >
                                <option value={AnimeEpisodeType.Regular}>Обычный (TV)</option>
                                <option value={AnimeEpisodeType.Ova}>OVA {/*Большой экран*/}</option>
                                <option value={AnimeEpisodeType.Ona}>ONA {/*Интернет*/}</option>
                            </select>
                        </div>
                    </>
                }

                {/*<ErrorField error={addItemError}>*/}
                {/*    <ErrorInput error={addItemError}>*/}
                {/*        <div className='input-group'>*/}
                {/*            /!*<ErrorInput error={addItemError}>*!/*/}
                {/*            /!*	<select className="form-select" aria-label="Язык названия"*!/*/}
                {/*            /!*			onChange={(event) => setAddItemType((event.target.value as unknown as ItemType) ?? ItemType.Season)}*!/*/}
                {/*            /!*		// disabled={!props.isEditing}*!/*/}
                {/*            /!*			value={addItemType}*!/*/}
                {/*            /!*	>*!/*/}
                {/*            /!*		<option value={ItemType.Season}>Сезон</option>*!/*/}
                {/*            /!*		<option value={ItemType.Episode}>Эпизод</option>*!/*/}
                {/*            /!*	</select>*!/*/}
                {/*            /!*</ErrorInput>*!/*/}
                {/*            <button type='button'*/}
                {/*                    className={'btn btn-' + (addItemError == null ? 'primary' : 'danger')}*/}
                {/*                    disabled={addAnimeItemModalWindowShow}*/}
                {/*                    onClick={() => setAddAnimeItemModalWindowShow(true)}>*/}
                {/*                <TfiPlus/>*/}
                {/*            </button>*/}
                {/*        </div>*/}
                {/*    </ErrorInput>*/}
                {/*</ErrorField>*/}

                {(addItemError != null && addItemError != '') &&
                    <div className='text-danger mt-2'>{addItemError}</div>
                }
            </>
        </TwoButtonModalWindowComponent>
    );
}