import {useNavigate, useParams} from "react-router-dom";
import {useEffect, useState} from "react";
import {
    AnimeSeasonCreateModel,
    CreateDescriptionModel, CreateGenreProportionModel,
    CreateMediaInfoModel,
    CreateNameModel,
    Description,
    GenreProportion,
    Language, MediaInfoType,
    NameItem
} from "../../../api/models/Types.tsx";
import {MediaInfoEditModel} from "../../../components/common/edit/MediaInfoTypes.tsx";
import {AddSeason, GetAnimeTitle} from "../../../api/AnimeTitleApi.tsx";
import MediaInfoEditComponent from "../../../components/common/edit/MediaInfoEditComponent.tsx";
import DateEditComponent from "../../../components/common/edit/DateEditComponent.tsx";
import {GetDate} from "../../../common/Helper.tsx";
import NamesEditComponent from "../../../components/MediaContent/edit/Names/NamesEditComponent.tsx";
import DescriptionsEditComponent
    from "../../../components/MediaContent/edit/Descriptions/DescriptionsEditComponent.tsx";
import GenreProportionEditComponent
    from "../../../components/MediaContent/edit/Genres/GenreProportionEditComponent.tsx";
import {TfiSave} from "react-icons/tfi";
import useUser from "../../../api/hooks/useUser.tsx";
import {useQuery} from "react-query";
import {userQueryKey} from "../../../components/common/UserShortComponent.tsx";
import {NameBreadcrumbsComponent} from "../../../components/common/view/NameBreadcrumbsComponent.tsx";

