import {AlertContext, AlertContextProps} from "@/context/AlertContext";
import {SessionContext, SessionContextProps} from "@/context/SessionContext";
import {apiPost} from '@/lib/api/client';
import {ChangeEvent, JSX, useContext, useState} from "react";
import {AIDictionary, DictionaryAIResponse} from "@/lib/types/quillsense";
import InputField from "@/components/form/InputField";
import {Search, SpellCheck} from "lucide-react";
import TextInput from "@/components/form/TextInput";
import {useTranslations} from '@/lib/i18n';
import {LangContext, LangContextProps} from "@/context/LangContext";
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 Dictionary({hasKey}: { hasKey: boolean }): JSX.Element {
    const {session}: SessionContextProps = useContext<SessionContextProps>(SessionContext);
    const {errorMessage}: AlertContextProps = useContext<AlertContextProps>(AlertContext);
    const t = useTranslations();
    const {lang}: LangContextProps = useContext<LangContextProps>(LangContext)
    const {setTotalCredits, setTotalPrice}: AIUsageContextProps = 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 apiPost<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 <LockCard title={t('dictionary.locked.title')}
                         description={t('dictionary.locked.description')}/>;
    }

    return (
        <div className="flex flex-col h-full overflow-hidden">
            <div className="p-5 bg-darkest-background">
                <InputField
                    input={
                        <TextInput
                            value={wordToCheck}
                            setValue={(e: ChangeEvent<HTMLInputElement>): void => setWordToCheck(e.target.value)}
                            placeholder={t("dictionary.searchPlaceholder")}
                        />
                    }
                    icon={SpellCheck}
                    fieldName={t("dictionary.fieldName")}
                    actionLabel={t("dictionary.searchAction")}
                    actionIcon={Search}
                    action={async (): Promise<void> => handleSearch()}
                />
            </div>

            <div className="flex-1 overflow-y-auto p-4">
                {inProgress && (
                    <PulseLoader text={t("dictionary.loading")}/>
                )}
                
                {!inProgress && aiResponse && (
                    <div className="space-y-4">
                        <h3 className="text-lg font-['ADLaM_Display'] text-text-primary flex items-center gap-2">
                            <SpellCheck className="text-primary w-5 h-5" strokeWidth={1.75}/>
                            <span>{wordToCheck}</span>
                        </h3>
                        
                        <div className="bg-tertiary rounded-xl p-4">
                            <h4 className="text-primary font-semibold mb-2 text-sm">{t("dictionary.definitionHeading")}</h4>
                            <p className="text-text-primary text-sm leading-relaxed">{aiResponse.definition}</p>
                        </div>
                        
                        <div className="bg-tertiary rounded-xl p-4">
                            <h4 className="text-primary font-semibold mb-2 text-sm">{t("dictionary.exampleHeading")}</h4>
                            <p className="text-text-primary text-sm italic leading-relaxed">{aiResponse.example}</p>
                        </div>
                        
                        <div className="bg-tertiary rounded-xl p-4">
                            <h4 className="text-primary font-semibold mb-2 text-sm">{t("dictionary.literaryUsageHeading")}</h4>
                            <p className="text-text-primary text-sm leading-relaxed">{aiResponse.literaryUsage}</p>
                        </div>
                    </div>
                )}

                {!inProgress && !aiResponse && (
                    <EmptyState icon={SpellCheck} title={t("dictionary.fieldName")}
                                description={t("dictionary.description")}/>
                )}
            </div>
        </div>
    );
}
