'use client';
import React, {useContext, useEffect, useState} from 'react';
import {useParams, useRouter} from '@/lib/navigation';
import {SessionContext, SessionContextProps} from '@/context/SessionContext';
import {LangContext, LangContextProps} from '@/context/LangContext';
import {AlertContext, AlertContextProps} from '@/context/AlertContext';
import {ChapterContext, ChapterContextProps} from '@/context/ChapterContext';
import {apiGet} from '@/lib/api/client';
import {isDesktop} from '@/lib/configs';
import * as tauri from '@/lib/tauri';
import OfflineContext, {OfflineContextType} from '@/context/OfflineContext';
import {BookContext, BookContextProps} from '@/context/BookContext';
import {ChapterProps} from '@/lib/types/chapter';
import {useTranslations} from '@/lib/i18n';
import NoBookHome from '@/components/editor/NoBookHome';

export default function BookPage() {
    const params: { bookId: string } = useParams<{ bookId: string }>();
    const router = useRouter();
    const {session}: SessionContextProps = useContext<SessionContextProps>(SessionContext);
    const {lang}: LangContextProps = useContext<LangContextProps>(LangContext);
    const {errorMessage}: AlertContextProps = useContext<AlertContextProps>(AlertContext);
    const {setChapter}: ChapterContextProps = useContext<ChapterContextProps>(ChapterContext);
    const {book}: BookContextProps = useContext<BookContextProps>(BookContext);
    const {isCurrentlyOffline}: OfflineContextType = useContext<OfflineContextType>(OfflineContext);
    const t = useTranslations();

    const [isRedirecting, setIsRedirecting] = useState<boolean>(true);

    useEffect((): void => {
        if (session.accessToken && params.bookId) {
            redirectToLastChapter().then();
        }
    }, [session.accessToken, params.bookId]);

    async function redirectToLastChapter(): Promise<void> {
        try {
            let response: ChapterProps | null;
            if (isDesktop && (isCurrentlyOffline() || book?.localBook)) {
                response = await tauri.getLastChapter(params.bookId);
            } else {
                response = await apiGet<ChapterProps | null>(
                    'chapter/last-chapter', session.accessToken, lang, {bookid: params.bookId}
                );
            }
            if (response) {
                setChapter(response);
                router.replace(`/book/${params.bookId}/chapter/${response.chapterId}`);
                return;
            }
            setIsRedirecting(false);
        } catch (e: unknown) {
            if (e instanceof Error) {
                errorMessage(e.message);
            } else {
                errorMessage(t('homePage.errors.lastChapterError'));
            }
            setIsRedirecting(false);
        }
    }

    if (isRedirecting) {
        return null;
    }

    return <NoBookHome/>;
}
