import React, { useEffect } from 'react';

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

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 { openDialog } = useAppConfig();

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

        if (structure) {
            setLoading(true);

            loadTableDataInProgress.current = true;
            rpc.data({
                search: (!!search && !!search.trim()) ? search.trim() : undefined,
                collection: collection,
                filter: { ...filter },
                pipeline: filterPreset?.filter,

            }).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
                        onClick={() => {
                            openDialog({
                                modalKey: `collection_view_${structure?.collection}_${card._id}`,
                                collection: structure?.collection ?? "",
                                _id: card._id,
                            });
                        }}
                        key={card._id}
                        values={card}
                        structure={structure}
                    />
                })}
            </div>
        </div>
    );
};

export default BoardColumn;
