'use client'
import {ChangeEvent, forwardRef, useContext, useEffect, useImperativeHandle, useState} from "react";
import OfflineContext, {OfflineContextType} from '@/context/OfflineContext';
import {isDesktop} from '@/lib/configs';
import {apiGet, apiPut} from '@/lib/api/client';
import {getSeriesDetail, updateSeries} from '@/lib/tauri';
import {AlertContext, AlertContextProps} from "@/context/AlertContext";
import {SessionContext, SessionContextProps} from "@/context/SessionContext";
import TextInput from "@/components/form/TextInput";
import TextAreaInput from "@/components/form/TextAreaInput";
import InputField from "@/components/form/InputField";
import {useTranslations} from '@/lib/i18n';
import {LangContext, LangContextProps} from "@/context/LangContext";
import {SeriesContext, SeriesContextProps} from "@/context/SeriesContext";
import {SeriesDetailResponse, SeriesUpdateResponse} from "@/lib/types/series";
import PulseLoader from '@/components/ui/PulseLoader';
import {SeriesSyncContext, SeriesSyncContextProps} from '@/context/SeriesSyncContext';
import {SyncedSeries} from '@/lib/types/synced-series';
import {LocalSyncQueueContext, LocalSyncQueueContextProps} from '@/context/SyncQueueContext';

function BasicSeriesInformation(props: object, ref: React.Ref<{ handleSave: () => Promise<void> }>) {
    const t = useTranslations();
    const {lang}: LangContextProps = useContext<LangContextProps>(LangContext);
    
    const {session}: SessionContextProps = useContext<SessionContextProps>(SessionContext);
    const {seriesId}: SeriesContextProps = useContext<SeriesContextProps>(SeriesContext);
    const userToken: string = session?.accessToken ? session?.accessToken : '';
    const {errorMessage, successMessage}: AlertContextProps = useContext<AlertContextProps>(AlertContext);
    const {isCurrentlyOffline} = useContext(OfflineContext);
    const {localSyncedSeries}: SeriesSyncContextProps = useContext<SeriesSyncContextProps>(SeriesSyncContext);
    const {addToQueue}: LocalSyncQueueContextProps = useContext<LocalSyncQueueContextProps>(LocalSyncQueueContext);
    const useLocal: boolean = isDesktop && isCurrentlyOffline();
    
    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 {
            const response: SeriesDetailResponse = useLocal
                ? await getSeriesDetail(seriesId) as SeriesDetailResponse
                : await apiGet<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 {
            let response: SeriesUpdateResponse;
            const updateData = {seriesId, name, description};
            if (useLocal) {
                response = {success: await updateSeries(updateData)} as SeriesUpdateResponse;
            } else {
                response = await apiPut<SeriesUpdateResponse>('series/update', updateData, userToken, lang);
                if (isDesktop && localSyncedSeries.find((s: SyncedSeries): boolean => s.id === seriesId)) {
                    addToQueue('update_series', updateData);
                }
            }
            if (!response.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 <PulseLoader/>;
    }
    
    return (
        <div className="space-y-6">
            <InputField fieldName={t('seriesBasicInformation.fields.name')} input={<TextInput
                value={name}
                setValue={(e: ChangeEvent<HTMLInputElement>) => setName(e.target.value)}
                placeholder={t('seriesBasicInformation.fields.namePlaceholder')}
            />}/>
            
            <InputField fieldName={t('seriesBasicInformation.fields.description')} input={<TextAreaInput
                value={description}
                setValue={(e: ChangeEvent<HTMLTextAreaElement>) => setDescription(e.target.value)}
                placeholder={t('seriesBasicInformation.fields.descriptionPlaceholder')}
            />}/>
        </div>
    );
}

export default forwardRef(BasicSeriesInformation);
