import {
    currentUser as currentUserQueryKey,
    languages as languagesQueryKey,
    sessionsQueryKey
} from "../../common/QueryKeys.tsx";
import {GetLanguageList} from "../../api/LanguageApi.tsx";
import {useMutation, useQuery, useQueryClient} from "@tanstack/react-query";
import AvatarComponent, {AvatarSize} from "../../components/account/AvatarComponent.tsx";
// import {GetDate} from "../../common/Helper.tsx";
import useUser from "../../api/hooks/useUser.tsx";
import {Language, MediaInfoType} from "../../api/models/Types.tsx";
import {FileUpload, FileUploadSelectEvent} from "primereact/fileupload";
import {ProgressBar} from "primereact/progressbar";
import {useEffect, useRef, useState} from "react";
import {MediaInfoEditModel} from "../../api/models/MediaInfoTypes.tsx";
import {Card} from "primereact/card";
import {Button} from "primereact/button";
import {Dialog} from "primereact/dialog";
import {FloatLabel} from "primereact/floatlabel";
import {InputText} from "primereact/inputtext";
import {
    BirthDateEditModel, DeleteSessionModel,
    LanguageEditModel,
    SessionModel,
    UserInformationEditModel,
    UserOnlineStatus
} from "../../api/models/AccountTypes.tsx";
import {Calendar} from "primereact/calendar";
import {AutoComplete, AutoCompleteChangeEvent, AutoCompleteCompleteEvent} from "primereact/autocomplete";
import {DataScroller} from 'primereact/datascroller';
import {DateToString, GetDate} from "../../common/Helper.tsx";
import {
    DeleteAllSessions,
    DeleteAvatar,
    DeleteSession,
    GetSessions,
    SetAvatar,
    SetBirthDate,
    SetLanguage,
    SetUserInformation
} from "../../api/UserApi.tsx";
import {Divider} from "primereact/divider";
import OnlineBadgeComponent from "../../components/account/OnlineBadgeComponent.tsx";
import useRedirectToLoginPage from "../../api/hooks/useRedirectToLoginPage.tsx";