export default function AnimeSeasonCreate(){
    const client = null;
    const navigate = useNavigate();
    const { getUser } = useUser();
    const { data: user } = useQuery(userQueryKey, getUser);
    
    const { titleId } = useParams();
    const [ titleNames, setTitleNames ] = useState<Array<NameItem> | null>(null);

    const [ names, setNames ] = useState<Array<NameItem>>([]);
    const [ preview, setPreview ] = useState<MediaInfoEditModel | null>(null);
    const [ descriptions, setDescriptions ] = useState<Array<Description>>([]);
    const [ genres, setGenres ] = useState<Array<GenreProportion>>([]);
    // const [ relatedContent, setRelatedContent ] = useState<Array<MediaInfo>>([]);
    const [ announcementDate, setAnnouncementDate ] = useState<string | null>(null);
    const [ estimatedReleaseDate, setEstimatedReleaseDate ] = useState<string | null>(null);

    // const [duration, setDuration] = useState<number | null>(null);

    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 AddDescription = (description: Description) => {
        if (descriptions.find(q => q.language.id == description.language.id && q.isOriginal == description.isOriginal && q.value == description.value)){
            return 'Description already exists';
        }
        else {
            const obj = descriptions
            obj.push(description);
            setDescriptions(obj);
            return '';
        }
    };
    const EditDescription = (descriptionItem: Description, newValue: string | null, newLanguage: Language | null) => {
        const obj = descriptions;
        const description = obj.find(q => q.language == descriptionItem.language && q.isOriginal == descriptionItem.isOriginal && q.value == descriptionItem.value);
        if (description != null){
            if (newValue != null) description.value = newValue;
            if (newLanguage != null) description.language = newLanguage;
            setDescriptions(obj);
        }
    };
    const DeleteDescription = (description: Description) => {
        const obj = descriptions;
        setDescriptions(obj.filter(q => !(q.language == description.language && q.isOriginal == description.isOriginal && q.value == description.value)));
    };

    const AddGenre = (genreProportionItem: GenreProportion) => {
        if (genres.find(q => q.genre.id == genreProportionItem.genre.id && q.proportion == genreProportionItem.proportion)){
            return 'Genre already exists';
        }
        else {
            const obj = genres;
            obj.push(genreProportionItem);
            setGenres(obj);
            return '';
        }
    };
    const EditGenre = (genreProportionItem: GenreProportion, proportionPercentage: number | null) => {
        const obj = genres;
        const genreProportion = obj.find(q => q.genre == genreProportionItem.genre && q.proportion == genreProportionItem.proportion);
        if (genreProportion != null){
            if (proportionPercentage != null) genreProportion.proportion = proportionPercentage;
            setGenres(obj);
        }
    };
    const DeleteGenre = (genreProportionItem: GenreProportion) => {
        const obj = genres;
        setGenres(obj.filter(q => !(q.genre == genreProportionItem.genre && q.proportion == genreProportionItem.proportion)));
    };

    const SetAnnouncementDate = (date: Date | null) => setAnnouncementDate(date == null ? null : date.toISOString());
    const SetEstimatedReleaseDate = (date: Date | null) => setEstimatedReleaseDate(date == null ? null : date.toISOString());

    // const SetPreview = (preview: MediaInfoEditModel | null) => setPreview(preview);

    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){
            // console.log('a');
            // console.log('alreadyDeleting');
            // console.log(alreadyDeleting ? 'TR' : 'FA');
            if (!alreadyDeleting){
                setIsDeletingValue(isDeleting.concat([elementName]))
            }
        }
        else{
            if (alreadyDeleting){
                setIsDeletingValue(isDeleting.filter(q => q != elementName))
            }
        }
    };

    const Save = () =>{
        const model = {
            animeTitleId: 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
        } as AnimeSeasonCreateModel;

        AddSeason(model)
            .then(() => navigate(`/admin/library/anime/${titleId}/edit`))
            // .then(() => navigate(`/admin/library/anime/${titleId}/season/${seasonId}/edit`))
            .catch((err) => { console.error(err);});
    };

    useEffect(() =>{
        if (titleId == null || titleId == ''){
            setTitleNames(null);
        }
        else{
            GetAnimeTitle(titleId ?? '', client)
                .then((data) =>{
                    if (data == null){
                        setTitleNames(null);
                    }
                    else{
                        // const name = GetTitleNames(names, user?.languageId)?.titleElement;
                        setTitleNames(data.commonProperties.names);
                    }
                    // setDataLoadingError(null);
                })
                .catch((error) => {
                    setTitleNames(null);
                    console.log(error);
                    // setDataLoadingError(error);
                });
        }
    }, [ titleId ]);
    
    return (
        <>
            <NameBreadcrumbsComponent titleId={titleId} titleNames={titleNames} returnToEdit={true} 
                                      userLanguageId={user?.languageId}  />
            
            номер сезона
            вариант сезона

            <div className='row overflow-x-hidden overflow-y-visible'>
                <div className='col-4'>
                    <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 className='card p-0 mt-2'>
                        <div className='card-body p-0'>
                            <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(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}
                                                />
                                                {/* {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={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}
                                                />
                                                {/* {props.animeTitle.commonProperties.estimatedReleaseDate?.toString() ?? '—//—'} */}
                                            </td>
                                        </tr>
                                        {/*<tr>*/}
                                        {/*    <th>Продолжительность</th>*/}
                                        {/*    <td className='text-end'>*/}
                                        {/*        <TimespanComponent*/}
                                        {/*            title="Продолжительность"*/}
                                        {/*            value={TimespanFromTicks(addEpisodeDuration)}*/}
                                        {/*            onChange={(ts) => setAddEpisodeDuration(TimespanToTicks(ts))}*/}
                                        {/*        />*/}
                                        {/*    </td>*/}
                                        {/*</tr>*/}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                </div>
                <div className='col p-0 pe-2'>
                    <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}
                    />
                    {/* <DescriptionViewComponent descriptions={props.animeTitle.commonProperties.descriptions} userLanguageId={props.userLanguageId} /> */}
                    <DescriptionsEditComponent
                        descriptions={descriptions}
                        createDescription={(description) => {
                            const error = AddDescription({
                                language: description.language,
                                value: description.value,
                                isOriginal: description.isOriginal
                            } as Description);
                            return error.length == 0 ? Promise.resolve('') : Promise.reject({message: error} as Error);
                        }}

                        editDescription={(description, newValue, newLanguage) => {
                            EditDescription({
                                language: description.language,
                                value: description.value,
                                isOriginal: description.isOriginal
                            } as Description, newValue, newLanguage);
                            return Promise.resolve('');
                        }}

                        deleteDescription={(description) => {
                            DeleteDescription({
                                language: description.language,
                                value: description.value,
                                isOriginal: description.isOriginal
                            } as Description);
                            return Promise.resolve('');
                        }}
                        dataLoadingError={null}
                        forceRefresh={Plug}
                    />

                    <div className='card p-0'>
                        <div className='card-header'>
                            <h3 className='card-heading'>Жанры</h3>
                        </div>
                        <div className='card-body'>
                            <GenreProportionEditComponent
                                genresProportions={genres}
                                createGenreProportionPercentage={(genreProportionItem) => {
                                    const error = AddGenre(genreProportionItem);
                                    return error.length == 0 ? Promise.resolve('') : Promise.reject({message: error} as Error);
                                }}
                                editGenreProportionPercentage={(genreProportionItem, proportionPercentage) => {
                                    EditGenre(genreProportionItem, proportionPercentage);
                                    return Promise.resolve('');
                                }}
                                deleteGenreProportionPercentage={(genreProportionItem) => {
                                    DeleteGenre(genreProportionItem);
                                    return Promise.resolve('');
                                }}
                                dataLoadingError={null}
                                forceRefresh={Plug}
                            />
                        </div>
                    </div>


                </div>
            </div>
            {/* <div className='bg-success'>
				<div>Содержимое</div>
				<div>сезоны</div>
				<div>эпизоды</div>
			</div> */}
            <hr/>
            <div className='row g-2 justify-content-end'>
                <div className="col">
                    <div className='btn btn-primary w-100' onClick={Save}>Save <TfiSave/></div>
                </div>
            </div>
        </>
    );
}

function Plug() {

}