import { useEffect, useState } from "react";
import { Card } from "primereact/card";
import { Button } from "primereact/button";
import {
    AnimeItemShort,
    EpisodeShort,
    NameItem,
    NameType,
    SeasonShort,
    CreateNameModel,
    EditNameModel,
    DeleteNameModel,
    CreateDescriptionModel,
    EditDescriptionModel,
    DeleteDescriptionModel,
    MediaInfoType, CreateMediaInfoModel, DeleteMediaInfoModel,
    CreateGenreProportionModel,
    EditGenreProportionModel,
    DeleteGenreProportionModel,
    EditDateModel,
    EditDirectorModel,
    // 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 { useParams } from "react-router-dom";
import {
    GetAnimeTitleDetail,
    CreateAnimeTitleName,
    EditAnimeTitleName,
    DeleteAnimeTitleName,
    CreateAnimeTitleDescription,
    EditAnimeTitleDescription,
    DeleteAnimeTitleDescription,
    SetAnimeTitlePreview,
    ClearAnimeTitlePreview,
    CreateAnimeTitleGenre,
    EditAnimeTitleGenre,
    DeleteAnimeTitleGenre, SetAnimeTitleAnnouncementDate,
    SetAnimeTitleExpectedReleaseDate,
    SetAnimeTitleReleaseDate, SetAnimeTitleDirector,
    SetAnimeTitleStudio, SetAnimeTitleCountry
} from "../../../../api/AnimeTitleApi.tsx";
import {dateToString, getDate} from "../../../../common/Helper.tsx";
import React from "react";
import { Divider } from "primereact/divider";
import AnimeLibraryBreadcrumbsComponent, {
    ItemAction
} from "../../../../components/AnimeLibraryBreadcrumbsComponent.tsx";
import EditPreviewImageComponent from "../../../../components/library/EditPreviewImageComponent.tsx";
import NamesEditComponent from "../../../../components/library/NamesEditComponent.tsx";
import {GetLanguageList} from "../../../../api/LanguageApi.tsx";

import DescriptionsEditComponent from "../../../../components/library/DescriptionsEditComponent.tsx";
import GenresEditComponent from "../../../../components/library/GenresEditComponent.tsx";
import {GetGenreList} from "../../../../api/GenreApi.tsx";
import { Calendar } from "primereact/calendar";
import { InputText } from "primereact/inputtext";
import EpisodeEditShortComponent from "../Episode/EpisodeEditShortComponent.tsx";
import SeasonEditShortComponent from "../Season/SeasonEditShortComponent.tsx";
import { Dialog } from "primereact/dialog";

const queryKey = 'anime_title_detail';
export default function SeasonEdit() {
    const client = libraryClient;
    //useAxiosWithAuth(libraryClient);
    const { getUser } = useUser();
    const queryClient = useQueryClient();
    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 { id } = useParams();
    // const { data: animeTitle, isLoading, isError } = useQuery({queryKey: [queryKey],
    const { data: animeTitle, isLoading, error } = useQuery({queryKey: [queryKey],
        queryFn: () => GetAnimeTitleDetail(id ?? '', client)}, queryClient);

    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 [ isRateEditing, setIsRateEditing ] = useState<bool>(false);
    
    const [ originalName, setOriginalName ] = useState<NameItem | null>(null);
    

    useEffect(() => {        
        if (animeTitle == null) {
            setOriginalName(null);
        }
        else {
            setOriginalName(animeTitle.commonProperties.names.find(q => q.type === NameType.Original) ?? null);
        }
    }, [animeTitle, user]); //user
    
    if (animeTitle == null){
        return (<>НЕТУТИ НИЧАГО</>);
    }
    
    if (isLoading){
        return (
            <>Загрузка...</>
        );
    }

    return (
        <div className='grid pt-3'>
            <div className='col-12'>
                <AnimeLibraryBreadcrumbsComponent action={ItemAction.view} title={{ id: animeTitle.id, name: originalName?.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">
                            {/*{animeTitle.commonProperties.preview?.url && (*/}
                            {/*    <img src={animeTitle.commonProperties.preview.url} className="w-full border-round"*/}
                            {/*         alt={(originalName ? `[${originalName.value}] ` : '') +  'preview'} />*/}
                            {/*)}*/}

                            <EditPreviewImageComponent
                                mediaInfo={animeTitle?.commonProperties.preview}
                                // mediaInfo={null}
                                dataLoadingError={null}
                                // inputTypeFilter={InputType.Url}
                                editMediaInfo={(mediaInfo, newUrl, newFile) =>
                                    animeTitle == null ? Promise.reject(error) : SetAnimeTitlePreview({
                                        animeTitleId: animeTitle.id,
                                        animeSeasonId: null,
                                        animeEpisodeId: null,
                                        newType: mediaInfo?.type ?? MediaInfoType.Image,
                                        newUrl: newUrl,
                                        newFile: newFile,
                                    } as CreateMediaInfoModel, client)}
                                // editMediaInfo={(mediaInfo: MediaInfo | null, newUrl: string | null, newFile: File | null) => {
                                //     console.log('edit');
                                //     return Promise.resolve('');
                                // }}
                                deleteMediaInfo={(mediaInfo) =>
                                    animeTitle == null ? Promise.reject(error) : ClearAnimeTitlePreview({
                                        animeTitleId: animeTitle.id,
                                        animeSeasonId: null,
                                        animeEpisodeId: null,
                                        objectId: mediaInfo.objectId,
                                    } as DeleteMediaInfoModel, client)}
                                // deleteMediaInfo={(mediaInfo: MediaInfo | null) => {
                                //     console.log('delete');
                                //     return Promise.resolve('');
                                // }}
                                // forceRefresh={() => console.log('Обновление данных')}
                                forceRefresh={() => InvalidateTitle(queryClient)}
                            />

                            <Card className='mt-4 mb-2 shadow-none'
                                  pt={{
                                      body: () => ({
                                          className: 'p-0'
                                      }),
                                      content: () => ({
                                          className: 'py-0 flex flex-column gap-3'
                                      })
                                  }}
                            >
                                {ShowDate('Анонс', 'дату анонса', getDate(animeTitle.commonProperties.announcementDate),
                                    dateDialogOpen === 'announcementDate', (show) => {
                                        setDialogDate(show ? getDate(animeTitle.commonProperties.announcementDate) : null);
                                        setDateDialogOpen(show ? 'announcementDate' : null);
                                    },
                                    dialogDate, (date) => setDialogDate(date),
                                    waitingForAction,
                                    () => {
                                        if (animeTitle == null) {
                                            return;
                                        }
                                        setWaitingForAction(true);
                                        SetAnimeTitleAnnouncementDate({
                                            animeTitleId: animeTitle.id,
                                            animeSeasonId: null,
                                            animeEpisodeId: null,
                                            value: dialogDate
                                        } as EditDateModel, client)
                                            .then(() => {
                                                setDateDialogOpen(null);
                                                InvalidateTitle(queryClient)
                                            })
                                            .finally(() => setWaitingForAction(false));
                                    }
                                )}

                                {ShowDate('Ожидаемая дата выхода', 'ожидаемую дату выхода', getDate(animeTitle.commonProperties.expectedReleaseDate),
                                    dateDialogOpen === 'expectedReleaseDate', (show) => {
                                        setDialogDate(show ? getDate(animeTitle.commonProperties.expectedReleaseDate) : null);
                                        setDateDialogOpen(show ? 'expectedReleaseDate' : null);
                                    },
                                    dialogDate, (date) => setDialogDate(date),
                                    waitingForAction,
                                    () => {
                                        if (animeTitle == null) {
                                            return;
                                        }
                                        setWaitingForAction(true);
                                        SetAnimeTitleExpectedReleaseDate({
                                            animeTitleId: animeTitle.id,
                                            animeSeasonId: null,
                                            animeEpisodeId: null,
                                            value: dialogDate
                                        } as EditDateModel, client)
                                            .then(() => {
                                                setDateDialogOpen(null);
                                                InvalidateTitle(queryClient)
                                            })
                                            .finally(() => setWaitingForAction(false));
                                    }
                                )}

                                {ShowDate('Дата выхода', 'дату выхода', getDate(animeTitle.commonProperties.releaseDate),
                                    dateDialogOpen === 'releaseDate', (show) => {
                                        setDialogDate(show ? getDate(animeTitle.commonProperties.releaseDate) : null);
                                        setDateDialogOpen(show ? 'releaseDate' : null);
                                    },
                                    dialogDate, (date) => setDialogDate(date),
                                    waitingForAction,
                                    () => {
                                        if (animeTitle == null) {
                                            return;
                                        }
                                        setWaitingForAction(true);
                                        SetAnimeTitleReleaseDate({
                                            animeTitleId: animeTitle.id,
                                            animeSeasonId: null,
                                            animeEpisodeId: null,
                                            value: dialogDate
                                        } as EditDateModel, client)
                                            .then(() => {
                                                setDateDialogOpen(null);
                                                InvalidateTitle(queryClient)
                                            })
                                            .finally(() => setWaitingForAction(false));
                                    }
                                )}

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

                                {ShowText('Режиссёр', 'режиссёра', animeTitle.director,
                                    textDialogOpen === 'director', (show) => {
                                        setDialogText(show ? animeTitle.director : null);
                                        setTextDialogOpen(show ? 'director' : null);
                                    },
                                    dialogText, (text) => setDialogText(text),
                                    waitingForAction,
                                    () => {
                                        if (animeTitle == null) {
                                            return;
                                        }
                                        setWaitingForAction(true);
                                        SetAnimeTitleDirector({
                                            animeTitleId: animeTitle.id,
                                            animeSeasonId: null,
                                            animeEpisodeId: null,
                                            value: dialogText
                                        } as EditDirectorModel, client)
                                            .then(() => {
                                                setTextDialogOpen(null);
                                                InvalidateTitle(queryClient)
                                            })
                                            .finally(() => setWaitingForAction(false));
                                    }
                                )}

                                {ShowText('Студия', 'студию', animeTitle.studio,
                                    textDialogOpen === 'studio', (show) => {
                                        setDialogText(show ? animeTitle.studio : null);
                                        setTextDialogOpen(show ? 'studio' : null);
                                    },
                                    dialogText, (text) => setDialogText(text),
                                    waitingForAction,
                                    () => {
                                        if (animeTitle == null) {
                                            return;
                                        }
                                        setWaitingForAction(true);
                                        SetAnimeTitleStudio({
                                            animeTitleId: animeTitle.id,
                                            animeSeasonId: null,
                                            animeEpisodeId: null,
                                            value: dialogText
                                        } as EditDirectorModel, client)
                                            .then(() => {
                                                setTextDialogOpen(null);
                                                InvalidateTitle(queryClient)
                                            })
                                            .finally(() => setWaitingForAction(false));
                                    }
                                )}

                                {ShowText('Страна', 'страну', animeTitle.country,
                                    textDialogOpen === 'country', (show) => {
                                        setDialogText(show ? animeTitle.country : null);
                                        setTextDialogOpen(show ? 'country' : null);
                                    },
                                    dialogText, (text) => setDialogText(text),
                                    waitingForAction,
                                    () => {
                                        if (animeTitle == null) {
                                            return;
                                        }
                                        setWaitingForAction(true);
                                        SetAnimeTitleCountry({
                                            animeTitleId: animeTitle.id,
                                            animeSeasonId: null,
                                            animeEpisodeId: null,
                                            value: dialogText
                                        } as EditDirectorModel, client)
                                            .then(() => {
                                                setTextDialogOpen(null);
                                                InvalidateTitle(queryClient)
                                            })
                                            .finally(() => setWaitingForAction(false));
                                    }
                                )}
                            </Card>
                        </div>
                        <div className="col-12 sm:col-6 lg:col-10 flex flex-column gap-2">

                            <NamesEditComponent languages={languages ?? []} names={animeTitle.commonProperties.names}
                                                onAdd={(name) =>
                                                    animeTitle == null ? Promise.reject(error)
                                                        : new Promise ((resolve, reject) => {
                                                            CreateAnimeTitleName({
                                                                animeTitleId: animeTitle.id,
                                                                animeSeasonId: null,
                                                                animeEpisodeId: null,
                                                                languageId:name.language.id,
                                                                value: name.value,
                                                                type: name.type
                                                            } as CreateNameModel, client)
                                                                .then((response) => {
                                                                    InvalidateTitle(queryClient);
                                                                    resolve(response);
                                                                })
                                                                .catch(e => reject(e));
                                                        })}
                                                onEdit={(name, newValue, newLanguage) =>
                                                    animeTitle == null ? Promise.reject(error)
                                                        : new Promise ((resolve, reject) => {
                                                            EditAnimeTitleName({
                                                                animeTitleId: animeTitle.id,
                                                                animeSeasonId: null,
                                                                animeEpisodeId: null,

                                                                languageId: name.language.id,
                                                                value: name.value,
                                                                type: name.type,

                                                                newLanguageId: newLanguage?.id,
                                                                newValue: newValue,
                                                            } as EditNameModel, client)
                                                                .then((response) => {
                                                                    InvalidateTitle(queryClient);
                                                                    resolve(response);
                                                                })
                                                                .catch(e => reject(e));
                                                        })}
                                                onDelete={(name) =>
                                                    animeTitle == null ? Promise.reject(error)
                                                        : new Promise ((resolve, reject) => {
                                                            DeleteAnimeTitleName({
                                                                animeTitleId: animeTitle.id,
                                                                animeSeasonId: null,
                                                                animeEpisodeId: null,

                                                                languageId: name.language.id,
                                                                value: name.value,
                                                                type: name.type,
                                                            } as DeleteNameModel, client)
                                                                .then((response) => {
                                                                    InvalidateTitle(queryClient);
                                                                    resolve(response);
                                                                })
                                                                .catch(e => reject(e));
                                                        })}
                            />

                            <DescriptionsEditComponent languages={languages ?? []} descriptions={animeTitle.commonProperties.descriptions}
                                                       onAdd={(name) =>
                                                           animeTitle == null ? Promise.reject(error)
                                                               : new Promise ((resolve, reject) => {
                                                                   CreateAnimeTitleDescription({
                                                                       animeTitleId: animeTitle.id,
                                                                       animeSeasonId: null,
                                                                       animeEpisodeId: null,
                                                                       languageId:name.language.id,
                                                                       value: name.value,
                                                                       isOriginal: name.isOriginal
                                                                   } as CreateDescriptionModel, client)
                                                                       .then((response) => {
                                                                           InvalidateTitle(queryClient);
                                                                           resolve(response);
                                                                       })
                                                                       .catch(e => reject(e));
                                                               })}
                                                       onEdit={(name, newValue, newLanguage) =>
                                                           animeTitle == null ? Promise.reject(error)
                                                               : new Promise ((resolve, reject) => {
                                                                   EditAnimeTitleDescription({
                                                                       animeTitleId: animeTitle.id,
                                                                       animeSeasonId: null,
                                                                       animeEpisodeId: null,

                                                                       languageId: name.language.id,
                                                                       value: name.value,
                                                                       isOriginal: name.isOriginal,

                                                                       newLanguageId: newLanguage?.id,
                                                                       newValue: newValue,
                                                                   } as EditDescriptionModel, client)
                                                                       .then((response) => {
                                                                           InvalidateTitle(queryClient);
                                                                           resolve(response);
                                                                       })
                                                                       .catch(e => reject(e));
                                                               })}
                                                       onDelete={(name) =>
                                                           animeTitle == null ? Promise.reject(error)
                                                               : new Promise ((resolve, reject) => {
                                                                   DeleteAnimeTitleDescription({
                                                                       animeTitleId: animeTitle.id,
                                                                       animeSeasonId: null,
                                                                       animeEpisodeId: null,

                                                                       languageId: name.language.id,
                                                                       value: name.value,
                                                                       isOriginal: name.isOriginal,
                                                                   } as DeleteDescriptionModel, client)
                                                                       .then((response) => {
                                                                           InvalidateTitle(queryClient);
                                                                           resolve(response);
                                                                       })
                                                                       .catch(e => reject(e));
                                                               })}
                            />


                            <div className='d-flex '>
                                <GenresEditComponent genres={genres ?? []} genreProportions={animeTitle.commonProperties.genres}
                                                     onAdd={(genreProportionItem) =>
                                                         animeTitle == null ? Promise.reject(error)
                                                             : new Promise ((resolve, reject) => {
                                                                 CreateAnimeTitleGenre({
                                                                     animeTitleId: animeTitle.id,
                                                                     animeSeasonId: null,
                                                                     animeEpisodeId: null,
                                                                     genreId:genreProportionItem.genre.id,
                                                                     proportion: genreProportionItem.proportion,
                                                                 } as CreateGenreProportionModel, client)
                                                                     .then((response) => {
                                                                         InvalidateTitle(queryClient);
                                                                         resolve(response);
                                                                     })
                                                                     .catch(e => reject(e));
                                                             })}
                                                     onEdit={(genreProportionItem, proportionPercentage) =>
                                                         animeTitle == null ? Promise.reject(error)
                                                             : new Promise ((resolve, reject) => {
                                                                 EditAnimeTitleGenre({
                                                                     animeTitleId: animeTitle.id,
                                                                     animeSeasonId: null,
                                                                     animeEpisodeId: null,
                                                                     genreId:genreProportionItem.genre.id,
                                                                     proportion: proportionPercentage
                                                                 } as EditGenreProportionModel, client)
                                                                     .then((response) => {
                                                                         InvalidateTitle(queryClient);
                                                                         resolve(response);
                                                                     })
                                                                     .catch(e => reject(e));
                                                             })}
                                                     onDelete={(genreProportionItem) =>
                                                         animeTitle == null ? Promise.reject(error)
                                                             : new Promise ((resolve, reject) => {
                                                                 DeleteAnimeTitleGenre({
                                                                     animeTitleId: animeTitle.id,
                                                                     animeSeasonId: null,
                                                                     animeEpisodeId: null,
                                                                     genreId:genreProportionItem.genre.id,
                                                                     // proportion: genreProportionItem.proportion,
                                                                 } as DeleteGenreProportionModel, client)
                                                                     .then((response) => {
                                                                         InvalidateTitle(queryClient);
                                                                         resolve(response);
                                                                     })
                                                                     .catch(e => reject(e));
                                                             })}
                                />
                            </div>
                        </div>

                        <div className="col-12">
                            <Card className='border-2 border-100'
                                  header={() => (
                                      <h3 className='m-0'>Содержимое</h3>
                                  )}
                                  pt={{
                                      header: () => ({
                                          className: 'border-bottom-2 border-noround-bottom border-100 p-2 pb-1'
                                      }),
                                      body: () => ({
                                          className: 'p-0'
                                      }),
                                      content: () => ({
                                          className: 'flex flex-column gap-2 p-2'
                                      })
                                  }}
                            >
                                {
                                    React.Children.toArray(
                                        animeTitle.items.sort((a, b) => a.order - b.order).map((item: AnimeItemShort) => {
                                            const isSeason = item.$type.toLowerCase() == 'seasonshort';
                                            if (isSeason){
                                                const season = item as SeasonShort;
                                                return (
                                                    <SeasonEditShortComponent
                                                        key={item.id}
                                                        titleId={animeTitle.id}
                                                        seasonId={item.id}
                                                        seasonNumber={item.number ?? 0}
                                                        names={item.names}
                                                        primaryLanguageId={user?.languageId}
                                                        episodeCount={season.episodesCount}
                                                        announcementDate={item.announcementDate ?? null}
                                                        expectedReleaseDate={item.expectedReleaseDate ?? null}
                                                        releaseDate={item.releaseDate ?? null}
                                                        isCompleted={item.completed}
                                                        userRating={item.rating}
                                                        myRating={item.myRating}
                                                        previewImage={item.preview?.url ?? ''}
                                                        totalDuration={season.contentDurationTicks}
                                                    />
                                                );
                                            }
                                            else{
                                                const episode = item as EpisodeShort;
                                                return (
                                                    <EpisodeEditShortComponent
                                                        key={item.id}
                                                        titleId={animeTitle.id}
                                                        episodeId={item.id}
                                                        episodeNumber={item.number ?? 0}
                                                        episodeVariant={episode.variant}
                                                        previewImage={item.preview?.url ?? ''}
                                                        names={item.names}
                                                        primaryLanguageId={user?.languageId}
                                                        announcementDate={item.announcementDate ?? null}
                                                        expectedReleaseDate={item.expectedReleaseDate ?? null}
                                                        releaseDate={item.releaseDate ?? null}
                                                        isCompleted={item.completed}
                                                        duration={episode.durationTicks ?? 0}
                                                        userRating={item.rating}
                                                        myRating={item.myRating}
                                                    />
                                                );
                                            }
                                        })
                                    )
                                }
                            </Card>
                        </div>
                    </>
                </Card>
            </div>
        </div>
    );
};

function ShowDateEditDialog(dateName: string, isDialogVisible: boolean, onHide: () => void,
        value: Date | null, onChange: (date: Date | null) => void,
        saving: boolean, onSave: () => void){
    return (
        <Dialog header={`Редактировать ${dateName}`}
            headerClassName='p-3 pt-2 pb-1'
            contentClassName='p-3 pt-0'
            style={{ width: '50vw' }}
            visible={isDialogVisible} onHide={onHide}>
            <div className='flex flex-column gap-3 mt-3'>
                <Calendar value={value} inline showButtonBar showWeek
                  inputClassName='p-inputtext-sm'
                  onChange={(e) => onChange(e.value ?? null)} />
                
                <span className={`text-${value == null ? '200' : 'blue-500'}`}>{(dateToString(value, false, true))}</span>
            </div>
            <Button label='Сохранить' className='w-full mt-4' loading={saving} onClick={onSave} />
        </Dialog>
    );
}

function  ShowDate(title: string, dialogDateName: string, value: Date | null,
       isDialogVisible: boolean, setDialogVisible: (value: boolean) => void,
       editingValue: Date | null, onChange: (date: Date | null) => void,
       saving: boolean, onSave: () => void){
    return (
        <div>
            <div className='uppercase text-xs text-400 mb-1'>
                <b>{title}</b>
            </div>            
            <div className='text-sm flex flex-row justify-content-between align-items-center w-full'>
                <span className={`text-${value == null ? '200' : 'blue-500'}`}>{(dateToString(value, false, true))}</span>
                <Button icon="pi pi-pencil" severity='secondary' text className='p-0' size='small'
                        disabled={isDialogVisible || saving}
                        onClick={() => setDialogVisible(true)} />
            </div>

            {ShowDateEditDialog(dialogDateName, isDialogVisible, () => setDialogVisible(false),
                editingValue, onChange, saving, onSave)}
        </div>
    );
}


function ShowTextEditDialog(textName: string, isDialogVisible: boolean, onHide: () => void,
        value: string | null, onChange: (date: string | null) => void,
        saving: boolean, onSave: () => void){
    return (
        <Dialog header={`Редактировать ${textName}`}
            headerClassName='p-3 pt-2 pb-1'
            contentClassName='p-3 pt-0'
            // style={{ width: '50vw' }}
            visible={isDialogVisible} onHide={onHide}>
            <div className='flex flex-column gap-3 mt-3'>
                <div className="p-inputgroup flex-1">
                    <InputText type="text" className="p-inputtext-sm" value={value ?? ''} autoComplete='off'
                           onChange={(e) => onChange(e.target.value ?? null)} />
                    <Button icon="pi pi-times" severity='danger' size='small'
                            onClick={() => onChange(null)} />
                </div>
            </div>
            <Button label='Сохранить' className='w-full mt-4' loading={saving} onClick={onSave} />
        </Dialog>
    );
}

function  ShowText(title: string, dialogTextName: string, value: string | null,
       isDialogVisible: boolean, setDialogVisible: (value: boolean) => void,
       editingValue: string | null, onChange: (date: string | null) => void,
       saving: boolean, onSave: () => void){
    const isValueNullOrEmpty = value === null || value.length === 0;
    return (
        <div>
            <div className='uppercase text-xs text-400 mb-1'>
                <b>{title}</b>
            </div>            
            <div className='text-sm flex flex-row justify-content-between align-items-center w-full'>
                <span className={`text-${isValueNullOrEmpty ? '200' : 'blue-500'}`}>{(isValueNullOrEmpty ? '--' : value)}</span>
                <Button icon="pi pi-pencil" severity='secondary' text className='p-0' size='small'
                        disabled={isDialogVisible || saving}
                        onClick={() => setDialogVisible(true)} />
            </div>

            {ShowTextEditDialog(dialogTextName, isDialogVisible, () => setDialogVisible(false),
                editingValue, onChange, saving, onSave)}
        </div>
    );
}

function InvalidateTitle(queryClient: QueryClient) { queryClient.invalidateQueries({ queryKey: [queryKey] }); }