const Account = () => {
    // const { data: languages, isError: languagesLoadingError} = useQuery({queryKey: [languagesQueryKey], queryFn: GetLanguageList});
    const queryClient = useQueryClient();
    const { data: languages } = useQuery({queryKey: [languagesQueryKey], queryFn: GetLanguageList}, queryClient);
    const { getUser, forceReloadUser } = useUser();
    // const { accessToken } = useAuth();
    const { data: currentUser } = useQuery({queryKey: [currentUserQueryKey], queryFn: () => getUser()}, queryClient);
    // const { data: sessions } = useQuery<Array<SessionModel>>({queryKey: [sessionsQueryKey], queryFn: () => getSessions()}, queryClient);
    const { data: sessions } = useQuery<Array<SessionModel> | undefined>({queryKey: [sessionsQueryKey], queryFn: () => GetSessions(currentUser?.accessToken)}, queryClient);
    const [preview, setPreview] = useState<MediaInfoModel | null>(null);

    const { toLoginPage } = useRedirectToLoginPage();
    
    //avatar
    const sizeMb = 1;
    const [totalSize, setTotalSize] = useState(0);
    const fileUploadRef = useRef<FileUpload | null>(null);
    
    const onTemplateSelect = async (e: FileUploadSelectEvent) => {
        let _totalSize;
        let file = e.files[0];
        
        if (file != null){
            _totalSize = file.size;
        }
        else{
            _totalSize = 0;
        }

        setTotalSize(_totalSize);
        const mi = currentUser?.avatar == null ? null : {
            // type: MediaInfoType.Image,
            type: currentUser.avatar.type,
            url: currentUser.avatar.url,
        } as MediaInfoEditModel;
        setPreview(await mediaInfoFromFile(file, mi));
    };
    
    //user personal data
    const [isUserInfoEditing, setIsUserInfoEditing] = useState<boolean>(false);
    const [currentUserFirstName, setCurrentUserFirstName] = useState<string | null>(null);
    const [currentUserLastName, setCurrentUserLastName] = useState<string | null>(null);
    const [currentUserPatronymic, setCurrentUserPatronymic] = useState<string | null>(null);

    const [isUserBirthDateEditing, setIsUserBirthDateEditing] = useState<boolean>(false);
    const [currentUserBirthDate, setCurrentUserBirthDate] = useState<Date | null>(null);

    const [isUserLanguageEditing, setIsUserLanguageEditing] = useState<boolean>(false);
    const [filteredLanguages, setFilteredLanguages] = useState<Array<Language>>([]);
    const [currentUserLanguage, setCurrentUserLanguage] = useState<Language | null>(null);

    const editUserPersonalDataMutation = useMutation({
        mutationFn: async ({firstName, lastName, patronymic}:
           { firstName: string | null, lastName: string | null, patronymic: string | null; }) => {
            if (currentUser?.accessToken == null){
                throw new Error("No access token")
            }
            await SetUserInformation(currentUser.accessToken, {
                firstName: firstName,
                patronymic: patronymic,
                lastName: lastName,
            } as UserInformationEditModel);
        },
        onSuccess: () => {
            setIsUserInfoEditing(false);
            forceReloadUser()
                .then(() => queryClient.invalidateQueries({ queryKey: [ currentUserQueryKey ] }));
            // setSelectedLanguage(null);
            // setEditingLanguageOriginalName(null);
        },
    });

    const editUserBirthDateMutation = useMutation({
        mutationFn: async (birthDate: string | null) => {
            if (currentUser?.accessToken == null){
                throw new Error("No access token")
            }
            await SetBirthDate(currentUser.accessToken, {
                birthDate: birthDate,
            } as BirthDateEditModel);
        },
        onSuccess: () => {
            setIsUserBirthDateEditing(false);
            forceReloadUser()
                .then(() => queryClient.invalidateQueries({ queryKey: [ currentUserQueryKey ] }));
            // setSelectedLanguage(null);
            // setEditingLanguageOriginalName(null);
        },
    });

    const editUserLanguageMutation = useMutation({
        mutationFn: async (languageId: string | null) => {
            if (currentUser?.accessToken == null){
                throw new Error("No access token")
            }
            await SetLanguage(currentUser.accessToken, { languageId: languageId } as LanguageEditModel);
        },
        onSuccess: () => {
            setIsUserLanguageEditing(false);
            forceReloadUser()
                .then(() => queryClient.invalidateQueries({ queryKey: [ currentUserQueryKey ] }));
            // setSelectedLanguage(null);
            // setEditingLanguageOriginalName(null);
        },
    });

    const editUserAvatarMutation = useMutation({
        mutationFn: async (file: File) => {
            if (currentUser?.accessToken == null){
                throw new Error("No access token")
            }
            await SetAvatar(currentUser.accessToken, file);
        },
        onSuccess: () => {
            setTotalSize(0);
            setPreview(null);
            fileUploadRef.current?.clear();
            forceReloadUser()
                .then(() => queryClient.invalidateQueries({ queryKey: [ currentUserQueryKey ] }));
        },
    });
    
    const [isUserAvatarDeleting, setIsUserAvatarDeleting] = useState<boolean>(false);
    const deleteUserAvatarMutation = useMutation({
        mutationFn: async () => {
            if (currentUser?.accessToken == null){
                throw new Error("No access token")
            }
            await DeleteAvatar(currentUser.accessToken);
        },
        onSuccess: () => {
            forceReloadUser()
                .then(() => {
                    setIsUserAvatarDeleting(false);
                    queryClient.invalidateQueries({ queryKey: [ currentUserQueryKey ] });
                });
        },
    });
    
    const deleteSessionMutation = useMutation({
        mutationFn: async (sessionId: string) => {
            if (currentUser?.accessToken == null){
                throw new Error("No access token")
            }
            await DeleteSession(currentUser?.accessToken, { sessionId:sessionId } as DeleteSessionModel);
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: [ sessionsQueryKey ] });
        },
    });
    
    const deleteAllSessionsMutation = useMutation({
        mutationFn: async () => {
            if (currentUser?.accessToken == null){
                throw new Error("No access token")
            }
            await DeleteAllSessions(currentUser.accessToken);
        },
        onSuccess: () => {
            forceReloadUser()
                .then(() => toLoginPage());
        },
    });
    

    useEffect(() => {
        setCurrentUserFirstName(currentUser?.firstName ?? null);
        setCurrentUserLastName(currentUser?.lastName ?? null);
        setCurrentUserPatronymic(currentUser?.patronymic ?? null);
        
        setCurrentUserBirthDate(GetDate(currentUser?.birthDate));
        setCurrentUserLanguage(currentUser?.languageId != null ? (languages?.find(l => l.id === currentUser?.languageId) ?? null) : null);
    }, [currentUser, isUserInfoEditing]);
    
    if (!currentUser){
        return ( <>no data</>  );
    }

    return (
        <div className="grid mt-2 flex align-items-stretch">
            <div className='col-12 sm:col h-auto'>
                <Card className='h-full'
                      footer={() =>{
                          return (
                              <FileUpload ref={fileUploadRef} name='avatar' accept='image/*' maxFileSize={sizeMb*Math.pow(2,20)}
                                          onSelect={onTemplateSelect}
                                          onClear={() => {
                                              setTotalSize(0);
                                              setPreview(null);
                                          }}
                                          customUpload
                                          // uploadHandler={(event) => editUserAvatarMutation.mutate(event.files[0])}
                                          uploadHandler={(event) => {
                                              console.log('upload event', event);
                                              editUserAvatarMutation.mutate(event.files[0]);
                                          }}
                                          className='mt-3'
                                          headerClassName='grid m-0 p-2'
                                          contentClassName='p-2 py-3'
                                          headerTemplate={(options) => {
                                              const { className, chooseButton, uploadButton, cancelButton } = options;
                                              const maxSize = sizeMb*Math.pow(2,20);
                                              const value = totalSize / maxSize;
                                              const formatedValue = fileUploadRef && fileUploadRef.current ? fileUploadRef.current.formatSize(totalSize) : '0 B';
                                              // console.log(fileUploadRef)

                                              return (
                                                  <>
                                                      <div className={className} style={{ backgroundColor: 'transparent', display: 'flex', alignItems: 'center' }}>
                                                          <div className="col-12 pt-0 pb-1 px-0 flex border border-bottom-1">
                                                              <div className='grid justify-content-between align-items-center w-full m-0' >
                                                                  <div className='col text-xl font-semibold text-400'>
                                                                      Изменить
                                                                  </div>
                                                                  <div className='col-auto'>
                                                                      <Button icon='pi pi-trash' outlined size='small' severity='danger'
                                                                          label='Удалить'
                                                                          onClick={() => setIsUserAvatarDeleting(true)} />
                                                                  </div>
                                                              </div>
                                                          </div>

                                                          <div className="col-auto">
                                                              {chooseButton}
                                                          </div>
                                                          <div className="col-auto">
                                                              {uploadButton}
                                                          </div>
                                                          <div className="col-auto">
                                                              {cancelButton}
                                                          </div>
                                                          <div className="col">
                                                              <div className="flex flex-column align-items-center gap-2 w-auto">
                                                                  <span>{formatedValue} / {fileUploadRef && fileUploadRef.current ? fileUploadRef.current.formatSize(maxSize) : `${maxSize / Math.pow(2,20)} MB`}</span>
                                                                  <ProgressBar value={Math.round((value * 100 + Number.EPSILON) * 100) / 100} className='w-full' style={{ height: '12px' }} showValue={false} ></ProgressBar>
                                                              </div>
                                                          </div>
                                                      </div>
                                                  </>
                                              );
                                          }}
                                          emptyTemplate={<p className="m-0 text-200">Перетащите сюда изображение для дальнейшей загрузки.</p>}
                                          chooseOptions={{ icon: 'pi pi-images', iconOnly: true, className: 'p-button-outlined p-button-sm' }}
                                          uploadOptions={{ icon: 'pi pi-cloud-upload', iconOnly: true, className: 'p-button-success p-button-outlined p-button-sm' }}
                                          cancelOptions={{ icon: 'pi pi-times', iconOnly: true, className: 'p-button-danger p-button-outlined p-button-sm' }}
                                          itemTemplate={(file: object) => {
                                              const f = file as File;
                                              return (<span>{f.name} | {f.size}</span>);
                                          }}
                              />
                          )
                      }}
                >
                    <div className="flex flex-row gap-2" style={{marginTop:'-1rem', marginBottom:'-2rem' }}>
                    {/*<div className="flex flex-row gap-2">*/}
                        {/*<div className="flex" style={{ maxHeight: '25rem', maxWidth: '25rem'}}>*/}
                        <div className="flex h-auto" style={{ maxHeight: '25rem', maxWidth: '25rem'}}>
                            {/*<AvatarComponent url={currentUser.avatar?.url} size={AvatarSize.extraLarge}/>*/}
                            <AvatarComponent url={preview?.data ?? currentUser.avatar?.url} size={AvatarSize.extraLarge}
                                 additionalClasses={preview?.data != null && currentUser.avatar?.url == null ? 'border border-2 border-round-lg border-yellow-600 border-dotted' : ''}
                            />
                        </div>
                        <div className="flex">
                            <AvatarComponent url={preview?.data ?? currentUser.avatar?.url} size={AvatarSize.medium}
                                 additionalClasses={preview?.data != null && currentUser.avatar?.url == null ? 'border border-1 border-round-md border-yellow-500 border-dashed' : ''}
                            />
                        </div>
                        <div className="flex">
                            <AvatarComponent url={preview?.data ?? currentUser.avatar?.url} size={AvatarSize.small}
                                 additionalClasses={preview?.data != null && currentUser.avatar?.url == null ? 'border border-1 border-round-md border-yellow-500 border-dashed' : ''}
                            />
                        </div>
                    </div>
                </Card>
            </div>
            <div className='col-12 sm:col-6 h-auto' >
                <Card className='h-full'
                    header={() => (
                        <div
                            className="surface-100 border-round-md border-noround-bottom text-4xl font-semibold text-500 align-content-center p-2"
                        >
                            Личные данные
                        </div>
                    )}
                >
                    
                    <div className='grid'>
                        <div className='col-2'>
                            
                        </div>
                    </div>
                    
                    <div className='p-card border border-1 surface-border border-dashed p-2'>
                        <div className='grid justify-content-between p-card-header'>
                            <div className='col text-xl font-semibold text-500 align-content-center'>
                                ФИО
                            </div>
                            <div className='col-auto align-content-center p-2 pt-2'>
                                <Button icon='pi pi-pencil' disabled={isUserInfoEditing} outlined size='small' onClick={() => setIsUserInfoEditing(true)} />
                            </div>
                        </div>
                        <div className='p-card-content py-0'>
                            <table className='text-left'>
                                <tbody>
                                    <tr>
                                        <th className='pr-2'>
                                            Фамилия
                                        </th>
                                        <td>
                                            <InputText type="text" value={currentUserLastName ?? ''}
                                                       onChange={(e) =>
                                                           setCurrentUserLastName(e.target.value ?? null)
                                                       }
                                                       disabled={!isUserInfoEditing} readOnly={!isUserInfoEditing}
                                                       className="p-inputtext-sm" placeholder="Введите фамилию" />
                                        </td>
                                    </tr>
                                    <tr>
                                        <th className='pr-2'>
                                            Имя
                                        </th>
                                        <td>
                                            <InputText type="text" value={currentUserFirstName ?? ''}
                                                       onChange={(e) =>
                                                           setCurrentUserFirstName(e.target.value ?? null)
                                                       }
                                                       disabled={!isUserInfoEditing} readOnly={!isUserInfoEditing} 
                                                       className="p-inputtext-sm" placeholder="Введите имя" />
                                        </td>
                                    </tr>
                                    <tr>
                                        <th className='pr-2'>
                                            Отчество
                                        </th>
                                        <td>
                                            <InputText type="text" value={currentUserPatronymic ?? ''}
                                                       onChange={(e) =>
                                                           setCurrentUserPatronymic(e.target.value ?? null)
                                                       }
                                                       disabled={!isUserInfoEditing} readOnly={!isUserInfoEditing}
                                                       className="p-inputtext-sm" placeholder="Введите отчество" />
                                        </td>
                                    </tr>
                                </tbody>
                            </table>

                            {isUserInfoEditing &&
                                <div className='flex justify-content-between pt-2'>
                                    <Button icon='pi pi-save' label='Сохранить' size='small' severity='success'
                                            onClick={() => editUserPersonalDataMutation.mutate({
                                                firstName: currentUserFirstName,
                                                lastName: currentUserLastName,
                                                patronymic: currentUserPatronymic,
                                            })}
                                    />
                                    <Button icon='pi pi-times' label='Отменить' size='small' severity='danger'
                                            onClick={() => {
                                                setIsUserInfoEditing(false);
                                                setCurrentUserFirstName(currentUser?.firstName ?? null);
                                                setCurrentUserLastName(currentUser?.lastName ?? null);
                                                setCurrentUserPatronymic(currentUser?.patronymic ?? null);
                                            }}
                                    />
                                </div>    
                            }
                        </div>
                    </div>
                    
                    <Divider />

                    <table className='text-left p-2 pt-0'>
                        <tbody>
                        <tr>
                            <th className='pr-2'>
                                Email
                            </th>
                            <td className='font-semibold text-200'>
                                <InputText value={currentUser?.email ?? ''} readOnly className='p-inputtext-sm' />
                            </td>
                        </tr>
                        <tr>
                            <th className='pr-2'>
                                Язык
                            </th>
                            <td>
                                <div className="p-inputgroup flex-1">
                                    <AutoComplete suggestions={filteredLanguages}
                                          completeMethod={(event: AutoCompleteCompleteEvent) => {
                                              let _filteredLanguages;

                                              if (!event.query.trim().length) {
                                                  _filteredLanguages = [...(languages ?? [])];
                                              }
                                              else {
                                                  _filteredLanguages = (languages ?? []).filter((language) => {
                                                      return language.name.toLowerCase().startsWith(event.query.toLowerCase());
                                                  });
                                              }

                                              setFilteredLanguages(_filteredLanguages);
                                          }}
                                          itemTemplate={(item: Language | null) => ShowLanguage(item?.id, languages ?? [])}
                                          value={GetLanguage(currentUser.languageId, languages)}
                                          selectedItemTemplate={(language) => {
                                              if (language == null) {
                                                  return null;
                                              }
                                              else {
                                                  return `${language.name} [${language.codeIso3}]`;
                                              }
                                          }}
                                          disabled
                                          className='p-inputtext-sm'
                                          placeholder='Язык'
                                          onChange={(e: AutoCompleteChangeEvent) => setCurrentUserLanguage(e.value ?? '')} />
                                    <Button icon="pi pi-pencil" className='border' outlined size='small'
                                            onClick={() => setIsUserLanguageEditing(true)} />
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <th className='pr-2'>
                                Дата рождения
                            </th>
                            <td>
                                <div className="p-inputgroup flex-1">
                                    <Calendar inputId="edit-birth-date"
                                              value={GetDate(currentUser.birthDate)}
                                              onChange={(e) => setCurrentUserBirthDate(e.value ?? null)}
                                              placeholder='День рождения'
                                              // className='w-full p-inputtext-sm'
                                              className='p-inputtext-sm'
                                              // showIcon
                                              dateFormat='dd-mm-yy'
                                              disabled
                                              readOnlyInput
                                    />
                                    <Button icon="pi pi-pencil" className='border' outlined size='small'
                                            disabled={GetDate(currentUser.birthDate) != null}
                                            onClick={() => setIsUserBirthDateEditing(true)} />
                                </div>
                            </td>
                        </tr>
                        </tbody>
                    </table>
                    
                    {/*<p><strong className='pr-3'>Статус:</strong>*/}
                    {/*    <Badge severity={currentUser.isBanned ? 'danger' : 'success'} value={currentUser.isBanned ? 'Забанен' : 'Активен'} />*/}
                    {/*</p>*/}

                    {/*<p><strong>Был онлайн:</strong> {currentUser?.lastOnline == null ? 'Неизвестно' : GetDate(currentUser.lastOnline)?.toISOString().slice(0, 16).replace('T', ' ') ?? '-- // --'}</p>*/}

                    <br />
                    <hr />
                    <br />
                    {/*<p><strong>Роли:</strong> {currentUser.roles.map(role => role.name).join(', ')}</p>*/}
                    <p><strong>Роли:</strong> роли</p>
                    {/*JSON:*/}
                    {/*<br />*/}
                    {/*{*/}
                    {/*    <textarea value={JSON.stringify(currentUser, null, 4)} readOnly={true} rows={20} className='w-full'/>*/}
                    {/*}*/}
                    
                    
                    
                </Card>

                
                
            </div>
            <div className='col-12 h-auto'>
                <Card
                    header={() => (
                        <div className="grid justify-content-between surface-100 border-round-md border-noround-bottom p-2 m-0">
                            <div className="col-6 text-3xl font-semibold text-500 align-content-center">
                                Сессии
                            </div>
                            <div className="col-auto align-content-center">
                                <Button
                                    label="Выйти на всех устройствах"
                                    icon="pi pi-sign-out"
                                    iconPos='right'
                                    severity="danger"
                                    // className="w-full"
                                    // disabled={!selectedGenre.name.trim()}
                                    onClick={() => deleteAllSessionsMutation.mutate()}
                                    size='small'
                                />
                            </div>
                        </div>
                    )}>
                    { ShowCurrentSession(sessions ?? []) }
                    <Divider />
                    { ShowUserSessions(sessions?.filter(q => !q.isCurrentSession) ?? [], (sessionId: string) => deleteSessionMutation.mutate(sessionId)) }
                </Card>
            </div>



            {/* Диалог подтверждения удаления аватара */}
            {currentUser && (
                <Dialog
                    header="Удаление аватара"
                    headerClassName='p-3 pb-1'
                    contentClassName='p-3 pt-0'
                    visible={isUserAvatarDeleting}
                    onHide={() => {
                        setIsUserAvatarDeleting(false);
                    }}
                >
                    <div className='text-center text-xxl text-400 mb-2'>
                        Вы хотите удалить аватар?
                    </div>

                    <div className='flex flex-row gap-2 justify-content-between'>
                        <Button
                            label="Да"
                            icon="pi pi-trash"
                            severity="danger"
                            // className="w-full"
                            // disabled={!selectedGenre.name.trim()}
                            onClick={() => deleteUserAvatarMutation.mutate()}
                            size='small'
                        />

                        <Button
                            label="Нет"
                            icon="pi pi-times"
                            onClick={() => {
                                setCurrentUserBirthDate(GetDate(currentUser.birthDate));
                                setIsUserAvatarDeleting(false);
                            }}
                            size='small'
                        />
                    </div>
                </Dialog>
            )}
            
            {/* Диалог редактирования даты рождения */}
            {currentUser && (
                <Dialog
                    header="Редактирование даты рождения"
                    headerClassName='p-3 pb-1'
                    contentClassName='p-3 pt-0'
                    visible={isUserBirthDateEditing}
                    onHide={() => {
                        setCurrentUserBirthDate(GetDate(currentUser.birthDate));
                        setIsUserBirthDateEditing(false);
                    }}
                >
                    <div className='field'>
                        {<p>{currentUser.birthDate}</p>}
                    </div>
                    <div className="field mt-5">
                        <FloatLabel>
                            <Calendar inputId="edit-birth-date"
                                      value={currentUserBirthDate}
                                      onChange={(e) => setCurrentUserBirthDate(e.value ?? null)}
                                      placeholder='День рождения'
                                      className='w-full p-inputtext-sm'
                                      showIcon
                            />
                            <label htmlFor="edit-birth-date">День рождения</label>
                        </FloatLabel>
                    </div>

                    <div className='flex flex-row gap-2 justify-content-between'>
                        <Button
                            label="Сохранить"
                            icon="pi pi-save"
                            severity="success"
                            // className="w-full"
                            // disabled={!selectedGenre.name.trim()}
                            onClick={() => editUserBirthDateMutation.mutate(DateToString(currentUserBirthDate))}
                            size='small'
                        />

                        <Button
                            label="Отменить"
                            icon="pi pi-times"
                            severity="danger"
                            // className="w-full"
                            // disabled={!selectedGenre.name.trim()}
                            onClick={() => {
                                setCurrentUserBirthDate(GetDate(currentUser.birthDate));
                                setIsUserBirthDateEditing(false);
                            }}
                            size='small'
                        />
                    </div>
                </Dialog>
            )}

            {/* Диалог редактирования языка */}
            {currentUser && (
                <Dialog
                    header="Редактирование языка"
                    headerClassName='p-3 pb-1'
                    contentClassName='p-3 pt-0'
                    visible={isUserLanguageEditing}
                    onHide={() => {
                        setCurrentUserBirthDate(GetDate(currentUser.birthDate));
                        setIsUserLanguageEditing(false);
                    }}
                >
                    <div className='field'>
                        {<p><strong>Язык:</strong> {ShowLanguage(currentUser?.languageId, languages ?? [])}</p>}
                    </div>
                    <div className="field mt-5">
                        <FloatLabel>
                            <AutoComplete suggestions={filteredLanguages}
                                          completeMethod={(event: AutoCompleteCompleteEvent) => {
                                              let _filteredLanguages;

                                              if (!event.query.trim().length) {
                                                  _filteredLanguages = [...(languages ?? [])];
                                              }
                                              else {
                                                  _filteredLanguages = (languages ?? []).filter((language) => {
                                                      return language.name.toLowerCase().startsWith(event.query.toLowerCase());
                                                  });
                                              }

                                              setFilteredLanguages(_filteredLanguages);
                                          }}
                                          itemTemplate={(item: Language | null) => ShowLanguage(item?.id, languages ?? [])}
                                // field='name'
                                // value={currentUserLanguage != null ? currentUserLanguage : null}
                                          value={currentUserLanguage?.id != null ? `${currentUserLanguage.name} [${currentUserLanguage.codeIso3}]` : null}
                                          className='w-full p-inputtext-sm'
                                          placeholder='Язык'
                                          onChange={(e: AutoCompleteChangeEvent) => setCurrentUserLanguage(e.value ?? '')} dropdown />
                            <label htmlFor="edit-birth-date">Язык</label>
                        </FloatLabel>
                    </div>

                    <div className='flex flex-row gap-2 justify-content-between'>
                        <Button
                            label="Сохранить"
                            icon="pi pi-save"
                            // className="w-full"
                            // disabled={!selectedGenre.name.trim()}
                            severity="success"
                            onClick={() => editUserLanguageMutation.mutate(currentUserLanguage?.id ?? null)}
                            size='small'
                        />

                        <Button
                            label="Отменить"
                            icon="pi pi-times"
                            // className="w-full"
                            // disabled={!selectedGenre.name.trim()}
                            severity="danger"
                            onClick={() => {
                                setCurrentUserBirthDate(GetDate(currentUser.birthDate));
                                setIsUserLanguageEditing(false);
                            }}
                            size='small'
                        />
                    </div>
                </Dialog>
            )}
            
        </div>
    )
}

