import React, { useEffect } from 'react';

import { rpc } from '@/api/request';
import {
    BoardFilterPresetFKTType,
    DatumDHLTType,
} from '@/api/types';
import { cn } from '@/lib/utils';

import { BoardViewProps } from '../BoardView';
import { useBoardViewSize } from '../boardViewSize';
import BoardCard from './BoardCard';
import BoardColumnHeader from './BoardColumnHeader';

type BoardColumnProps = {

    filterPreset: BoardFilterPresetFKTType;
} & BoardViewProps

const BoardColumn = ({ filterPreset, search, filter, collection, structure }: BoardColumnProps) => {

    const tokens = useBoardViewSize();

    const [loading, setLoading] = React.useState<boolean>(false);
    const [data, setData] = React.useState<DatumDHLTType | null>(null);
    const [total, setTotal] = React.useState<number>(0);

    const loadTableDataInProgress = React.useRef<boolean>(false);
    const loadTableData = React.useCallback(() => {

        if (structure) {
            setLoading(true);


            loadTableDataInProgress.current = true;
            rpc.data({
                //  sort: sort ?? undefined,
                search: (!!search && !!search.trim()) ? search.trim() : undefined,
                collection: collection,

                // limit: limit,
                filter: { ...filter },
                pipeline: filterPreset?.filter,
                // offset: offset,

            }).then((data) => {



                setData(data.result ?? null);
                setTotal(data.result?.total ?? 0);
            }).finally(() => {
                loadTableDataInProgress.current = false;
                setLoading(false);
            });
        }
    }, [structure, collection, search, filterPreset, filter]);

    useEffect(() => {
        loadTableData();
    }, [search, filterPreset, filter, collection, structure]);


    return (
        <div className={cn('board-view__column shrink-0', tokens?.columnWidth)}>
            <BoardColumnHeader title={filterPreset.title ?? ""} count={total} />
            <div className={cn('board-view__column-body', tokens?.bodyGap)}>

                {data?.data?.map((card) => {
                    return <BoardCard
                        key={card._id}
                        values={card}
                        structure={structure}
                    />
                })}
            </div>
        </div>
    );
};

export default BoardColumn;
