import PageBlock from "../../../components/PageBlock/PageBlock.tsx";
import {FC, useEffect, useState} from "react";
import styles from './ProductsPage.module.css';
import {Button, Text, Pagination} from "@mantine/core";
import ClientSelect from "../../../components/Selects/ClientSelect/ClientSelect.tsx";
import ProductsTable from "../components/ProductsTable/ProductsTable.tsx";
import {modals} from "@mantine/modals";
import {notifications} from "../../../shared/lib/notifications.ts";
import {CreateProductRequest} from "../types.ts";
import {ProductSchema, ProductService} from "../../../client";
import ServiceSelect from "../../../components/ServiceSelect/ServiceSelect.tsx";
import useProductsList from "../hooks/useProductsList.tsx";
import useServicesList from "../../ServicesPage/hooks/useServicesList.tsx";

export const ProductsPage: FC = () => {
    const [clientId, setClientId] = useState(-1);
    const [totalPages, setTotalPages] = useState(1);
    const [currentPage, setCurrentPage] = useState(1);

    const {products, paginationInfo, refetch} = useProductsList({
        clientId,
        page: currentPage - 1,
        itemsPerPage: 10
    });
    const onProductCreate = (request: CreateProductRequest) => {
        ProductService.createProduct({requestBody: request})
            .then(async ({ok, message}) => {
                notifications.guess(ok, {message: message});
                if (!ok) return;
                await refetch();
            });
    }

    const onProductChange = (product: ProductSchema) => {
        ProductService.updateProduct({requestBody: {product}})
            .then(async ({ok, message}) => {
                notifications.guess(ok, {message});
                if (!ok) return;
                await refetch();
            })
    }

    const onCreateProductClick = () => {
        if (clientId < 0) {
            notifications.error({message: "Необходимо выбрать клиента"});
            return
        }
        modals.openContextModal({
            modal: "createProduct",
            title: 'Создание товара',
            withCloseButton: false,
            innerProps: {
                clientId,
                onCreate: onProductCreate
            }
        })
    }

    const onDeleteClick = (product: ProductSchema) => {
        modals.openConfirmModal({
            title: 'Удаление товара',
            centered: true,
            children: (
                <Text size="sm">
                    Вы уверены что хотите удалить товар {product.name}
                </Text>
            ),
            labels: {confirm: 'Да', cancel: "Нет"},
            confirmProps: {color: 'red'},
            onConfirm: () =>
                ProductService.deleteProduct({requestBody: {productId: product.id}})
                    .then(async ({ok, message}) => {
                        notifications.guess(ok, {message: message});
                        if (!ok) return;
                        await refetch();
                    })
        });
    }

    useEffect(() => {
        if (!paginationInfo) return;
        setTotalPages(paginationInfo.totalPages);
    }, [paginationInfo]);
    return (
        <>
            <div className={styles['container']}>
                <PageBlock>
                    <div className={styles['top-panel']}>
                        <ClientSelect onChange={event => setClientId(event.id)}/>
                        <Button
                            onClick={() => onCreateProductClick()}
                            variant={"default"}
                        >Создать</Button>
                        {/*<ServiceSelect*/}
                        {/*    value={selectedService}*/}
                        {/*    onChange={setSelectedService}/>*/}
                    </div>
                </PageBlock>
                <PageBlock>
                    <div className={styles['body-container']}>
                        <div className={styles['table-container']}>
                            <ProductsTable
                                onChange={onProductChange}
                                onDelete={onDeleteClick}
                                items={products}
                            />
                            <Pagination
                                className={styles['table-pagination']}
                                withEdges
                                onChange={event => setCurrentPage(event)}
                                total={totalPages}
                                value={currentPage}
                            />
                        </div>
                    </div>
                </PageBlock>
            </div>
        </>
    )
}