function ShowLanguage(languageId: string | null | undefined, languages: Array<Language>){
    const language = languages.find(l => l.id === languageId);
    if (language == null) {
        return (<>не найден</>);
    }
    else {
        return (<>{language.name} [{language.codeIso3}]</>);
    }
}

function GetLanguage(languageId: string | null | undefined, languages: Array<Language> | null | undefined){
    const language = (languages ?? []).find(l => l.id === languageId);
    return language ?? null;
}

function ShowUserSessions(sessions: Array<SessionModel>, deleteSessionCallback?: ((sessionId: string) => void) | null | undefined){
    return (
        <DataScroller value={sessions} itemTemplate={(session) => ShowSession(session, deleteSessionCallback)} rows={5} inline scrollHeight="20rem"
              className='p-0'
              // footer='as'
              // header='Scroll Down to Load More'
        />
    )
}

function ShowCurrentSession(sessions: Array<SessionModel>){
    const session = sessions.find(q => q.isCurrentSession);
    if (session == null) {
        return (<></>);
    }
    
    return ShowSession(session);
}

function ShowSession(session: SessionModel, deleteSessionCallback?: ((sessionId: string) => void) | null | undefined){
    return (
        <div className='p-card my-2 border-round-md surface-50'>
            <div className='p-card-header flex flex-row justify-content-between border-round-md border-noround-bottom p-2 m-0 surface-100'>
                <div className='text-xl font-semibold text-500 align-content-center'>
                    {session.userAgent}
                </div>
                { !session.isCurrentSession &&
                    <div>
                        {/*<Button icon='pi pi-sign-out' severity='danger' size='small' />*/}
                        <Button icon='pi pi-trash' severity='danger' size='small' onClick={() => deleteSessionCallback?.(session.id)} />
                    </div>
                }
            </div>
            <div className='p-card-body p-0'>
                <div className='grid p-2 pb-0'>
                    <div className='col align-content-center flex flex-row justify-content-start gap-4'>
                        <div className='align-content-center'>
                            {/*<OnlineBadgeComponent onlineStatus={currentUser.onlineStatus ?? UserOnlineStatus.unknown} className='absolute' style={onlineStatusBadgeStyle} size='large' showStatusText={true} />*/}
                            <OnlineBadgeComponent onlineStatus={session.onlineStatus ?? UserOnlineStatus.unknown} size='normal' showStatusText={true} />
                            {/*<OnlineBadgeComponent onlineStatus={UserOnlineStatus.online} size='normal' showStatusText={true} />*/}
                        </div>
                        <div className='align-content-center'>
                            {session.country}, {session.region}
                        </div>
                        <div className='align-content-center'>
                            {GetDate(session.lastOnline)?.toString() ?? ''}
                        </div>
                    </div>
                    {(session.onlineStatus == UserOnlineStatus.offline || session.onlineStatus == UserOnlineStatus.unknown) &&
                        <div className='col-auto align-content-center p-2'>
                            {GetSessionExpireDays(session, '')}
                        </div>
                    }

                    {/*JSON:*/}
                    {/*<br />*/}
                    {/*{*/}
                    {/*    <textarea value={JSON.stringify(session, null, 4)} readOnly={true} rows={20} className='w-full'/>*/}
                    {/*}*/}
                </div>
            </div>
        </div>
    );
    
    // return (
    //     <Card
    //         // className='border border-1 border-round-md my-3 surface-50 p-0 pt-2 px-2'
    //         className='my-2 border-round-2xl surface-50'
    //         header={() =>
    //             <div className="flex flex-row justify-content-between border-round-2xl border-noround-bottom p-2 m-0 surface-100">
    //                 <div className='text-xl font-semibold text-500 align-content-center'>
    //                     {session.userAgent}
    //                 </div>
    //                 { !session.isCurrentSession &&
    //                     <div>
    //                         {/*<Button icon='pi pi-sign-out' severity='danger' size='small' />*/}
    //                         <Button icon='pi pi-trash' severity='danger' size='small' onClick={() => deleteSessionCallback?.(session.id)} />
    //                     </div>
    //                 }
    //             </div>
    //         }
    //     >
    //         <div className='grid'  style={{marginTop:'-2.5rem', marginBottom:'-1rem' }} >
    //             <div className='col align-content-center flex flex-row justify-content-start gap-4'>
    //                 <div>
    //                     {/*<OnlineBadgeComponent onlineStatus={currentUser.onlineStatus ?? UserOnlineStatus.unknown} className='absolute' style={onlineStatusBadgeStyle} size='large' showStatusText={true} />*/}
    //                     <OnlineBadgeComponent onlineStatus={session.onlineStatus ?? UserOnlineStatus.unknown} size='normal' showStatusText={true} />
    //                     {/*<OnlineBadgeComponent onlineStatus={UserOnlineStatus.online} size='normal' showStatusText={true} />*/}
    //                 </div>
    //                 <div>
    //                     {session.country}, {session.region}
    //                 </div>
    //                 <div>
    //                     {GetDate(session.lastOnline).toString()}
    //                 </div>
    //             </div>
    //             {(session.onlineStatus == UserOnlineStatus.offline || session.onlineStatus == UserOnlineStatus.unknown) &&
    //                 <div className='col-auto align-content-center'>
    //                     <span>Истекает через: </span><span>{GetSessionExpireDays(session, '')}</span>
    //                 </div>
    //             }
    //         </div>
    //     </Card>
    // );
}

