import {Trash2} from 'lucide-react';
import React, {useContext, useState} from "react";
import IconButton from "@/components/ui/IconButton";
import {apiDelete} from "@/lib/api/client";
import {isDesktop} from '@/lib/configs';
import * as tauri from '@/lib/tauri';
import OfflineContext, {OfflineContextType} from '@/context/OfflineContext';
import {SessionContext, SessionContextProps} from "@/context/SessionContext";
import {BookContext, BookContextProps} from "@/context/BookContext";
import {LangContext, LangContextProps} from "@/context/LangContext";
import {AlertContext, AlertContextProps} from "@/context/AlertContext";
import AlertBox from "@/components/ui/AlertBox";
import {BooksSyncContext, BooksSyncContextProps} from "@/context/BooksSyncContext";
import {SyncedBook} from "@/lib/types/synced-book";

interface DeleteBookProps {
    bookId: string;
}

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

    async function handleDeleteBook(): Promise<void> {
        try {
            let response: boolean;
            if (isDesktop && (isCurrentlyOffline() || book?.localBook)) {
                response = await tauri.deleteBook(bookId, Date.now());
            } else {
                response = await apiDelete<boolean>('book/delete', {
                    id: bookId,
                }, session.accessToken, lang);
            }
            if (response) {
                setShowConfirmBox(false);
                if (!response) {
                    errorMessage("Une erreur est survenue lors de la suppression du livre.");
                    return;
                }
                setServerSyncedBooks((prev: SyncedBook[]): SyncedBook[] => prev.filter((book: SyncedBook): boolean => book.id !== bookId))
            }
        } catch (e: unknown) {
            if (e instanceof Error) {
                errorMessage(e.message)
            } else {
                errorMessage("Une erreur inconnue est survenue lors de la suppression du livre.");
            }
        }
    }

    return (
        <>
            <IconButton icon={Trash2} variant="ghost" shape="square" onClick={handleConfirmation}/>
            {
                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'}/>
                )
            }
        </>
    )
}
