'use client'
import {ChangeEvent, forwardRef, useContext, useEffect, useImperativeHandle, useState} from "react";
import {apiGet, apiPut} from '@/lib/api/client';
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';

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 [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 = 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 {
            const response: SeriesUpdateResponse = await apiPut<SeriesUpdateResponse>('series/update', {
                seriesId: seriesId,
                name: name,
                description: description
            }, userToken, lang);
            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);
