'use client'
import {ChangeEvent, forwardRef, useContext, useEffect, useImperativeHandle, useState} from "react";
import System from "@/lib/models/System";
import {AlertContext} from "@/context/AlertContext";
import {SessionContext} from "@/context/SessionContext";
import TextInput from "@/components/form/TextInput";
import TexteAreaInput from "@/components/form/TexteAreaInput";
import InputField from "@/components/form/InputField";
import {useTranslations} from "next-intl";
import {LangContext, LangContextProps} from "@/context/LangContext";
import {SeriesContext, SeriesContextProps} from "@/context/SeriesContext";
import {SeriesDetailResponse, SeriesUpdateResponse} from "@/lib/models/Series";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faSpinner} from "@fortawesome/free-solid-svg-icons";
import OfflineContext, {OfflineContextType} from "@/context/OfflineContext";
import {LocalSyncQueueContext, LocalSyncQueueContextProps} from "@/context/SyncQueueContext";
import {SeriesSyncContext, SeriesSyncContextProps} from "@/context/SeriesSyncContext";
import {SyncedSeries} from "@/lib/models/SyncedSeries";

function BasicSeriesInformation(props: object, ref: React.Ref<{ handleSave: () => Promise<void> }>) {
    const t = useTranslations();
    const {lang} = useContext<LangContextProps>(LangContext);

    const {session} = useContext(SessionContext);
    const {seriesId, localSeries} = useContext<SeriesContextProps>(SeriesContext);
    const userToken: string = session?.accessToken ? session?.accessToken : '';
    const {errorMessage, successMessage} = useContext(AlertContext);
    const {isCurrentlyOffline} = useContext<OfflineContextType>(OfflineContext);
    const {addToQueue} = useContext<LocalSyncQueueContextProps>(LocalSyncQueueContext);
    const {localSyncedSeries} = useContext<SeriesSyncContextProps>(SeriesSyncContext);

    const [isLoading, setIsLoading] = useState<boolean>(true);
    const [name, setName] = useState<string>('');
    const [description, setDescription] = useState<string>('');

    useEffect(function () {
        if (seriesId) {
            loadSeriesData();
        }
    }, [seriesId]);

    async function loadSeriesData(): Promise<void> {
        setIsLoading(true);
        try {
            let response: SeriesDetailResponse;

            if (isCurrentlyOffline() || localSeries) {
                response = await window.electron.invoke<SeriesDetailResponse>('db:series:detail', {seriesId});
            } else {
                response = await System.authGetQueryToServer<SeriesDetailResponse>(
                    'series/detail',
                    userToken,
                    lang,
                    {seriesid: seriesId}
                );
            }

            if (response) {
                setName(response.name);
                setDescription(response.description || '');
            }
        } catch (e: unknown) {
            if (e instanceof Error) {
                errorMessage(e.message);
            } else {
                errorMessage(t('seriesBasicInformation.error.unknown'));
            }
        } finally {
            setIsLoading(false);
        }
    }

    useImperativeHandle(ref, function () {
        return {
            handleSave: handleSave
        };
    });

    async function handleSave(): Promise<void> {
        if (!name) {
            errorMessage(t('seriesBasicInformation.error.nameRequired'));
            return;
        }
        try {
            const updateData = {
                seriesId: seriesId,
                name: name,
                description: description
            };
            let success: boolean;

            if (isCurrentlyOffline() || localSeries) {
                success = await window.electron.invoke<boolean>('db:series:update', updateData);
            } else {
                const response: SeriesUpdateResponse = await System.authPutToServer<SeriesUpdateResponse>(
                    'series/update',
                    updateData,
                    userToken,
                    lang
                );
                success = response.success;

                if (localSyncedSeries.find((s: SyncedSeries): boolean => s.id === seriesId)) {
                    addToQueue('db:series:update', updateData);
                }
            }

            if (!success) {
                errorMessage(t('seriesBasicInformation.error.update'));
                return;
            }
            successMessage(t('seriesBasicInformation.success.update'));
        } catch (e: unknown) {
            if (e instanceof Error) {
                errorMessage(e.message);
            } else {
                errorMessage(t('seriesBasicInformation.error.unknown'));
            }
        }
    }

    if (isLoading) {
        return (
            <div className="flex items-center justify-center py-12">
                <FontAwesomeIcon icon={faSpinner} className="w-8 h-8 text-primary animate-spin"/>
            </div>
        );
    }

    return (
        <div className="space-y-6">
            <div className="bg-tertiary/90 backdrop-blur-sm rounded-xl p-5 border border-secondary/50 shadow-md">
                <InputField fieldName={t('seriesBasicInformation.fields.name')} input={<TextInput
                    value={name}
                    setValue={(e: ChangeEvent<HTMLInputElement>) => setName(e.target.value)}
                    placeholder={t('seriesBasicInformation.fields.namePlaceholder')}
                />}/>
            </div>

            <div className="bg-tertiary/90 backdrop-blur-sm rounded-xl p-5 border border-secondary/50 shadow-md">
                <InputField fieldName={t('seriesBasicInformation.fields.description')} input={<TexteAreaInput
                    value={description}
                    setValue={(e: ChangeEvent<HTMLTextAreaElement>) => setDescription(e.target.value)}
                    placeholder={t('seriesBasicInformation.fields.descriptionPlaceholder')}
                />}/>
            </div>
        </div>
    );
}

export default forwardRef(BasicSeriesInformation);
