import {JSX, useContext, useState} from "react";
import {SessionContext} from "@/context/SessionContext";
import {AlertContext} from "@/context/AlertContext";
import {AISynonyms, SynonymAI, SynonymsAIResponse} from "@/lib/models/QuillSense";
import System from "@/lib/models/System";
import {faExchangeAlt, faLock, faSearch} from "@fortawesome/free-solid-svg-icons";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {useTranslations} from "next-intl";
import {LangContext, LangContextProps} from "@/context/LangContext";
import SearchInputWithSelect from "@/components/form/SearchInputWithSelect";
import {AIUsageContext, AIUsageContextProps} from "@/context/AIUsageContext";

export default function Synonyms({hasKey}: { hasKey: boolean }): JSX.Element {
    const t = useTranslations();
    const {session} = useContext(SessionContext);
    const {lang} = useContext<LangContextProps>(LangContext);
    const {errorMessage} = useContext(AlertContext);
    const {setTotalCredits, setTotalPrice} = useContext<AIUsageContextProps>(AIUsageContext);
    const [type, setType] = useState<string>('synonymes')
    const [wordToCheck, setWordToCheck] = useState<string>('')
    const [inProgress, setInProgress] = useState<boolean>(false);
    const [aiResponse, setAiResponse] = useState<SynonymsAIResponse | null>(null)
    
    async function handleSearch(): Promise<void> {
        if (wordToCheck.trim() === '') {
            errorMessage(t("synonyms.enterWordError"));
            return;
        }
        setInProgress(true);
        try {
            const response: AISynonyms = await System.authPostToServer<AISynonyms>(`quillsense/synonyms`, {
                word: wordToCheck,
                type: type
            }, session.accessToken, lang);
            if (!response) {
                errorMessage(t("synonyms.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("synonyms.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">
                <div className="mb-3">
                    <div className="flex items-center gap-3 mb-4">
                        <div className="w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center shadow-sm">
                            <FontAwesomeIcon icon={faExchangeAlt} className="text-primary w-6 h-6"/>
                        </div>
                        <div>
                            <h3 className="text-xl font-['ADLaM_Display'] text-text-primary">{t("synonyms.heading")}</h3>
                            <p className="text-sm text-muted">{t("synonyms.subheading")}</p>
                        </div>
                    </div>
                    
                    <div className="mb-3">
                        <SearchInputWithSelect
                            selectValue={type}
                            setSelectValue={setType}
                            selectOptions={[
                                {value: "synonymes", label: t("synonyms.optionSynonyms")},
                                {value: "antonymes", label: t("synonyms.optionAntonyms")}
                            ]}
                            inputValue={wordToCheck}
                            setInputValue={setWordToCheck}
                            inputPlaceholder={t("synonyms.inputPlaceholder")}
                            searchIcon={faSearch}
                            onSearch={handleSearch}
                            onKeyDown={(e: React.KeyboardEvent<HTMLInputElement>) => {
                                if (e.key === 'Enter') {
                                    handleSearch();
                                }
                            }}
                        />
                    </div>
                </div>
            </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("synonyms.loading")}</p>
                        </div>
                    </div>
                )}
                
                {!inProgress && aiResponse && aiResponse.words.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={faExchangeAlt} className="text-primary w-6 h-6"/>
                                <span>
                                    {type === 'synonymes'
                                        ? t("synonyms.resultSynonyms", {word: wordToCheck})
                                        : t("synonyms.resultAntonyms", {word: wordToCheck})}
                                </span>
                            </h3>
                        </div>
                        
                        <div className="p-5">
                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                                {aiResponse.words.map((item: SynonymAI, index: number) => (
                                    <div key={index}
                                         className="bg-secondary/20 rounded-xl p-4 border border-secondary/30 hover:border-primary/50 hover:shadow-md hover:scale-102 transition-all duration-200">
                                        <div className="font-semibold text-primary mb-1.5">{item.word}</div>
                                        <div className="text-sm text-muted leading-relaxed">{item.context}</div>
                                    </div>
                                ))}
                            </div>
                        </div>
                    </div>
                )}
                
                {!inProgress && (!aiResponse || aiResponse.words.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={faExchangeAlt} className="w-10 h-10 text-primary"/>
                        </div>
                        <h3 className="text-xl font-['ADLaM_Display'] text-text-primary mb-3">
                            {type === 'synonymes' ? t("synonyms.emptySynonymsTitle") : t("synonyms.emptyAntonymsTitle")}
                        </h3>
                        <p className="text-muted max-w-md text-lg leading-relaxed">
                            {type === 'synonymes'
                                ? t("synonyms.emptySynonymsDescription")
                                : t("synonyms.emptyAntonymsDescription")}
                        </p>
                    </div>
                )}
            </div>
        </div>
    );
}