/*
 * Copyright (C) Contributors to the Suwayomi project
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

import { useState } from 'react';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogActions from '@mui/material/DialogActions';
import Button from '@mui/material/Button';
import { useLingui } from '@lingui/react/macro';
import { requestManager } from '@/lib/requests/RequestManager.ts';
import { useUpdateChecker } from '@/features/app-updates/hooks/useUpdateChecker.tsx';
import { VersionUpdateInfoDialog } from '@/features/app-updates/components/VersionUpdateInfoDialog.tsx';
import { useMetadataServerSettings } from '@/features/settings/services/ServerSettingsMetadata.ts';
import { useLocalStorage } from '@/base/hooks/useStorage.tsx';
import { AppRoutes } from '@/base/AppRoute.constants.ts';

const disabledUpdateCheck = () => Promise.resolve();

export const ServerUpdateChecker = () => {
    const { t } = useLingui();

    const [serverVersion, setServerVersion] = useLocalStorage<string>('serverVersion');
    const [open, setOpen] = useState(false);

    const {
        settings: { serverInformAvailableUpdate, serverInformVersionUpdated },
        loading: areMetadataServerSettingsLoading,
    } = useMetadataServerSettings();

    const {
        data: serverUpdateCheckData,
        loading: isCheckingForServerUpdate,
        error: serverUpdateCheckError,
        refetch: checkForUpdate,
    } = requestManager.useCheckForServerUpdate({
        notifyOnNetworkStatusChange: true,
        fetchPolicy: 'cache-only',
    });

    const { data } = requestManager.useGetAbout();
    const { aboutServer } = data ?? {};

    const selectedServerChannelInfo = serverUpdateCheckData?.checkForServerUpdates?.find(
        (channel) => channel.channel === aboutServer?.buildType,
    );
    const version = aboutServer ? aboutServer.version : undefined;
    const isServerUpdateAvailable = !!selectedServerChannelInfo?.tag && selectedServerChannelInfo.tag !== version;

    const updateChecker = useUpdateChecker(
        'server',
        serverInformAvailableUpdate ? checkForUpdate : disabledUpdateCheck,
        selectedServerChannelInfo?.tag,
    );

    const changelogUrl =
        aboutServer?.buildType.toLowerCase() === 'stable'
            ? `https://github.com/Suwayomi/Suwayomi-Server/releases/tag/${aboutServer.version}`
            : undefined;

    const isSameAsCurrent = !version || !serverVersion || serverVersion === version;

    const saveInitialVersion = !serverVersion && !!version;
    if (saveInitialVersion) {
        setServerVersion(version);
    }

    if (!areMetadataServerSettingsLoading && !isSameAsCurrent && !open) {
        if (serverInformVersionUpdated) {
            setOpen(true);
        } else {
            setServerVersion(version);
        }
    }

    if (isCheckingForServerUpdate) {
        return null;
    }

    if (serverUpdateCheckError) {
        return null;
    }

    if (isServerUpdateAvailable) {
        if (!serverInformAvailableUpdate) {
            return null;
        }

        const isAboutPage = window.location.pathname === AppRoutes.about.path;
        if (isAboutPage) {
            return null;
        }

        if (!updateChecker.handleUpdate) {
            return null;
        }

        return (
            <VersionUpdateInfoDialog
                info={t`Server version ${selectedServerChannelInfo.tag} (${selectedServerChannelInfo.channel}) available for download`}
                actionTitle={t`Download`}
                actionUrl={selectedServerChannelInfo.url}
                updateCheckerProps={['server', checkForUpdate, selectedServerChannelInfo?.tag]}
            />
        );
    }

    if (!open) {
        return null;
    }

    return (
        <Dialog open={open}>
            <DialogTitle>{t`Updated version`}</DialogTitle>
            <DialogContent>
                <DialogContentText>{t`Server was updated to version ${version} (${aboutServer?.buildType})`}</DialogContentText>
            </DialogContent>
            <DialogActions>
                {changelogUrl && (
                    <Button href={changelogUrl} target="_blank" rel="noreferrer">
                        {t`Changelog`}
                    </Button>
                )}
                <Button
                    onClick={() => {
                        setServerVersion(version);
                        setOpen(false);
                    }}
                    variant="contained"
                >
                    {t`Ok`}
                </Button>
            </DialogActions>
        </Dialog>
    );
};
