'use client'
import React, {ChangeEvent, forwardRef, useContext, useEffect, useImperativeHandle, useState} from "react";
import {BookContext} from "@/context/BookContext";
import {SessionContext} from "@/context/SessionContext";
import {AlertContext} from "@/context/AlertContext";
import {LangContext} from "@/context/LangContext";
import System from "@/lib/models/System";
import {QuillSenseSettingsProps} from "@/lib/models/QuillSenseSettings";
import {useTranslations} from "next-intl";
import ToggleSwitch from "@/components/form/ToggleSwitch";
import TexteAreaInput from "@/components/form/TexteAreaInput";
import InputField from "@/components/form/InputField";
import {faMagicWandSparkles, faToggleOn} from "@fortawesome/free-solid-svg-icons";

const QuillSenseSetting = forwardRef(function QuillSenseSetting(props, ref) {
    const t = useTranslations();
    const {book, setBook} = useContext(BookContext);
    const {session} = useContext(SessionContext);
    const {errorMessage, successMessage} = useContext(AlertContext);
    const {lang} = useContext(LangContext);

    const [quillsenseEnabled, setQuillsenseEnabled] = useState<boolean>(true);
    const [advancedPrompt, setAdvancedPrompt] = useState<string>('');
    const [isLoading, setIsLoading] = useState<boolean>(true);

    useImperativeHandle(ref, () => ({
        handleSave
    }));

    useEffect((): void => {
        if (book?.bookId) {
            fetchQuillSenseSettings();
        }
    }, [book?.bookId]);

    async function fetchQuillSenseSettings(): Promise<void> {
        try {
            setIsLoading(true);
            const settings: QuillSenseSettingsProps = await System.authGetQueryToServer<QuillSenseSettingsProps>(
                'book/quillsense-settings',
                session.accessToken,
                lang,
                {bookId: book?.bookId}
            );
            setQuillsenseEnabled(settings.quillsenseEnabled);
            setAdvancedPrompt(settings.advancedPrompt ?? '');
        } catch (e: unknown) {
            if (e instanceof Error) {
                errorMessage(e.message);
            }
        } finally {
            setIsLoading(false);
        }
    }

    async function handleSave(): Promise<void> {
        try {
            const updateResult: boolean = await System.authPutToServer<boolean>(
                'book/quillsense-settings',
                {
                    bookId: book?.bookId,
                    quillsenseEnabled: quillsenseEnabled,
                    advancedPrompt: advancedPrompt
                },
                session.accessToken,
                lang
            );
            if (updateResult) {
                successMessage(t('quillSenseSetting.successSave'));
                // Mettre a jour le contexte du livre
                if (setBook && book) {
                    setBook({...book, quillsenseEnabled: quillsenseEnabled});
                }
            } else {
                errorMessage(t('quillSenseSetting.errorSave'));
            }
        } catch (e: unknown) {
            if (e instanceof Error) {
                errorMessage(e.message);
            }
        }
    }

    if (isLoading) {
        return (
            <div className="flex items-center justify-center p-8">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
            </div>
        );
    }

    return (
        <div className="space-y-6 p-4">
            <div className="bg-secondary/20 rounded-xl p-5 shadow-inner border border-secondary/30">
                <InputField
                    icon={faToggleOn}
                    fieldName={t('quillSenseSetting.enableLabel')}
                    input={
                        <ToggleSwitch
                            checked={quillsenseEnabled}
                            onChange={(checked: boolean): void => setQuillsenseEnabled(checked)}
                        />
                    }
                />
                <p className="text-muted text-sm mt-2">
                    {t('quillSenseSetting.enableDescription')}
                </p>
            </div>

            <div className="bg-secondary/20 rounded-xl p-5 shadow-inner border border-secondary/30">
                <InputField
                    icon={faMagicWandSparkles}
                    fieldName={t('quillSenseSetting.advancedPromptLabel')}
                    input={
                        <TexteAreaInput
                            value={advancedPrompt}
                            setValue={(e: ChangeEvent<HTMLTextAreaElement>): void => setAdvancedPrompt(e.target.value)}
                            placeholder={t('quillSenseSetting.advancedPromptPlaceholder')}
                        />
                    }
                />
                <p className="text-muted text-sm mt-2">
                    {t('quillSenseSetting.advancedPromptHint')}
                </p>
            </div>
        </div>
    );
});

export default QuillSenseSetting;
