import React, {JSX, useContext, useState} from "react";
import {SessionContext, SessionContextProps} from "@/context/SessionContext";
import {AlertContext, AlertContextProps} from "@/context/AlertContext";
import {AISynonyms, SynonymAI, SynonymsAIResponse} from "@/lib/types/quillsense";
import {apiPost} from '@/lib/api/client';
import {ArrowLeftRight, Search} from "lucide-react";
import {useTranslations} from '@/lib/i18n';
import {LangContext, LangContextProps} from "@/context/LangContext";
import SearchInputWithSelect from "@/components/form/SearchInputWithSelect";
import {AIUsageContext, AIUsageContextProps} from "@/context/AIUsageContext";
import EmptyState from "@/components/ui/EmptyState";
import PulseLoader from "@/components/ui/PulseLoader";
import LockCard from "@/components/ui/LockCard";

export default function Synonyms({hasKey}: { hasKey: boolean }): JSX.Element {
    const t = useTranslations();
    const {session}: SessionContextProps = useContext<SessionContextProps>(SessionContext);
    const {lang}: LangContextProps = useContext<LangContextProps>(LangContext);
    const {errorMessage}: AlertContextProps = useContext<AlertContextProps>(AlertContext);
    const {setTotalCredits, setTotalPrice}: AIUsageContextProps = 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 apiPost<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 <LockCard title={t('synonyms.locked.title')}
                         description={t('synonyms.locked.description')}/>;
    }

    return (
        <div className="flex flex-col h-full overflow-hidden">
            <div className="p-5 bg-darkest-background">
                <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={Search}
                            onSearch={handleSearch}
                            onKeyDown={(e: React.KeyboardEvent<HTMLInputElement>): void => {
                                if (e.key === 'Enter') {
                                    handleSearch();
                                }
                            }}
                        />
                </div>
            </div>
            
            <div className="flex-1 overflow-y-auto p-4">
                {inProgress && (
                    <PulseLoader text={t("synonyms.loading")}/>
                )}
                
                {!inProgress && aiResponse && aiResponse.words.length > 0 && (
                    <div className="space-y-4">
                        <h3 className="text-lg font-['ADLaM_Display'] text-text-primary flex items-center gap-2">
                            <ArrowLeftRight className="text-primary w-5 h-5" strokeWidth={1.75}/>
                            <span>
                                {type === 'synonymes'
                                    ? t("synonyms.resultSynonyms", {word: wordToCheck})
                                    : t("synonyms.resultAntonyms", {word: wordToCheck})}
                            </span>
                        </h3>
                        
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                            {aiResponse.words.map((item: SynonymAI, index: number): React.JSX.Element => (
                                <div key={index}
                                     className="bg-tertiary rounded-xl p-4 hover:bg-secondary transition-colors duration-150">
                                    <div className="font-semibold text-primary text-sm mb-1.5">{item.word}</div>
                                    <div className="text-xs text-muted leading-relaxed">{item.context}</div>
                                </div>
                            ))}
                        </div>
                    </div>
                )}

                {!inProgress && (!aiResponse || aiResponse.words.length === 0) && (
                    <EmptyState
                        icon={ArrowLeftRight}
                        title={type === 'synonymes' ? t("synonyms.emptySynonymsTitle") : t("synonyms.emptyAntonymsTitle")}
                        description={type === 'synonymes' ? t("synonyms.emptySynonymsDescription") : t("synonyms.emptyAntonymsDescription")}
                    />
                )}
            </div>
        </div>
    );
}
