import * as tauri from '@/lib/tauri';
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 {BooksSyncContext, BooksSyncContextProps} from "@/context/BooksSyncContext";
import {SyncedBook} from "@/lib/models/SyncedBook";
import {useTranslations} from "next-intl";

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 [showConfirmBox, setShowConfirmBox] = useState<boolean>(false);
    const [deleteLocalToo, setDeleteLocalToo] = useState<boolean>(false);
    const {errorMessage} = useContext<AlertContextProps>(AlertContext)
    const {serverOnlyBooks,setServerOnlyBooks,localOnlyBooks,setLocalOnlyBooks,localSyncedBooks,setLocalSyncedBooks,setServerSyncedBooks} = useContext<BooksSyncContextProps>(BooksSyncContext);
    const t = useTranslations('deleteBook');

    const ifLocalOnlyBook: SyncedBook | undefined = localOnlyBooks.find((book: SyncedBook): boolean => book.id === bookId);
    const ifSyncedBook: SyncedBook | undefined = localSyncedBooks.find((book: SyncedBook): boolean => book.id === bookId);

    function handleConfirmation(): void {
        setDeleteLocalToo(false);
        setShowConfirmBox(true);
    }

    async function handleDeleteBook(): Promise<void> {
        try {
            let response: boolean;
            const deletedAt: number = System.timeStampInSeconds();
            const deleteData = { id: bookId, deletedAt };

            if (isCurrentlyOffline() || ifLocalOnlyBook) {
                response = await tauri.deleteBook(deleteData.id, deleteData.deletedAt);
            } else {
                response = await System.authDeleteToServer<boolean>(
                    `book/delete`,
                    deleteData,
                    session.accessToken,
                    lang
                );
                // If synced book and user wants to delete local too
                if (response && ifSyncedBook && deleteLocalToo) {
                    await tauri.deleteBook(deleteData.id, deleteData.deletedAt);
                }
            }
            if (response) {
                setShowConfirmBox(false);
                if (ifLocalOnlyBook) {
                    setLocalOnlyBooks(localOnlyBooks.filter((b: SyncedBook): boolean => b.id !== bookId));
                } else if (ifSyncedBook) {
                    // Remove from synced lists
                    setLocalSyncedBooks(localSyncedBooks.filter((b: SyncedBook): boolean => b.id !== bookId));
                    setServerSyncedBooks((prev: SyncedBook[]): SyncedBook[] => prev.filter((b: SyncedBook): boolean => b.id !== bookId));
                    // If not deleting local, move to localOnlyBooks
                    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(t('errorUnknown'));
            }
        }
    }

    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={t('title')}
                              message={t('message')}
                              type={"danger"}
                              onConfirm={handleDeleteBook}
                              onCancel={() => setShowConfirmBox(false)}
                              confirmText={t('confirm')}
                              cancelText={t('cancel')}>
                        {ifSyncedBook && !isCurrentlyOffline() && (
                            <div className="mt-4 p-3 bg-error/10 border border-error/30 rounded-lg">
                                <label className="flex items-center gap-3 cursor-pointer">
                                    <input
                                        type="checkbox"
                                        checked={deleteLocalToo}
                                        onChange={(e) => setDeleteLocalToo(e.target.checked)}
                                        className="w-5 h-5 accent-error cursor-pointer"
                                    />
                                    <span className="text-sm text-text-primary">
                                        {t('deleteLocalToo')}
                                    </span>
                                </label>
                                <p className="text-xs text-error mt-2">
                                    {t('deleteLocalWarning')}
                                </p>
                            </div>
                        )}
                    </AlertBox>
                )
            }
        </>
    )
}
