import { Flex, LoadingOverlay } from '@mantine/core';
import { IObjectParam } from '../../../interfaces/objects';
import ObjectParameter from '../ObjectParameter';
import useSWR from 'swr';
import { BASE_URL } from '../../../constants';
import { fetcher } from '../../../http/axiosInstance';
import { useObjectsStore } from '../../../store/objects';

const ObjectParameters = () => {
    const { currentObjectId } = useObjectsStore()

    const { data: valuesData, isValidating: valuesValidating } = useSWR(
        currentObjectId ? `/general/values/all?object_id=${currentObjectId}` : null,
        (url) => fetcher(url, BASE_URL.ems),
        {
            revalidateOnFocus: false,
            revalidateIfStale: false
        }
    )

    return (
        <Flex gap={'sm'} direction={'column'} pos='relative'>
            <LoadingOverlay visible={valuesValidating} />
            {Array.isArray(valuesData) &&
                Object.entries(
                    valuesData.reduce((acc, param) => {
                        if (!acc[param.id_param]) {
                            acc[param.id_param] = [];
                        }
                        acc[param.id_param].push(param);
                        return acc;
                    }, {} as Record<string, IObjectParam[]>)
                ).map(([id_param, params]) => {
                    // Step 1: Sort the parameters by date_s (start date) and date_po (end date)
                    const sortedParams = (params as IObjectParam[]).sort((b, a) => {
                        const dateA = new Date(a.date_s || 0);
                        const dateB = new Date(b.date_s || 0);
                        return dateA.getTime() - dateB.getTime();
                    });

                    return sortedParams.length > 1 ? (
                        sortedParams.map((param: IObjectParam) => {
                            if (param.date_po == null) {
                                return (
                                    <ObjectParameter key={id_param} param={param} showLabel={false} />
                                )
                            }
                        }
                        )
                    ) : (
                        <ObjectParameter key={id_param} param={sortedParams[0]} />
                    );
                })
            }
        </Flex>
    )
}

export default ObjectParameters