function GetSessionExpireDays(session: SessionModel, classString?: string | null) {
    const expireDays = differenceInDays(new Date(), session.expiredDate);
    let daysString = 'дней';
    if (expireDays == 1){
        daysString = 'день';
    }
    else if (expireDays > 1 && expireDays < 5){
        daysString = 'дня';
    }
    if (expireDays < 7){
        return (
            <>
                <span>Истекает через: </span><span className={`${classString != null ? (classString + ' ') : ''}${expireDays < 3 ? 'text-red-400' : 'text-yellow-400'}`}>{expireDays} {daysString}</span>
            </>
        )
    }
    else{
        // <h6>Истекает через: </h6>
        return(
            <></>
        )
    }

}

function differenceInDays(date1: Date, date2: Date): number {
    const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
    const diffInTime = new Date(date2).getTime() - new Date(date1).getTime();
    return Math.round(diffInTime / oneDay);
}

type MediaInfoModel = {
    type: MediaInfoType,
    data: string,
}

function mediaInfoFromFile(file: Blob | null, propsMediainfo: MediaInfoEditModel | null) : Promise<MediaInfoModel | null>{
    //return  new Promise<MediaInfo | null>((resolve, reject) => {
    return 	new Promise<MediaInfoModel | null>((resolve) => {
        if (file == null) return resolve(null)
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () =>
            typeof reader.result === "string" ? resolve({
                type: propsMediainfo?.type ?? MediaInfoType.Image,
                data: reader.result
            } as MediaInfoModel) : resolve(null);
        //   reader.onerror = error => reject(error);
        //   reader.onerror = error => console.error(error);
    });
}

export default Account;