import {
    useEffect,
    useState,
} from 'react';

import _ from 'lodash';
import { Loader2Icon } from 'lucide-react';

import { getDisplayValue } from '@/api/displayValuesService';

import ShortViewText from './ShortViewText';

const DisplayValue = ({ value, collection, short = false, className }: { value: any, collection?: string, short?: boolean, className?: string }) => {





    const [display, setDisplay] = useState<string | null>(null);

    const [loading, setLoading] = useState<boolean>(true);

    useEffect(() => {
        if (collection && value) {
            setLoading(true);

            getDisplayValue(collection, value)
                .then((displayValue) => {
                    setDisplay(displayValue);
                })
                .catch((error) => {
                    console.error('Error fetching display value:', error);
                    setDisplay(null);
                })
                .finally(() => {
                    setLoading(false);
                });
        } else {
            setDisplay(null);
            setLoading(false);
        }
    }, [value, collection]);



    if (loading) {
        return <span
            className={!!className ? className : 'text-sm font-medium'}

        ><Loader2Icon className="size-4 animate-spin" /></span>;
    }

    if (short) {

        return <ShortViewText
            className={!!className ? className : 'text-sm font-medium'}
            text={display}
        />
    }

    return <span
        className={!!className ? className : 'text-sm font-medium'}

    >{display}</span>;

}

export default DisplayValue;