import InputField from "@/components/form/InputField";
import TexteAreaInput from "@/components/form/TexteAreaInput";
import {ChangeEvent, Dispatch, SetStateAction, useContext, useEffect} from "react";
import {faGuilded} from "@fortawesome/free-brands-svg-icons";
import {AlertContext} from "@/context/AlertContext";
import System from "@/lib/models/System";
import {SessionContext} from "@/context/SessionContext";
import {BookContext} from "@/context/BookContext";
import {LangContext, LangContextProps} from "@/context/LangContext";
import {useTranslations} from "next-intl";

interface GhostWriterSettingsProps {
    advancedPrompt: string;
    setAdvancedPrompt: Dispatch<SetStateAction<string>>;
}

export default function GhostWriterSettings(
    {
        advancedPrompt,
        setAdvancedPrompt
    }: GhostWriterSettingsProps) {
    const {errorMessage} = useContext(AlertContext);
    const {session} = useContext(SessionContext);
    const t = useTranslations();
    const {lang} = useContext<LangContextProps>(LangContext)
    const {book} = useContext(BookContext);
    
    useEffect((): void => {
        getAdvancedSettings().catch();
    }, []);
    
    async function getAdvancedSettings(): Promise<void> {
        try {
            const setting: string = await System.authGetQueryToServer<string>(`quillsense/ghostwriter/advanced-settings`, session.accessToken, lang, {
                bookId: book?.bookId
            });
            if (setting) {
                setAdvancedPrompt(setting);
            }
        } catch (e: unknown) {
            if (e instanceof Error) {
                errorMessage(e.message);
            } else {
                errorMessage(t('ghostwriter.settings.unknownError'));
            }
        }
    }
    
    return (
        <div className={`p-4 lg:p-5 space-y-5 overflow-y-auto flex-grow custom-scrollbar`}>
            <InputField input={<TexteAreaInput value={advancedPrompt}
                                               setValue={(e: ChangeEvent<HTMLTextAreaElement>): void => setAdvancedPrompt(e.target.value)}
                                               placeholder={`Information complémentaire pour la génération...`}
                                               maxLength={600}/>}
                        fieldName={`Prompt additionnel`} icon={faGuilded}/>
        </div>
    );
}