import React, {ChangeEvent, useContext, useEffect, useState} from "react";
import {SessionContext, SessionContextProps} from "@/context/SessionContext";
import {BookContext, BookContextProps} from "@/context/BookContext";
import {ChapterContext, ChapterContextProps} from "@/context/ChapterContext";
import {AlertContext, AlertContextProps} from "@/context/AlertContext";
import {AIInspire, InspirationAIIdea} from "@/lib/types/quillsense";
import {apiPost} from '@/lib/api/client';
import {htmlToText} from '@/lib/utils/html';
import InputField from "@/components/form/InputField";
import TextInput from "@/components/form/TextInput";
import {ArrowRight, Lightbulb, Link} from "lucide-react";
import {useTranslations} from '@/lib/i18n';
import {LangContext, LangContextProps} from "@/context/LangContext";
import {EditorContext, EditorContextProps} from "@/context/EditorContext";
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 InspireMe({hasKey}: { hasKey: boolean }): React.JSX.Element {
    const t = useTranslations();
    const {session}: SessionContextProps = useContext<SessionContextProps>(SessionContext);
    const {editor}: EditorContextProps = useContext<EditorContextProps>(EditorContext);
    const {book}: BookContextProps = useContext<BookContextProps>(BookContext);
    const {chapter}: ChapterContextProps = useContext<ChapterContextProps>(ChapterContext);
    const {errorMessage}: AlertContextProps = useContext<AlertContextProps>(AlertContext);
    const {lang}: LangContextProps = useContext<LangContextProps>(LangContext);
    const {setTotalCredits, setTotalPrice}: AIUsageContextProps = useContext<AIUsageContextProps>(AIUsageContext);
    const [prompt, setPrompt] = useState<string>('');

    const [hideHelp, setHideHelp] = useState<boolean>(true);
    const [loading, setLoading] = useState<boolean>(false);
    const [inspirations, setInspirations] = useState<InspirationAIIdea[]>([]);

    useEffect((): void => {
        if (prompt.trim().length > 0) {
            setHideHelp(true);
        } else {
            setHideHelp(false);
        }
    }, [prompt]);

    async function handleInspireMe(): Promise<void> {
        if (prompt.trim() === '') {
            errorMessage(t("inspireMe.emptyPromptError"));
            return;
        }
        setLoading(true);
        setInspirations([]);

        try {
            let content: string = '';
            if (editor) {
                try {
                    content = editor.getHTML();
                    content = htmlToText(content);
                } catch (e: unknown) {
                    if (e instanceof Error) {
                        errorMessage(e.message);
                    } else {
                        errorMessage(t('inspireMe.error.contentRetrievalUnknown'));
                    }
                    setLoading(false);
                    return;
                }
            }
            if (!book?.bookId) {
                errorMessage(t('inspireMe.error.noBook'));
                setLoading(false);
                return;
            }
            if (chapter?.chapterOrder === undefined) {
                errorMessage(t('inspireMe.error.noChapter'));
                setLoading(false);
                return;
            }
            const inspire: AIInspire = await apiPost<AIInspire>(
                `quillsense/inspire`,
                {
                    prompt: prompt,
                    bookId: book.bookId,
                    chapterOrder: chapter.chapterOrder,
                    currentContent: content,
                },
                session.accessToken,
                lang
            )
            if (inspire.useYourKey) {
                setTotalPrice((prevState: number): number => prevState + inspire.totalPrice)
            } else {
                setTotalCredits(inspire.totalPrice)
            }
            setInspirations(inspire.data.ideas);
        } catch (e: unknown) {
            if (e instanceof Error) {
                errorMessage(e.message);
            } else {
                errorMessage(t('inspireMe.error.unknown'));
            }
        } finally {
            setLoading(false);
        }
    }

    if (!hasKey) {
        return <LockCard title={t('inspireMe.locked.title')}
                         description={t('inspireMe.locked.description')}/>;
    }

    return (
        <div className="flex flex-col h-full overflow-hidden">
            <div className="p-5 bg-darkest-background">
                <InputField
                    input={
                        <TextInput
                            value={prompt}
                            setValue={(e: ChangeEvent<HTMLInputElement>): void => setPrompt(e.target.value)}
                            placeholder={t("inspireMe.inputPlaceholder")}
                        />
                    }
                    icon={Lightbulb}
                    fieldName={t("inspireMe.fieldName")}
                    actionLabel={t("inspireMe.actionLabel")}
                    actionIcon={Lightbulb}
                    action={async (): Promise<void> => handleInspireMe()}
                />
            </div>
            
            <div className="flex-1 overflow-y-auto p-4">
                {loading && (
                    <PulseLoader text={t("inspireMe.loading")}/>
                )}
                
                {!loading && inspirations.length > 0 && (
                    <div className="space-y-4">
                        <h3 className="text-lg font-['ADLaM_Display'] text-text-primary flex items-center gap-2">
                            <Lightbulb className="text-primary w-5 h-5" strokeWidth={1.75}/>
                            <span>{t("inspireMe.resultHeading")}</span>
                        </h3>
                        
                        <div className="space-y-4">
                            {inspirations.map((idea: InspirationAIIdea, index: number): React.JSX.Element => (
                                <div key={index}
                                     className="bg-tertiary rounded-xl hover:bg-secondary transition-colors duration-150 overflow-hidden">
                                    <div className="p-4">
                                        <h4 className="text-sm font-semibold text-primary mb-3">{idea.idea}</h4>
                                        
                                        <div className="mb-3">
                                            <div className="flex items-center mb-1.5 text-xs text-text-secondary">
                                                <ArrowRight className="mr-1.5 text-primary w-4 h-4" strokeWidth={1.75}/>
                                                <span>{t("inspireMe.justificationHeading")}</span>
                                            </div>
                                            <p className="text-text-primary text-sm pl-5">{idea.reason}</p>
                                        </div>

                                        <div>
                                            <div className="flex items-center mb-1.5 text-xs text-text-secondary">
                                                <Link className="mr-1.5 text-primary w-4 h-4" strokeWidth={1.75}/>
                                                <span>{t("inspireMe.linkHeading")}</span>
                                            </div>
                                            <div className="pl-5">
                                                <span
                                                    className="text-xs bg-secondary text-text-secondary px-2.5 py-1 rounded-lg inline-block">
                                                    {idea.relatedTo}
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                )}

                {!loading && inspirations.length === 0 && (
                    <EmptyState icon={Lightbulb} title={t("inspireMe.emptyHeading")}
                                description={t("inspireMe.emptyDescription")}/>
                )}
            </div>
        </div>
    );
}
