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 {serverOnlyBooks, setServerOnlyBooks, localOnlyBooks, setLocalOnlyBooks, localSyncedBooks, setLocalSyncedBooks, setServerSyncedBooks}: BooksSyncContextProps = useContext<BooksSyncContextProps>(BooksSyncContext)
    const [deleteLocalToo, setDeleteLocalToo] = useState<boolean>(false);
    const ifLocalOnlyBook: SyncedBook | undefined = localOnlyBooks.find((b: SyncedBook): boolean => b.id === bookId);
    const ifSyncedBook: SyncedBook | undefined = localSyncedBooks.find((b: SyncedBook): boolean => b.id === bookId);
    const {book}: BookContextProps = useContext<BookContextProps>(BookContext);
    const {isCurrentlyOffline}: OfflineContextType = useContext<OfflineContextType>(OfflineContext);
    
    function handleConfirmation(): void {
        setDeleteLocalToo(false);
        setShowConfirmBox(true);
    }

    async function handleDeleteBook(): Promise<void> {
        try {
            let response: boolean;
            const deletedAt: number = Math.floor(Date.now() / 1000);

            if (isDesktop && (isCurrentlyOffline() || ifLocalOnlyBook)) {
                response = await tauri.deleteBook(bookId, deletedAt);
            } else {
                response = await apiDelete<boolean>('book/delete', {id: bookId, deletedAt}, session.accessToken, lang);
                if (response && isDesktop && ifSyncedBook && deleteLocalToo) {
                    await tauri.deleteBook(bookId, deletedAt);
                }
            }
            if (response) {
                setShowConfirmBox(false);
                if (ifLocalOnlyBook) {
                    setLocalOnlyBooks(localOnlyBooks.filter((b: SyncedBook): boolean => b.id !== bookId));
                } else if (ifSyncedBook) {
                    setLocalSyncedBooks(localSyncedBooks.filter((b: SyncedBook): boolean => b.id !== bookId));
                    setServerSyncedBooks((prev: SyncedBook[]): SyncedBook[] => prev.filter((b: SyncedBook): boolean => b.id !== bookId));
                    if (!deleteLocalToo) {
                        setLocalOnlyBooks([...localOnlyBooks, ifSyncedBook]);
                    }
                } else {
                    setServerOnlyBooks(serverOnlyBooks.filter((b: SyncedBook): boolean => b.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'}/>
                )
            }
        </>
    )
}
