import {useEffect, useState } from "react";
import {
    CreateNameModel,
    CreateDescriptionModel,
    CreateMediaInfoModel,
    CreateGenreProportionModel,
    NameItem,
    Description, GenreProportion, AnimeSeasonCreateModel, SeasonDetail, CommonProperties, MediaInfo, MediaInfoType,
    Language, NameType,
    // EditStudioModel, EditCountryModel
} from "../../../../api/models/Types.tsx";
import { libraryClient } from "../../../../api/axios.tsx";
import useUser from "../../../../api/hooks/useUser.tsx";
import {QueryClient, useQuery, useQueryClient } from "@tanstack/react-query";
import {
    currentUser as currentUserQueryKey,
    languages as languageQueryKey,
    genres as genresQueryKey
} from "../../../../common/QueryKeys.tsx";
import {useNavigate, useParams } from "react-router-dom";
import AnimeLibraryBreadcrumbsComponent, { ItemAction } from "../../../../components/AnimeLibraryBreadcrumbsComponent.tsx";
import {GetLanguageList} from "../../../../api/LanguageApi.tsx";

import {GetGenreList} from "../../../../api/GenreApi.tsx";
import { MediaInfoEditModel } from "../../../../api/models/MediaInfoTypes.tsx";
import {AddSeason, GetAnimeTitle} from "../../../../api/AnimeTitleApi.tsx";
import EditPreviewImageComponent from "../../../../components/library/EditPreviewImageComponent.tsx";
import DateEditComponent from "../../../../components/admin/library/animeItems/DateEditComponent.tsx";
import {getDate} from "../../../../common/Helper.tsx";
import TextEditComponent from "../../../../components/admin/library/animeItems/TextEditComponent.tsx";
import NamesEditComponent from "../../../../components/library/NamesEditComponent.tsx";
import DescriptionsEditComponent from "../../../../components/library/DescriptionsEditComponent.tsx";
import GenresEditComponent from "../../../../components/library/GenresEditComponent.tsx";
import { Card } from "primereact/card";
import { Divider } from "primereact/divider";

