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 {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";
import {BooksSyncContext, BooksSyncContextProps} from "@/context/BooksSyncContext";
import {SyncedBook} from "@/lib/models/SyncedBook";

interface DeleteBookProps {
    bookId: string;
}

export default function DeleteBook({bookId}: DeleteBookProps) {
    const {session} = 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)
    const {serverOnlyBooks,setServerOnlyBooks,localOnlyBooks,setLocalOnlyBooks} = useContext<BooksSyncContextProps>(BooksSyncContext);
    
    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 {
                const ifLocalBook:SyncedBook|undefined = localOnlyBooks.find((book: SyncedBook):boolean => book.id === bookId);
                if (ifLocalBook) {
                    response = await window.electron.invoke<boolean>('db:book:delete', {
                        id: bookId,
                    });
                } else {
                    response = await window.electron.invoke<boolean>('db:book:delete', {
                        id: bookId,
                    });
                    response = await System.authDeleteToServer<boolean>(
                        `book/delete`,
                        {
                            id: bookId,
                        },
                        session.accessToken,
                        lang
                    );
                }
            }
            if (response) {
                setShowConfirmBox(false);
                if (book?.localBook){
                    setLocalOnlyBooks(localOnlyBooks.filter((book:SyncedBook):boolean => book.id !== bookId));
                    return;
                }
                setServerOnlyBooks(serverOnlyBooks.filter((book:SyncedBook):boolean => book.id !== bookId));
                setShowConfirmBox(false);
            }
        } 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'}/>
                )
            }
        </>
    )
}
