import {useEffect, useState} from "@wordpress/element";
import {__, sprintf} from "@wordpress/i18n";
import Badge from "../../../../../../fields/badge";
import {DeleteModel, GetModels} from "../../../../../../../rest/models";
import {handleError, handleSuccess} from "../../../../../../../helpers/notifications";
import {handlePaginationAfterDeletion} from "../../../../../../../helpers";
import Table from "../../../../../../sections/table";
import Empty from "../../../../containers/content/empty";
import ContentLoading from "../../../../containers/content/loading";
import ContentBodyInner from "../../../../containers/content/body-inner";
import Container from "../../../../containers/content/container";
import {getUtilityLinkTo} from "../../../../../../../helpers";
import Actions from "./table/actions";
import confirm from "../../../../../../../helpers/confirm";

export default function TrainingMyModels({notifications}) {
    // State
    const [loading, setLoading] = useState(0);
    const [isDataFetched, setIsDataFetched] = useState(false);
    const [isAllSelected, setIsAllSelected] = useState(false);
    const [deleting, setDeleting] = useState([]);
    // Data
    const [models, setModels] = useState([]);
    const [selected, setSelected] = useState([]);
    const [modelsPagination, setModelsPagination] = useState({
        page: 1,
        perPage: LimbChatbot.screen_options?.lbaic_items_per_page || 10,
        total: 0
    });
    const [modelsOrder, setModelsOrder] = useState({
        orderBy: 'id',
        order: 'asc',
    });

    useEffect(() => {
        // Fetch models
        fetchModels(1, modelsPagination.perPage, modelsOrder);
    }, [modelsOrder]);

    useEffect(() => {
        // If all datasets ids exists in the selected list
        setIsAllSelected(selected.length > 0 && models.every(item => selected.includes(item.id)));
    }, [models, selected]);

    /**
     * Check/Uncheck all datasets
     */
    const toggleAll = () => {
        if (isAllSelected) {
            setSelected([]);
        } else {
            setSelected([...models.map(item => item.id)]);
        }
    }

    /**
     * Get models
     */
    const fetchModels = (page, perPage, params = {}) => {
        setLoading(prev => prev + 1);
        GetModels(LimbChatbot.rest.url, LimbChatbot.rest.nonce, {
            page: page,
            per_page: perPage,
            fine_tuned: 1,
            include: ['dataset', 'parent_model', 'metas'],
            orderby: params.orderBy || 'id',
            order: params.order || 'asc',
        }).then(res => {
            if (res.items?.length) {
                setModels([...res.items]);
            } else {
                setModels([]);
            }
            // Pagination state
            setModelsPagination(prevState => ({
                ...prevState,
                page: page,
                total: +res.total,
            }));
            setIsDataFetched(true);
            setLoading(prev => prev - 1);
        }).catch(e => {
            setModels([]);
            setIsDataFetched(true);
            setLoading(prev => prev - 1);
            handleError(e, notifications.set, {
                title: __("Failed to retrieve models data.", 'limb-chatbot'),
                description: e.message ? __(e.message, 'limb-chatbot') : __("Please check your connection and try again.", 'limb-chatbot'),
            });
        });
    }

    /**
     * Delete model
     *
     * @param {object} model Model data
     */
    const deleteModel = async (model) => {
        if (deleting.indexOf(model.id) === -1) {
            if (await confirm(__("Are you sure you want to delete the model?", 'limb-chatbot'))) {
                setDeleting(prevState => [...prevState, model.id]);
                DeleteModel(LimbChatbot.rest.url, LimbChatbot.rest.nonce, model.id).then(res => {
                    // Handle pagination after deletion
                    handlePaginationAfterDeletion({
                        currentItemsCount: models.length,
                        deletedCount: 1,
                        pagination: modelsPagination,
                        fetchFunction: fetchModels,
                        order: modelsOrder,
                        setItems: setModels,
                        setPagination: setModelsPagination,
                        deletedIds: [model.id]
                    });

                    setDeleting(prevState => prevState.filter(item => item !== model.id));
                    handleSuccess(notifications.set, {
                        title: __("Deletion completed successfully.", 'limb-chatbot'),
                    });
                }).catch(e => {
                    setDeleting(prevState => prevState.filter(item => item !== model.id));
                    handleError(e, notifications.set, {
                        title: __("Failed to delete model.", 'limb-chatbot'),
                        description: e.message ? __(e.message, 'limb-chatbot') : __("Please try again.", 'limb-chatbot'),
                    });
                });
            }
        }
    }

    const tableStructure = {
        columns: [
            // {
            //     id: 'check',
            //     label: false,
            //     className: 'lbaic-settings-table-card-checkbox',
            //     render: () => <Checkbox isChecked={isAllSelected} toggleValue={toggleAll}/>,
            //     value: {
            //         className: 'lbaic-settings-table-card-checkbox',
            //         render: (row, index) => {
            //             return <Checkbox isChecked={selected.includes(row.id)} toggleValue={() => {
            //                 if (selected.includes(row.id)) {
            //                     setSelected(prevState => prevState.filter((item) => item.id !== row.id));
            //                 } else {
            //                     setSelected(prevState => [...prevState, row.id]);
            //                 }
            //             }}/>;
            //         }
            //     },
            // },
            {
                id: 'id',
                label: __("ID", 'limb-chatbot'),
                className: false,
                render: false,
                sortable: true,
                value: {
                    className: false,
                    value: (row, index) => row.id,
                },
            },
            {
                id: 'name',
                label: __("Model name", 'limb-chatbot'),
                className: false,
                render: false,
                sortable: true,
                value: {
                    className: false,
                    value: (row, index) => row.name,
                },
            },
            {
                id: 'ai_provider_id',
                label: __("AI model name", 'limb-chatbot'),
                className: false,
                render: false,
                value: {
                    className: false,
                    nullable: (row, index) => !row.parent_model?.name,
                    value: (row, index) => row.parent_model?.name || __("N/A", 'limb-chatbot'),
                },
            },
            {
                id: 'dataset_name',
                label: __("Q&A name", 'limb-chatbot'),
                className: false,
                render: false,
                value: {
                    className: false,
                    nullable: (row, index) => !row.dataset?.name,
                    value: (row, index) => row.dataset?.name || __("N/A", 'limb-chatbot'),
                },
            },
            {
                id: 'status',
                label: __("Status", 'limb-chatbot'),
                className: false,
                render: false,
                value: {
                    className: 'lbaic-settings-table-card-floating',
                    nullable: (row, index) => row.status !== 1 && row.status !== 2,
                    render: (row, index) => {
                        if (row.status === 1) {
                            return <Badge label={__("Active", 'limb-chatbot')} icon='check' className='lbaic-settings-badge-green'/>;
                        }
                        if (row.status === 2) {
                            return <Badge label={__("Inactive", 'limb-chatbot')} icon='alert' className='lbaic-settings-badge-gray'/>;
                        }
                        return __("N/A", 'limb-chatbot');
                    },
                },
            },
            {
                id: 'actions',
                label: false,
                className: false,
                render: null,
                value: {
                    className: 'lbaic-settings-table-card-floating',
                    render: (row, index) =>
                        <Actions model={row} deleting={deleting} deleteModel={deleteModel} notifications={notifications}/>
                },
            },
        ]
    };

    return (
        <>
            <ContentBodyInner>
                {loading > 0 && !isDataFetched && <ContentLoading/>}
                <Container className="lbaic-settings-a-ftmm">
                    {
                        models.length > 0 ? (
                            <Table
                                className='lbaic-settings-scroll-style lbaic-settings-scroll-x lbaic-settings-table-card-kb-my-models'
                                structure={tableStructure}
                                data={models}
                                pagination={modelsPagination}
                                order={{get: modelsOrder, set: setModelsOrder}}
                                _callback={fetchModels}/>
                        ) : (
                            isDataFetched && (
                                <Empty title={__("No models yet", 'limb-chatbot')}
                                       subtitle={sprintf(__("Start by running your Q&A %shere%s", 'limb-chatbot'), '<a href="' + getUtilityLinkTo('training', 'qas') + '">', '</a>')}
                                       icon="tab-my-moduls-active"/>
                            )
                        )
                    }
                </Container>
            </ContentBodyInner>
        </>
    )
}