import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faTrash} from "@fortawesome/free-solid-svg-icons";
import {useContext, useState} from "react";
import System from "@/lib/models/System";
import {SessionContext} from "@/context/SessionContext";
import {BookProps} from "@/lib/models/Book";
import {LangContext, LangContextProps} from "@/context/LangContext";
import {AlertContext, AlertContextProps} from "@/context/AlertContext";
import AlertBox from "@/components/AlertBox";
import OfflineContext, {OfflineContextType} from "@/context/OfflineContext";
import {BookContext} from "@/context/BookContext";

interface DeleteBookProps {
    bookId: string;
}

export default function DeleteBook({bookId}: DeleteBookProps) {
    const {session, setSession} = useContext(SessionContext);
    const {lang} = useContext<LangContextProps>(LangContext)
    const {isCurrentlyOffline} = useContext<OfflineContextType>(OfflineContext);
    const {book} = useContext(BookContext);
    const [showConfirmBox, setShowConfirmBox] = useState<boolean>(false);
    const {errorMessage} = useContext<AlertContextProps>(AlertContext)
    
    function handleConfirmation(): void {
        setShowConfirmBox(true);
    }

    async function handleDeleteBook(): Promise<void> {
        try {
            let response: boolean;
            if (isCurrentlyOffline()) {
                response = await window.electron.invoke<boolean>('db:book:delete', {
                    id: bookId,
                });
            } else {
                if (book?.localBook) {
                    response = await window.electron.invoke<boolean>('db:book:delete', {
                        id: bookId,
                    });
                } else {
                    response = await System.authDeleteToServer<boolean>(
                        `book/delete`,
                        {
                            id: bookId,
                        },
                        session.accessToken,
                        lang
                    );
                }
            }
            if (response) {
                setShowConfirmBox(false);
                const updatedBooks: BookProps[] = (session.user?.books || []).reduce((acc: BookProps[], book: BookProps): BookProps[] => {
                    if (book.bookId !== bookId) {
                        acc.push({...book});
                    }
                    return acc;
                }, []);
                if (!response) {
                    errorMessage("Une erreur est survenue lors de la suppression du livre.");
                    return;
                }
                const updatedUser = {
                    ...(JSON.parse(JSON.stringify(session.user))),
                    books: updatedBooks
                };
                
                const newSession = {
                    ...JSON.parse(JSON.stringify(session)),
                    user: updatedUser,
                    isConnected: true,
                    accessToken: session.accessToken
                };
                
                setSession(newSession);
                
                setTimeout((): void => {
                    setSession({...newSession});
                }, 0);
            }
        } catch (e: unknown) {
            if (e instanceof Error) {
                errorMessage(e.message)
            } else {
                errorMessage("Une erreur inconnue est survenue lors de la suppression du livre.");
            }
        }
    }

    return (
        <>
            <button onClick={handleConfirmation}
                    className="text-muted hover:text-error hover:bg-error/10 transition-all duration-200 p-2 rounded-lg hover:scale-110">
                <FontAwesomeIcon icon={faTrash} className={'w-5 h-5'}/>
            </button>
            {
                showConfirmBox && (
                    <AlertBox title={'Suppression du livre'}
                              message={'Vous être sur le point de supprimer votre livre définitivement.'} type={"danger"}
                              onConfirm={handleDeleteBook} onCancel={() => setShowConfirmBox(false)}
                              confirmText={'Supprimer'} cancelText={'Annuler'}/>
                )
            }
        </>
    )
}
