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

interface ConjugationTenses {
    [tense: string]: {
        firstPersonSingular?: string;
        secondPersonSingular?: string;
        thirdPersonSingular?: string;
        firstPersonPlural?: string;
        secondPersonPlural?: string;
        thirdPersonPlural?: string;
        présent?: string;
        passé?: string;
    } | string;
}

interface ConjugationResponse {
    conjugations: {
        [mode: string]: ConjugationTenses;
    };
}

export default function Conjugator({hasKey}: { hasKey: boolean }): JSX.Element {
    const {session} = useContext(SessionContext);
    const {errorMessage} = useContext(AlertContext);
    const {lang} = useContext<LangContextProps>(LangContext);
    const t = useTranslations();
    const {setTotalCredits, setTotalPrice} = 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 System.authPostToServer<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 as ConjugationResponse);
        } 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-secondary/20 rounded-xl p-4 border border-secondary/30">
                        <span className="text-text-primary">{conjugations}</span>
                    </div>
                </div>
            );
        }
        if (typeof conjugations === 'object' && conjugations !== null) {
            const hasPersonConjugations = 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-secondary/20 rounded-xl p-4 border border-secondary/30">
                            <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/20 pb-2">
                        {mode}
                    </h3>
                    <div className="ml-4 space-y-4">
                        {Object.entries(tenses).map(([tense, conjugation]: [string, string | ConjugationTenses[string]]) => (
                            <div key={tense} className="mb-4">
                                <h4 className="text-primary font-medium mb-2 capitalize">
                                    {tense}
                                </h4>
                                <div className="bg-secondary/20 rounded-xl p-4 border border-secondary/30">
                                    <span className="text-text-primary">{conjugation as string}</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/20 pb-2">
                    {mode}
                </h3>
                <div className="ml-4">
                    {Object.entries(tenses).map(([tense, conjugations]) =>
                        renderConjugationTable(tense, conjugations)
                    )}
                </div>
            </div>
        );
    }
    
    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">
                                {t('conjugator.locked.title')}
                            </h3>
                            <p className="text-muted leading-relaxed text-lg">
                                {t('conjugator.locked.description')}
                            </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={verbToConjugate}
                            setValue={(e: ChangeEvent<HTMLInputElement>) => setVerbToConjugate(e.target.value)}
                            placeholder={t('conjugator.input.placeholder')}
                        />
                    }
                    icon={faLanguage}
                    fieldName={t('conjugator.input.label')}
                    actionLabel={t('conjugator.input.action')}
                    actionIcon={faMagnifyingGlass}
                    action={async (): Promise<void> => handleConjugation()}
                />
            </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('conjugator.loading')}</p>
                        </div>
                    </div>
                )}
                {!inProgress && conjugationResponse && (
                    <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={faLanguage} className="text-primary w-6 h-6"/>
                                <span>{verbToConjugate}</span>
                            </h3>
                        </div>
                        <div className="p-5">
                            {Object.entries(conjugationResponse.conjugations).map(([mode, tenses]: [string, ConjugationTenses]) =>
                                renderMode(mode, tenses)
                            )}
                        </div>
                    </div>
                )}
                {!inProgress && !conjugationResponse && (
                    <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={faLanguage} className="text-primary w-10 h-10"/>
                        </div>
                        <h3 className="text-xl font-['ADLaM_Display'] text-text-primary mb-3">{t('conjugator.welcome.title')}</h3>
                        <p className="text-muted max-w-md text-lg leading-relaxed">
                            {t('conjugator.welcome.description')}
                        </p>
                    </div>
                )}
            </div>
        </div>
    );
}