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 InputField from "@/components/form/InputField";
import {Languages, Search} from "lucide-react";
import TextInput from "@/components/form/TextInput";
import {LangContext, LangContextProps} from "@/context/LangContext";
import {useTranslations} from '@/lib/i18n';
import {AIVerbConjugation, ConjugationResponse, ConjugationTenses} from "@/lib/types/quillsense";
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 Conjugator({hasKey}: { hasKey: boolean }): JSX.Element {
    const {session}: SessionContextProps = useContext<SessionContextProps>(SessionContext);
    const {errorMessage}: AlertContextProps = useContext<AlertContextProps>(AlertContext);
    const {lang}: LangContextProps = useContext<LangContextProps>(LangContext);
    const t = useTranslations();
    const {setTotalCredits, setTotalPrice}: AIUsageContextProps = useContext<AIUsageContextProps>(AIUsageContext);
    const [verbToConjugate, setVerbToConjugate] = useState<string>('');
    const [inProgress, setInProgress] = useState<boolean>(false);
    const [conjugationResponse, setConjugationResponse] = useState<ConjugationResponse | null>(null);

    async function handleConjugation(): Promise<void> {
        if (verbToConjugate.trim() === '') {
            return;
        }
        setInProgress(true);
        try {
            const response: AIVerbConjugation = await apiPost<AIVerbConjugation>(
                `quillsense/verb-conjugation`,
                {verb: verbToConjugate},
                session.accessToken,
                lang
            );
            if (!response) {
                errorMessage(t("conjugator.error.noResponse"));
                return;
            }
            if (response.useYourKey) {
                setTotalPrice((prevState: number): number => prevState + response.totalPrice)
            } else {
                setTotalCredits(response.totalPrice)
            }
            setConjugationResponse(response.data);
        } catch (e: unknown) {
            if (e instanceof Error) {
                errorMessage(e.message);
            } else {
                errorMessage(t("conjugator.error.unknown"));
            }
        } finally {
            setInProgress(false);
        }
    }
    
    function renderConjugationTable(tense: string, conjugations: ConjugationTenses[string]): JSX.Element {
        if (typeof conjugations === 'string') {
            return (
                <div key={tense} className="mb-4">
                    <div className="bg-tertiary rounded-xl p-4">
                        <span className="text-text-primary">{conjugations}</span>
                    </div>
                </div>
            );
        }
        if (typeof conjugations === 'object' && conjugations !== null) {
            const hasPersonConjugations: string | undefined = conjugations.firstPersonSingular || conjugations.secondPersonSingular ||
                conjugations.thirdPersonSingular || conjugations.firstPersonPlural ||
                conjugations.secondPersonPlural || conjugations.thirdPersonPlural;
            if (hasPersonConjugations) {
                return (
                    <div key={tense} className="mb-6">
                        <h4 className="text-primary font-medium mb-3 capitalize">
                            {tense}
                        </h4>
                        <div className="bg-tertiary rounded-xl p-4">
                            <div className="grid grid-cols-2 gap-2">
                                {conjugations.firstPersonSingular && (
                                    <div className="flex">
                                        <span className="text-text-secondary w-20">{t('conjugator.persons.je')}</span>
                                        <span className="text-text-primary">{conjugations.firstPersonSingular}</span>
                                    </div>
                                )}
                                {conjugations.firstPersonPlural && (
                                    <div className="flex">
                                        <span className="text-text-secondary w-20">{t('conjugator.persons.nous')}</span>
                                        <span className="text-text-primary">{conjugations.firstPersonPlural}</span>
                                    </div>
                                )}
                                {conjugations.secondPersonSingular && (
                                    <div className="flex">
                                        <span className="text-text-secondary w-20">{t('conjugator.persons.tu')}</span>
                                        <span className="text-text-primary">{conjugations.secondPersonSingular}</span>
                                    </div>
                                )}
                                {conjugations.secondPersonPlural && (
                                    <div className="flex">
                                        <span className="text-text-secondary w-20">{t('conjugator.persons.vous')}</span>
                                        <span className="text-text-primary">{conjugations.secondPersonPlural}</span>
                                    </div>
                                )}
                                {conjugations.thirdPersonSingular && (
                                    <div className="flex">
                                        <span className="text-text-secondary w-20">{t('conjugator.persons.il')}</span>
                                        <span className="text-text-primary">{conjugations.thirdPersonSingular}</span>
                                    </div>
                                )}
                                {conjugations.thirdPersonPlural && (
                                    <div className="flex">
                                        <span className="text-text-secondary w-20">{t('conjugator.persons.ils')}</span>
                                        <span className="text-text-primary">{conjugations.thirdPersonPlural}</span>
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                );
            }
        }
        return <div key={tense}></div>;
    }
    
    function renderMode(mode: string, tenses: ConjugationTenses): JSX.Element {
        if (mode === 'infinitif' || mode === 'participe') {
            return (
                <div key={mode} className="mb-8">
                    <h3 className="text-lg font-['ADLaM_Display'] text-primary mb-4 capitalize border-b border-primary pb-2">
                        {mode}
                    </h3>
                    <div className="ml-4 space-y-4">
                        {Object.entries(tenses).map(([tense, conjugation]: [string, string | ConjugationTenses[string]]): JSX.Element => (
                            <div key={tense} className="mb-4">
                                <h4 className="text-primary font-medium mb-2 capitalize">
                                    {tense}
                                </h4>
                                <div className="bg-tertiary rounded-xl p-4">
                                    <span
                                        className="text-text-primary">{typeof conjugation === 'string' ? conjugation : ''}</span>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>
            );
        }
        return (
            <div key={mode} className="mb-8">
                <h3 className="text-xl font-semibold text-primary mb-4 capitalize border-b border-primary pb-2">
                    {mode}
                </h3>
                <div className="ml-4">
                    {Object.entries(tenses).map(([tense, conjugations]: [string, ConjugationTenses[string]]): JSX.Element =>
                        renderConjugationTable(tense, conjugations)
                    )}
                </div>
            </div>
        );
    }
    
    if (!hasKey) {
        return <LockCard title={t('conjugator.locked.title')} description={t('conjugator.locked.description')}/>;
    }
    
    return (
        <div className="flex flex-col h-full overflow-hidden">
            <div className="p-5 bg-darkest-background">
                <InputField
                    input={
                        <TextInput
                            value={verbToConjugate}
                            setValue={(e: ChangeEvent<HTMLInputElement>): void => setVerbToConjugate(e.target.value)}
                            placeholder={t('conjugator.input.placeholder')}
                        />
                    }
                    icon={Languages}
                    fieldName={t('conjugator.input.label')}
                    actionLabel={t('conjugator.input.action')}
                    actionIcon={Search}
                    action={async (): Promise<void> => handleConjugation()}
                />
            </div>
            <div className="flex-1 overflow-y-auto p-4">
                {inProgress && (
                    <PulseLoader text={t('conjugator.loading')}/>
                )}
                {!inProgress && conjugationResponse && (
                    <div className="space-y-4">
                        <h3 className="text-lg font-['ADLaM_Display'] text-text-primary flex items-center gap-2">
                            <Languages className="text-primary w-5 h-5" strokeWidth={1.75}/>
                            <span>{verbToConjugate}</span>
                        </h3>
                        <div>
                            {Object.entries(conjugationResponse.conjugations).map(([mode, tenses]: [string, ConjugationTenses]): JSX.Element =>
                                renderMode(mode, tenses)
                            )}
                        </div>
                    </div>
                )}
                {!inProgress && !conjugationResponse && (
                    <EmptyState icon={Languages} title={t('conjugator.welcome.title')}
                                description={t('conjugator.welcome.description')}/>
                )}
            </div>
        </div>
    );
}