import {AlertContext} from "@/context/AlertContext";
import {SessionContext} from "@/context/SessionContext";
import System from "@/lib/models/System";
import {ChangeEvent, JSX, useContext, useState} from "react";
import {AIDictionary, DictionaryAIResponse} from "@/lib/models/QuillSense";
import InputField from "@/components/form/InputField";
import {faLock, faMagnifyingGlass, faSpellCheck} from "@fortawesome/free-solid-svg-icons";
import TextInput from "@/components/form/TextInput";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {useTranslations} from "next-intl";
import {LangContext, LangContextProps} from "@/context/LangContext";
import {AIUsageContext, AIUsageContextProps} from "@/context/AIUsageContext";

export default function Dictionary({hasKey}: { hasKey: boolean }): JSX.Element {
    const {session} = useContext(SessionContext);
    const {errorMessage} = useContext(AlertContext);
    const t = useTranslations();
    const {lang} = useContext<LangContextProps>(LangContext)
    const {setTotalCredits,setTotalPrice} = useContext<AIUsageContextProps>(AIUsageContext)
    const [wordToCheck, setWordToCheck] = useState<string>('');
    const [inProgress, setInProgress] = useState<boolean>(false);
    const [aiResponse, setAiResponse] = useState<DictionaryAIResponse | null>(null);

    async function handleSearch(): Promise<void> {
        if (wordToCheck.trim() === '') {
            return;
        }
        setInProgress(true);
        try {
            const response: AIDictionary = await System.authPostToServer<AIDictionary>(
                `quillsense/dictionary`,
                {word: wordToCheck},
                session.accessToken,
                lang
            );
            if (!response) {
                errorMessage(t("dictionary.errorNoResponse"));
                return;
            }
            if (response.useYourKey){
                setTotalPrice((prevState:number):number => prevState + response.totalPrice)
            } else {
                setTotalCredits(response.totalPrice)
            }
            setAiResponse(response.data);
        } catch (e: unknown) {
            if (e instanceof Error) {
                errorMessage(e.message);
            } else {
                errorMessage(t("dictionary.errorUnknown"));
            }
        } finally {
            setInProgress(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 dictionnaire intelligent.
                            </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={wordToCheck}
                            setValue={(e: ChangeEvent<HTMLInputElement>) => setWordToCheck(e.target.value)}
                            placeholder={t("dictionary.searchPlaceholder")}
                        />
                    }
                    icon={faSpellCheck}
                    fieldName={t("dictionary.fieldName")}
                    actionLabel={t("dictionary.searchAction")}
                    actionIcon={faMagnifyingGlass}
                    action={async (): Promise<void> => handleSearch()}
                />
            </div>
            
            <div className="flex-1 overflow-y-auto p-4">
                {inProgress && (
                    <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("dictionary.loading")}</p>
                        </div>
                    </div>
                )}
                
                {!inProgress && aiResponse && (
                    <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={faSpellCheck} className="text-primary w-6 h-6"/>
                                <span>{wordToCheck}</span>
                            </h3>
                        </div>
                        
                        <div className="p-5 space-y-5">
                            <div className="bg-secondary/20 rounded-xl p-4 border border-secondary/30">
                                <h4 className="text-primary font-semibold mb-2 text-base">{t("dictionary.definitionHeading")}</h4>
                                <p className="text-text-primary leading-relaxed">{aiResponse.definition}</p>
                            </div>
                            
                            <div className="bg-secondary/20 rounded-xl p-4 border border-secondary/30">
                                <h4 className="text-primary font-semibold mb-2 text-base">{t("dictionary.exampleHeading")}</h4>
                                <p className="text-text-primary italic leading-relaxed">{aiResponse.example}</p>
                            </div>
                            
                            <div className="bg-secondary/20 rounded-xl p-4 border border-secondary/30">
                                <h4 className="text-primary font-semibold mb-2 text-base">{t("dictionary.literaryUsageHeading")}</h4>
                                <p className="text-text-primary leading-relaxed">{aiResponse.literaryUsage}</p>
                            </div>
                        </div>
                    </div>
                )}
                
                {!inProgress && !aiResponse && (
                    <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={faSpellCheck} className="text-primary w-10 h-10"/>
                        </div>
                        <h3 className="text-xl font-['ADLaM_Display'] text-text-primary mb-3">{t("dictionary.fieldName")}</h3>
                        <p className="text-muted max-w-md text-lg leading-relaxed">
                            {t("dictionary.description")}
                        </p>
                    </div>
                )}
            </div>
        </div>
    );
}