import PageBlock from "../../../components/PageBlock/PageBlock.tsx";
import {FC, useEffect, useState} from "react";
import styles from './ProductsPage.module.css';
import {Button, Flex, Pagination, rem, Text, TextInput} 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 useProductsList from "../hooks/useProductsList.tsx";
import {useDebouncedValue} from "@mantine/hooks";

export const ProductsPage: FC = () => {
    const [clientId, setClientId] = useState(-1);
    const [totalPages, setTotalPages] = useState(1);
    const [currentPage, setCurrentPage] = useState(1);
    const [searchInputRaw, setSearchInputRaw] = useState<string>("");
    const [searchInput] = useDebouncedValue(searchInputRaw, 500);
    const {products, paginationInfo, refetch} = useProductsList({
        clientId,
        page: currentPage - 1,
        itemsPerPage: 10,
        searchInput
    });
    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);
        if (currentPage > paginationInfo.totalPages) {
            setCurrentPage(1);
        }
    }, [paginationInfo]);

    return (
        <>
            <div className={styles['container']}>
                <PageBlock>
                    <div className={styles['top-panel']}>
                        <Flex gap={rem(10)}>

                            <ClientSelect onChange={event => setClientId(event.id)}/>
                            <Button
                                onClick={() => onCreateProductClick()}
                                variant={"default"}
                            >Создать</Button>
                        </Flex>
                        <Flex>
                            <TextInput
                                placeholder={"Артикул, название, шк"}
                                onChange={event => setSearchInputRaw(event.currentTarget.value)}
                                value={searchInputRaw}
                            />
                        </Flex>
                    </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>
        </>
    )
}
