'use client'

import {ChangeEvent, useContext, useEffect, useState} from 'react';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {faArrowDown, faArrowUp, faBookmark, faMinus, faPlus, faTrash,} from '@fortawesome/free-solid-svg-icons';
import {ChapterListProps} from '@/lib/models/Chapter';
import System from '@/lib/models/System';
import {BookContext} from '@/context/BookContext';
import {SessionContext} from '@/context/SessionContext';
import {AlertContext} from '@/context/AlertContext';
import AlertBox from "@/components/AlertBox";
import CollapsableArea from "@/components/CollapsableArea";
import {useTranslations} from "next-intl";
import {LangContext} from "@/context/LangContext";
import OfflineContext, {OfflineContextType} from "@/context/OfflineContext";
import {LocalSyncQueueContext, LocalSyncQueueContextProps} from "@/context/SyncQueueContext";
import {BooksSyncContext, BooksSyncContextProps} from "@/context/BooksSyncContext";
import {SyncedBook} from "@/lib/models/SyncedBook";

interface MainChapterProps {
    chapters: ChapterListProps[];
    setChapters: React.Dispatch<React.SetStateAction<ChapterListProps[]>>;
}

export default function MainChapter({chapters, setChapters}: MainChapterProps) {
    const t = useTranslations();
    const {lang} = useContext(LangContext)
    const {isCurrentlyOffline} = useContext<OfflineContextType>(OfflineContext);
    const {addToQueue} = useContext<LocalSyncQueueContextProps>(LocalSyncQueueContext);
    const {localSyncedBooks} = useContext<BooksSyncContextProps>(BooksSyncContext);
    const {book} = useContext(BookContext);
    const {session} = useContext(SessionContext);
    const {errorMessage, successMessage} = useContext(AlertContext);
    
    const bookId: string | undefined = book?.bookId;
    const token: string = session.accessToken;
    
    const [newChapterTitle, setNewChapterTitle] = useState<string>('');
    const [newChapterOrder, setNewChapterOrder] = useState<number>(0);
    
    const [deleteConfirmMessage, setDeleteConfirmMessage] = useState<boolean>(false);
    const [chapterIdToRemove, setChapterIdToRemove] = useState<string>('');
    
    function handleChapterTitleChange(chapterId: string, newTitle: string) {
        const updatedChapters: ChapterListProps[] = chapters.map((chapter: ChapterListProps): ChapterListProps => {
            if (chapter.chapterId === chapterId) {
                return {...chapter, title: newTitle};
            }
            return chapter;
        });
        setChapters(updatedChapters);
    }
    
    function moveChapter(index: number, direction: number): void {
        const visibleChapters: ChapterListProps[] = chapters
            .filter((chapter: ChapterListProps): boolean => chapter.chapterOrder !== -1)
            .sort((a: ChapterListProps, b: ChapterListProps): number => (a.chapterOrder || 0) - (b.chapterOrder || 0));
        
        const currentChapter: ChapterListProps = visibleChapters[index];
        const allChaptersIndex: number = chapters.findIndex(
            (chapter: ChapterListProps): boolean => chapter.chapterId === currentChapter.chapterId,
        );
        
        const updatedChapters: ChapterListProps[] = [...chapters];
        
        const currentOrder: number = updatedChapters[allChaptersIndex].chapterOrder || 0;
        const newOrder: number = Math.max(0, currentOrder + direction);
        
        updatedChapters[allChaptersIndex] = {
            ...updatedChapters[allChaptersIndex],
            chapterOrder: newOrder,
        };
        
        setChapters(updatedChapters);
    }
    
    function moveChapterUp(index: number): void {
        moveChapter(index, -1);
    }
    
    function moveChapterDown(index: number): void {
        moveChapter(index, 1);
    }
    
    async function deleteChapter(): Promise<void> {
        try {
            setDeleteConfirmMessage(false);
            let response: boolean;
            const deletedAt: number = System.timeStampInSeconds();
            const deleteData = {
                bookId,
                chapterId: chapterIdToRemove,
                deletedAt,
            };
            if (isCurrentlyOffline() || book?.localBook) {
                response = await window.electron.invoke<boolean>('db:chapter:remove', deleteData);
            } else {
                response = await System.authDeleteToServer<boolean>('chapter/remove', deleteData, token, lang);

                if (localSyncedBooks.find((syncedBook: SyncedBook): boolean => syncedBook.id === bookId)) {
                    addToQueue('db:chapter:remove', deleteData);
                }
            }
            if (!response) {
                errorMessage(t("mainChapter.errorDelete"));
            }
            const updatedChapters: ChapterListProps[] = chapters.filter((chapter: ChapterListProps): boolean => chapter.chapterId !== chapterIdToRemove,);
            setChapters(updatedChapters);
        } catch (e: unknown) {
            if (e instanceof Error) {
                errorMessage(e.message)
            } else {
                errorMessage(t("mainChapter.errorUnknownDelete"));
            }
        }
    }
    
    async function addNewChapter(): Promise<void> {
        if (newChapterTitle.trim() === '') {
            return;
        }

        try {
            let responseId: string;
            const chapterData = {
                bookId: bookId,
                wordsCount: 0,
                chapterOrder: newChapterOrder ? newChapterOrder : 0,
                title: newChapterTitle,
            };
            if (isCurrentlyOffline() || book?.localBook) {
                responseId = await window.electron.invoke<string>('db:chapter:add', chapterData);
            } else {
                responseId = await System.authPostToServer<string>('chapter/add', chapterData, token);

                if (localSyncedBooks.find((syncedBook: SyncedBook): boolean => syncedBook.id === bookId)) {
                    addToQueue('db:chapter:add', {
                        ...chapterData,
                        chapterId: responseId,
                    });
                }
            }
            if (!responseId) {
                errorMessage(t("mainChapter.errorAdd"));
                return;
            }
            const newChapter: ChapterListProps = {
                chapterId: responseId as string,
                title: newChapterTitle,
                chapterOrder: newChapterOrder,
                summary: '',
                goal: '',
            };
            setChapters([...chapters, newChapter]);
            setNewChapterTitle('');

            setNewChapterOrder(newChapterOrder + 1);
        } catch (e: unknown) {
            if (e instanceof Error) {
                errorMessage(e.message)
            } else {
                errorMessage(t("mainChapter.errorUnknownAdd"));
            }
        }
    }
    
    function decrementNewChapterOrder(): void {
        if (newChapterOrder > 0) {
            setNewChapterOrder(newChapterOrder - 1);
        }
    }
    
    function incrementNewChapterOrder(): void {
        setNewChapterOrder(newChapterOrder + 1);
    }
    
    useEffect((): void => {
        const visibleChapters: ChapterListProps[] = chapters
            .filter((chapter: ChapterListProps): boolean => chapter.chapterOrder !== -1)
            .sort((a: ChapterListProps, b: ChapterListProps): number =>
                (a.chapterOrder || 0) - (b.chapterOrder || 0),
            );
        
        const nextOrder: number =
            visibleChapters.length > 0
                ? (visibleChapters[visibleChapters.length - 1].chapterOrder || 0) + 1
                : 0;
        
        setNewChapterOrder(nextOrder);
    }, [chapters]);
    
    const visibleChapters: ChapterListProps[] = chapters
        .filter((chapter: ChapterListProps): boolean => chapter.chapterOrder !== -1)
        .sort((a: ChapterListProps, b: ChapterListProps): number => (a.chapterOrder || 0) - (b.chapterOrder || 0));
    
    return (
        <div>
            <CollapsableArea icon={faBookmark} title={t("mainChapter.chapters")} children={
                <div className="space-y-4">
                    {visibleChapters.length > 0 ? (
                        <div>
                            {visibleChapters.map((item: ChapterListProps, index: number) => (
                                <div key={item.chapterId}
                                     className="mb-2 bg-secondary/30 rounded-xl p-3 shadow-sm hover:shadow-md transition-all duration-200">
                                    <div className="flex items-center">
                                <span
                                    className="bg-primary-dark text-white text-sm w-6 h-6 rounded-full text-center leading-6 mr-2">
                                  {item.chapterOrder !== undefined ? item.chapterOrder : index}
                                </span>
                                        <input
                                            className="flex-1 text-text-primary text-base px-2 py-1 bg-transparent border-b border-secondary/50 focus:outline-none focus:border-primary transition-colors duration-200"
                                            value={item.title}
                                            onChange={(e: ChangeEvent<HTMLInputElement>) => handleChapterTitleChange(item.chapterId, e.target.value)}
                                            placeholder={t("mainChapter.chapterTitlePlaceholder")}
                                        />
                                        <div className="flex ml-1">
                                            <button
                                                className={`p-1.5 mx-0.5 rounded-lg hover:bg-secondary/50 transition-all duration-200 ${
                                                    item.chapterOrder === 0 ? 'text-muted cursor-not-allowed' : 'text-primary hover:scale-110'
                                                }`}
                                                onClick={(): void => moveChapterUp(index)}
                                                disabled={item.chapterOrder === 0}
                                            >
                                                <FontAwesomeIcon icon={faArrowUp} size="sm"/>
                                            </button>
                                            <button
                                                className="p-1.5 mx-0.5 rounded-lg text-primary hover:bg-secondary/50 hover:scale-110 transition-all duration-200"
                                                onClick={(): void => moveChapterDown(index)}
                                            >
                                                <FontAwesomeIcon icon={faArrowDown} size="sm"/>
                                            </button>
                                            <button
                                                className="p-1.5 mx-0.5 rounded-lg text-error hover:bg-error/20 hover:scale-110 transition-all duration-200"
                                                onClick={(): void => {
                                                    setChapterIdToRemove(item.chapterId);
                                                    setDeleteConfirmMessage(true);
                                                }}
                                            >
                                                <FontAwesomeIcon icon={faTrash} size="sm"/>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    ) : (
                        <p className="text-text-secondary text-center py-2">
                            {t("mainChapter.noChapter")}
                        </p>
                    )}
                    
                    <div className="bg-secondary/30 rounded-xl p-3 mt-3 shadow-sm">
                        <div className="flex items-center">
                            <div
                                className="flex items-center gap-1 bg-secondary/50 rounded-lg mr-2 px-1 py-0.5 shadow-inner">
                                <button
                                    className={`w-6 h-6 rounded-full bg-secondary flex justify-center items-center hover:scale-110 transition-all duration-200 ${
                                        newChapterOrder <= 0 ? 'text-muted cursor-not-allowed opacity-50' : 'text-primary hover:bg-secondary-dark'
                                    }`}
                                    onClick={decrementNewChapterOrder}
                                    disabled={newChapterOrder <= 0}
                                >
                                    <FontAwesomeIcon icon={faMinus} size="xs"/>
                                </button>
                                <span
                                    className="bg-primary-dark text-white text-sm w-6 h-6 rounded-full text-center leading-6 mx-0.5">
                                  {newChapterOrder}
                                </span>
                                <button
                                    className="w-6 h-6 rounded-full bg-secondary flex justify-center items-center text-primary hover:bg-secondary-dark hover:scale-110 transition-all duration-200"
                                    onClick={incrementNewChapterOrder}
                                >
                                    <FontAwesomeIcon icon={faPlus} size="xs"/>
                                </button>
                            </div>
                            <input
                                className="flex-1 text-text-primary text-base px-2 py-1 bg-transparent border-b border-secondary/50 focus:outline-none focus:border-primary transition-colors duration-200 placeholder:text-muted/60"
                                value={newChapterTitle}
                                onChange={e => setNewChapterTitle(e.target.value)}
                                placeholder={t("mainChapter.newChapterPlaceholder")}
                            />
                            <button
                                className="bg-primary w-9 h-9 rounded-full flex justify-center items-center ml-2 text-text-primary shadow-md hover:shadow-lg hover:scale-110 hover:bg-primary-dark transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100"
                                onClick={addNewChapter}
                                disabled={newChapterTitle.trim() === ''}
                            >
                                <FontAwesomeIcon icon={faPlus} className={'w-5 h-5'}/>
                            </button>
                        </div>
                    </div>
                </div>
            }/>
            {
                deleteConfirmMessage &&
                <AlertBox title={t("mainChapter.deleteTitle")} message={t("mainChapter.deleteMessage")}
                          type={"danger"} onConfirm={deleteChapter}
                          onCancel={(): void => setDeleteConfirmMessage(false)}/>
            }
        </div>
    );
}