import {ChangeEvent, useContext, useEffect, useState} from "react";
import {SessionContext} from "@/context/SessionContext";
import {BookContext} from "@/context/BookContext";
import {ChapterContext} from "@/context/ChapterContext";
import {AlertContext} from "@/context/AlertContext";
import {AIInspire, InspirationAIIdea} from "@/lib/models/QuillSense";
import System from "@/lib/models/System";
import InputField from "@/components/form/InputField";
import TextInput from "@/components/form/TextInput";
import {faArrowRight, faLightbulb, faLink, faLock} from "@fortawesome/free-solid-svg-icons";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {useTranslations} from "next-intl";
import {LangContext, LangContextProps} from "@/context/LangContext";
import {EditorContext} from "@/context/EditorContext";
import {AIUsageContext, AIUsageContextProps} from "@/context/AIUsageContext";

export default function InspireMe({hasKey}: { hasKey: boolean }) {
    const t = useTranslations();
    const {session} = useContext(SessionContext);
    const {editor} = useContext(EditorContext);
    const {book} = useContext(BookContext);
    const {chapter} = useContext(ChapterContext);
    const {errorMessage} = useContext(AlertContext);
    const {lang} = useContext<LangContextProps>(LangContext);
    const {setTotalCredits, setTotalPrice} = useContext<AIUsageContextProps>(AIUsageContext);
    const [prompt, setPrompt] = useState<string>('');
    
    const [hideHelp, setHideHelp] = useState<boolean>(true);
    const [loading, setLoading] = useState<boolean>(false);
    const [inspirations, setInspirations] = useState<InspirationAIIdea[]>([]);
    
    useEffect((): void => {
        if (prompt.trim().length > 0) {
            setHideHelp(true);
        } else {
            setHideHelp(false);
        }
    }, [prompt]);
    
    async function handleInspireMe(): Promise<void> {
        if (prompt.trim() === '') {
            errorMessage(t("inspireMe.emptyPromptError"));
            return;
        }
        setLoading(true);
        setInspirations([]);
        
        try {
            let content: string = '';
            if (editor) {
                try {
                    content = editor.getHTML();
                    content = System.htmlToText(content);
                } catch (e: unknown) {
                    if (e instanceof Error) {
                        errorMessage('Erreur lors de la récupération du contenu.');
                        console.error('Erreur lors de la récupération du contenu.');
                    } else {
                        errorMessage('Erreur inconnue lors de la récupération du contenu.')
                        console.error('Erreur inconnue lors de la récupération du contenu.');
                    }
                    setLoading(false);
                    return;
                }
            }
            if (!book?.bookId) {
                errorMessage('Aucun livre sélectionné.');
                setLoading(false);
                return;
            }
            if (chapter?.chapterOrder === undefined) {
                errorMessage('Aucun chapitre sélectionné.');
                setLoading(false);
                return;
            }
            const inspire: AIInspire = await System.authPostToServer<AIInspire>(
                `quillsense/inspire`,
                {
                    prompt: prompt,
                    bookId: book.bookId,
                    chapterOrder: chapter.chapterOrder,
                    currentContent: content,
                },
                session.accessToken,
                lang
            )
            if (inspire.useYourKey) {
                setTotalPrice((prevState: number): number => prevState + inspire.totalPrice)
            } else {
                setTotalCredits(inspire.totalPrice)
            }
            setInspirations(inspire.data.ideas);
        } catch (e: unknown) {
            if (e instanceof Error) {
                errorMessage(e.message);
            } else {
                errorMessage(`Une erreur inconnue est survenue lors de la génération.`);
            }
        } finally {
            setLoading(false);
        }
    }
    
    if (!hasKey) {
        return (
            <div className="flex flex-col h-full bg-secondary/20 backdrop-blur-sm">
                <div className="flex-1 p-6 overflow-y-auto flex items-center justify-center">
                    <div className="max-w-md mx-auto">
                        <div
                            className="bg-tertiary/90 backdrop-blur-sm border border-secondary/50 rounded-2xl p-8 text-center shadow-2xl">
                            <div
                                className="w-20 h-20 mx-auto mb-6 bg-primary rounded-2xl flex items-center justify-center shadow-lg">
                                <FontAwesomeIcon icon={faLock} className="w-10 h-10 text-text-primary"/>
                            </div>
                            
                            <h3 className="text-xl font-['ADLaM_Display'] text-text-primary mb-4">
                                Accès requis
                            </h3>
                            
                            <p className="text-muted leading-relaxed text-lg">
                                Un abonnement de niveau de base de QuillSense ou une clé API OpenAI est requis pour
                                activer le mode "Inspire-moi".
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
    
    return (
        <div className="flex flex-col h-full bg-secondary/20 backdrop-blur-sm overflow-hidden">
            <div className="p-5 border-b border-secondary/50 bg-secondary/30 shadow-sm">
                <InputField
                    input={
                        <TextInput
                            value={prompt}
                            setValue={(e: ChangeEvent<HTMLInputElement>) => setPrompt(e.target.value)}
                            placeholder={t("inspireMe.inputPlaceholder")}
                        />
                    }
                    icon={faLightbulb}
                    fieldName={t("inspireMe.fieldName")}
                    actionLabel={t("inspireMe.actionLabel")}
                    actionIcon={faLightbulb}
                    action={async () => handleInspireMe()}
                />
            </div>
            
            <div className="flex-1 overflow-y-auto p-4">
                {loading && (
                    <div className="flex items-center justify-center h-32">
                        <div className="animate-pulse flex flex-col items-center">
                            <div
                                className="w-12 h-12 border-4 border-primary border-t-transparent rounded-full animate-spin mb-3"></div>
                            <p className="text-text-secondary">{t("inspireMe.loading")}</p>
                        </div>
                    </div>
                )}
                
                {!loading && inspirations.length > 0 && (
                    <div
                        className="rounded-xl bg-tertiary/90 backdrop-blur-sm shadow-lg overflow-hidden border border-secondary/50">
                        <div className="bg-primary/10 p-4 border-b border-secondary/30">
                            <h3 className="text-xl font-['ADLaM_Display'] text-text-primary flex items-center gap-2">
                                <FontAwesomeIcon icon={faLightbulb} className="text-primary w-6 h-6"/>
                                <span>{t("inspireMe.resultHeading")}</span>
                            </h3>
                        </div>
                        
                        <div className="p-5 space-y-6">
                            {inspirations.map((idea, index) => (
                                <div key={index}
                                     className="bg-secondary/20 rounded-xl shadow-md border border-secondary/30 hover:border-primary/50 hover:shadow-lg hover:scale-102 transition-all duration-200 overflow-hidden">
                                    <div className="p-4 bg-primary/10 border-b border-secondary/30">
                                        <h4 className="text-lg font-semibold text-primary">{idea.idea}</h4>
                                    </div>
                                    
                                    <div className="p-4">
                                        <div className="mb-4">
                                            <div className="flex items-center mb-1.5 text-sm text-text-secondary">
                                                <FontAwesomeIcon icon={faArrowRight}
                                                                 className="mr-1.5 text-primary w-5 h-5"/>
                                                <span>{t("inspireMe.justificationHeading")}</span>
                                            </div>
                                            <p className="text-text-primary pl-5">{idea.reason}</p>
                                        </div>
                                        
                                        <div>
                                            <div className="flex items-center mb-1.5 text-sm text-text-secondary">
                                                <FontAwesomeIcon icon={faLink} className="mr-1.5 text-primary w-5 h-5"/>
                                                <span>{t("inspireMe.linkHeading")}</span>
                                            </div>
                                            <div className="pl-5">
                                                <span
                                                    className="text-xs bg-secondary/50 text-text-secondary px-2.5 py-1 rounded-lg inline-block border border-secondary/50">
                                                    {idea.relatedTo}
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                )}
                
                {!loading && inspirations.length === 0 && (
                    <div className="h-full flex flex-col items-center justify-center text-center p-8">
                        <div
                            className="w-20 h-20 rounded-2xl bg-primary/10 flex items-center justify-center mb-6 shadow-md">
                            <FontAwesomeIcon icon={faLightbulb} className="text-primary w-10 h-10"/>
                        </div>
                        <h3 className="text-xl font-['ADLaM_Display'] text-text-primary mb-3">{t("inspireMe.emptyHeading")}</h3>
                        <p className="text-muted max-w-md text-lg leading-relaxed">
                            {t("inspireMe.emptyDescription")}
                        </p>
                    </div>
                )}
            </div>
        </div>
    );
}