export default function SeasonCreate() {
    const client = libraryClient;
    //useAxiosWithAuth(libraryClient);
    const { getUser } = useUser();
    const queryClient = useQueryClient();
    const navigate = useNavigate();
    const { data: user } = useQuery({queryKey: [currentUserQueryKey], queryFn: () => getUser(),
        refetchInterval: 30000}, queryClient);

    const { data: languages } = useQuery({queryKey: [languageQueryKey], queryFn: () => GetLanguageList(),
        refetchInterval: 30000}, queryClient);
    const { data: genres } = useQuery({queryKey: [genresQueryKey], queryFn: () => GetGenreList(),
        refetchInterval: 30000}, queryClient);
    
    const { titleId } = useParams();
    // const { data: animeSeason, isLoading, error } = useQuery({queryKey: [queryKey],
    //     queryFn: () => GetAnimeSeasonDetail(titleId ?? '', id ?? '', client)}, queryClient);
    
    const [ titleNames, setTitleNames ] = useState<Array<NameItem> | null>(null);


    const [ waitingForAction, setWaitingForAction ] = useState<boolean>(false);
    
    const [ dateDialogOpen, setDateDialogOpen ] = useState<string | null>(null);
    const [ dialogDate, setDialogDate ] = useState<Date | null>(null);

    const [ textDialogOpen, setTextDialogOpen ] = useState<string | null>(null);
    const [ dialogText, setDialogText ] = useState<string | null>(null);

    const [ order, setOrder ] = useState<number>(0);
    const [ number, setNumber ] = useState<number>(0);
    const [ variant, setVariant ] = useState<number | null>(null);
    const [ names, setNames ] = useState<Array<NameItem>>([]);
    const [ preview, setPreview ] = useState<MediaInfoEditModel | null>(null);
    const [ descriptions, setDescriptions ] = useState<Array<Description>>([]);
    const [ genreProportions, setGenreProportions ] = useState<Array<GenreProportion>>([]);
    // const [ relatedContent, setRelatedContent ] = useState<Array<MediaInfo>>([]);
    const [ announcementDate, setAnnouncementDate ] = useState<string | null>(null);
    const [ expectedReleaseDate, setExpectedReleaseDate ] = useState<string | null>(null);

    const [ director, setDirector ] = useState<string | null>(null);
    const [ country, setCountry ] = useState<string | null>(null);
    const [ studio, setStudio ] = useState<string | null>(null);
    
    const [isSaving, setIsSaving] = useState<boolean>(false);
    const [savingError, setSavingError] = useState<string | null>(null);

    // if (isLoading){
    //     return (
    //         <>Загрузка...</>
    //     );
    // }

    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 (genreProportions.find(q => q.genre.id == genreProportionItem.genre.id && q.proportion == genreProportionItem.proportion)){
            return 'Genre already exists';
        }
        else {
            const obj = genreProportions;
            obj.push(genreProportionItem);
            setGenreProportions(obj);
            return '';
        }
    };
    const EditGenre = (genreProportionItem: GenreProportion, proportionPercentage: number | null) => {
        const obj = genreProportions;
        const genreProportion = obj.find(q => q.genre == genreProportionItem.genre && q.proportion == genreProportionItem.proportion);
        if (genreProportion != null){
            if (proportionPercentage != null) genreProportion.proportion = proportionPercentage;
            setGenreProportions(obj);
        }
    };
    const DeleteGenre = (genreProportionItem: GenreProportion) => {
        const obj = genreProportions;
        setGenreProportions(obj.filter(q => !(q.genre == genreProportionItem.genre && q.proportion == genreProportionItem.proportion)));
    };


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

    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: genreProportions.map(q => {
                return {
                    genreId: q.genre.id,
                    proportion: q.proportion,
                } as CreateGenreProportionModel
            }),
            announcementDate: announcementDate,
            estimatedReleaseDate: expectedReleaseDate
        } 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 ]);

    useEffect(() =>{
        if (titleId == null || titleId == ''){
            setSeasonDetail(null);
        }
        else{
            const detail = {
                id: '',
                deleted: false,

                titleId: titleId,
                titleNames: titleNames,

                completed: false,
                commonProperties: {
                    names: names,
                    preview: preview == null ? null : {
                        newType: preview.type,
                        // newUrl: preview.objectId,
                        newUrl: preview.url,
                        newFile: preview.data
                    } as CreateMediaInfoModel,
                    descriptions: descriptions,
                    genres: genreProportions,
                    // relatedContent: relatedContent;
                    relatedContent: [],
                    // announcementDate?: string | Date | null;
                    announcementDate: announcementDate,
                    expectedReleaseDate: expectedReleaseDate,
                    // releaseDate?: Date | null;
                } as CommonProperties,
                order: order,
                number: number,

                rating: null,
                myRating: null,

                viewsCount: null,
                myViewsCount: null,
                lastViewPercentage: 0,

                episodes: [],

                director: director,
                country: country,
                studio: studio,

                firstEpisodeReleaseDate: null,
                lastEpisodeReleaseDate: null
            } as unknown as SeasonDetail;
            setSeasonDetail(detail);
        }
    }, [ titleId ]);

    return (
        <div className='grid pt-3'>
            <div className='col-12'>
                <AnimeLibraryBreadcrumbsComponent action={ItemAction.create}
                  title={{ id: titleId ?? '', name: titleNames?.find(q => q.type === NameType.Original)?.value ?? '' }} />
            </div>
            <div className='col'>

                <Card
                    // header={}
                    pt={{
                        // header: () => ({
                        //     className: 'p-2 border-bottom-1 border-200'
                        // }),
                        body: () => ({
                            className: 'p-2 pt-3'
                        }),
                        content: () => ({
                            className: 'grid p-0'
                        })
                    }}
                >
                    <>
                        <div className="col-12 sm:col-6 lg:col-2">
                            {/*{animeSeason.commonProperties.preview?.url && (*/}
                            {/*    <img src={animeSeason.commonProperties.preview.url} className="w-full border-round"*/}
                            {/*         alt={(originalName ? `[${originalName.value}] ` : '') +  'preview'} />*/}
                            {/*)}*/}

                            <EditPreviewImageComponent
                                mediaInfo={preview == null ? null
                                    : {
                                        // // type: mediaInfo?.type ?? MediaInfoType.Image,
                                        // type: preview.type,
                                        // url: preview.url,
                                        // data: preview.data,
                                        // objectId: null,
                                        // // isNew: false,
                                        type: preview.type,
                                        // contentType: string,
                                        objectId: '',
                                        url: preview.url ?? preview.data,
                                    } as MediaInfo
                                }
                                dataLoadingError={null}
                                // inputTypeFilter={InputType.Url}
                                editMediaInfo={(mediaInfo, newUrl, newFile) => {
                                    setPreview({
                                        // type: mediaInfo?.type ?? MediaInfoType.Image,
                                        type: MediaInfoType.Image,
                                        url: newUrl,
                                        data: newFile,
                                        objectId: null,
                                        // isNew: false,
                                    } as MediaInfoEditModel);
                                    return Promise.resolve('');  
                                }}
                                deleteMediaInfo={(mediaInfo) => {
                                    setPreview(null);
                                    return Promise.resolve('');
                                }}
                                forceRefresh={() => {}}
                            />

                            <Card className='mt-4 mb-2 shadow-none'
                                  pt={{
                                      body: () => ({
                                          className: 'p-0'
                                      }),
                                      content: () => ({
                                          className: 'py-0 flex flex-column gap-3'
                                      })
                                  }}
                            >
                                {DateEditComponent('Анонс', 'дату анонса', getDate(announcementDate),
                                    dateDialogOpen === 'announcementDate', (show) => {
                                        setDialogDate(show ? getDate(announcementDate) : null);
                                        setDateDialogOpen(show ? 'announcementDate' : null);
                                    },
                                    dialogDate, (date) => setDialogDate(date),
                                    waitingForAction,
                                    () => {
                                        setWaitingForAction(true);
                                        setAnnouncementDate(dialogDate?.toISOString() ?? null);
                                        setDateDialogOpen(null);
                                        setWaitingForAction(false);
                                    }
                                )}

                                {DateEditComponent('Ожидаемая дата выхода', 'ожидаемую дату выхода', getDate(expectedReleaseDate),
                                    dateDialogOpen === 'expectedReleaseDate', (show) => {
                                        setDialogDate(show ? getDate(expectedReleaseDate) : null);
                                        setDateDialogOpen(show ? 'expectedReleaseDate' : null);
                                    },
                                    dialogDate, (date) => setDialogDate(date),
                                    waitingForAction,
                                    () => {
                                        setWaitingForAction(true);
                                        setExpectedReleaseDate(dialogDate?.toISOString() ?? null);
                                        setDateDialogOpen(null);
                                        setWaitingForAction(false);
                                    }
                                )}

                                {/*
                                {DateEditComponent('Дата выхода', 'дату выхода', getDate(releaseDate),
                                    dateDialogOpen === 'releaseDate', (show) => {
                                        setDialogDate(show ? getDate(releaseDate) : null);
                                        setDateDialogOpen(show ? 'releaseDate' : null);
                                    },
                                    dialogDate, (date) => setDialogDate(date),
                                    waitingForAction,
                                    () => {
                                        setWaitingForAction(true);
                                        setReleaseDate(dialogDate?.toISOString() ?? null);
                                        setDateDialogOpen(null);
                                        setWaitingForAction(false);
                                    }
                                )}
                                */}

                                <Divider type="solid" className="my-0" />

                                {TextEditComponent('Режиссёр', 'режиссёра', director,
                                    textDialogOpen === 'director', (show) => {
                                        setDialogText(show ? director : null);
                                        setTextDialogOpen(show ? 'director' : null);
                                    },
                                    dialogText, (text) => setDialogText(text),
                                    waitingForAction,
                                    () => {
                                        setWaitingForAction(true);
                                        setDirector(dialogText);
                                        setTextDialogOpen(null);
                                        setWaitingForAction(false);
                                    }
                                )}

                                {TextEditComponent('Студия', 'студию', studio,
                                    textDialogOpen === 'studio', (show) => {
                                        setDialogText(show ? studio : null);
                                        setTextDialogOpen(show ? 'studio' : null);
                                    },
                                    dialogText, (text) => setDialogText(text),
                                    waitingForAction,
                                    () => {
                                        setWaitingForAction(true);
                                        setStudio(dialogText);
                                        setTextDialogOpen(null);
                                        setWaitingForAction(false);
                                    }
                                )}

                                {TextEditComponent('Страна', 'страну', country,
                                    textDialogOpen === 'country', (show) => {
                                        setDialogText(show ? country : null);
                                        setTextDialogOpen(show ? 'country' : null);
                                    },
                                    dialogText, (text) => setDialogText(text),
                                    waitingForAction,
                                    () => {
                                        setWaitingForAction(true);
                                        setCountry(dialogText);
                                        setTextDialogOpen(null);
                                        setWaitingForAction(false);
                                    }
                                )}
                            </Card>
                        </div>
                        <div className="col-12 sm:col-6 lg:col-10 flex flex-column gap-2">

                            <NamesEditComponent languages={languages ?? []} names={names}
                                onAdd={(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);
                                }}
                                onEdit={(name, newValue, newLanguage) => {
                                    EditName({
                                        language: name.language,
                                        value: name.value,
                                        type: name.type
                                    } as NameItem, newValue, newLanguage);
                                    return Promise.resolve('');
                                }}
                                onDelete={(name) => {
                                    DeleteName({
                                        language: name.language,
                                        value: name.value,
                                        type: name.type
                                    } as NameItem);
                                    return Promise.resolve('');
                                }}
                            />

                            <DescriptionsEditComponent languages={languages ?? []} descriptions={descriptions}
                               onAdd={(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);
                               }}
                               onEdit={(description, newValue, newLanguage) => {
                                   EditDescription({
                                       language: description.language,
                                       value: description.value,
                                       isOriginal: description.isOriginal
                                   } as Description, newValue, newLanguage);
                                   return Promise.resolve('');
                               }}
                               onDelete={(description) => {
                                   DeleteDescription({
                                       language: description.language,
                                       value: description.value,
                                       isOriginal: description.isOriginal
                                   } as Description);
                                   return Promise.resolve('');
                               }}
                            />


                            <div className='d-flex '>
                                <GenresEditComponent genres={genres ?? []} genreProportions={genreProportions}
                                     onAdd={(genreProportionItem) => {
                                         const error = AddGenre(genreProportionItem);
                                         return error.length == 0 ? Promise.resolve('') : Promise.reject({message: error} as Error);
                                     }}
                                     onEdit={(genreProportionItem, proportionPercentage) => {
                                         EditGenre(genreProportionItem, proportionPercentage);
                                         return Promise.resolve('');
                                     }}
                                     onDelete={(genreProportionItem) => {
                                         DeleteGenre(genreProportionItem);
                                         return Promise.resolve('');
                                     }}
                                />
                            </div>
                        </div>
                    </>
                </Card>
            </div>
        </div>
    );

    /*
    return (
        <>
            <SeasonEditComponent user={user} action={ItemAction.create}
                 animeTitleId={titleId} animeTitleNames={titleNames} animeSeason={animeSeason}
                 languages={languages ?? []} genres={genreProportions ?? []}
                 setAnimeSeasonPreview={(model: CreateMediaInfoModel) => SetAnimeSeasonPreview(model)}
                 clearAnimeSeasonPreview={(model: DeleteMediaInfoModel) => ClearAnimeSeasonPreview(model)}

                 createAnimeSeasonName={(model: CreateNameModel) => CreateAnimeSeasonName(model)}
                 editAnimeSeasonName={(model: EditNameModel) => EditAnimeSeasonName(model)}
                 deleteAnimeSeasonName={(model: DeleteNameModel) => DeleteAnimeSeasonName(model)}

                 createAnimeSeasonDescription={(model: CreateDescriptionModel) => CreateAnimeSeasonDescription(model)}
                 editAnimeSeasonDescription={(model: EditDescriptionModel) => EditAnimeSeasonDescription(model)}
                 deleteAnimeSeasonDescription={(model: DeleteDescriptionModel) => DeleteAnimeSeasonDescription(model)}

                 createAnimeSeasonGenre={(model: CreateGenreProportionModel)=> CreateAnimeSeasonGenre(model)}
                 editAnimeSeasonGenre={(model: EditGenreProportionModel) => EditAnimeSeasonGenre(model)}
                 deleteAnimeSeasonGenre={(model: DeleteGenreProportionModel) => DeleteAnimeSeasonGenre(model)}

                 setAnimeSeasonAnnouncementDate={(model: EditDateModel) => SetAnimeSeasonAnnouncementDate(model)}
                 setAnimeSeasonExpectedReleaseDate={(model: EditDateModel) => SetAnimeSeasonExpectedReleaseDate(model)}
                 setAnimeSeasonReleaseDate={(model: EditDateModel) => SetAnimeSeasonReleaseDate(model)}

                 setAnimeSeasonDirector={(model: EditDirectorModel) => SetAnimeSeasonDirector(model)}
                 setAnimeSeasonStudio={(model: EditStudioModel) => SetAnimeSeasonStudio(model)}
                 setAnimeSeasonCountry={(model: EditCountryModel) => SetAnimeSeasonCountry(model)}
                 invalidateItem={() => {}}
            />
        </>
    );
    */
};