import {FC} from "react";
import ClientsTable from "./components/ClientsTable/ClientsTable.tsx";
import useClientsList from "./hooks/useClientsList.tsx";
import PageBlock from "../../components/PageBlock/PageBlock.tsx";
import styles from './ClientsPage.module.css';
import {Button} from "@mantine/core";
import {modals} from "@mantine/modals";
import {ClientSchema, ClientService} from "../../client";
import {notifications} from "../../shared/lib/notifications.ts";

const ClientsPage: FC = () => {
    const {clients, refetch} = useClientsList();
    const onCreate = (client: ClientSchema) => {
        ClientService
            .createClientApi({
                requestBody: {
                    data: client
                }
            })
            .then(async ({ok, message}) => {
                notifications.guess(ok, {message});
                if (ok)
                    await refetch()
            })
    }
    const onChange = (client: ClientSchema) => {
        ClientService
            .updateClient({
                requestBody: {
                    data: client
                }
            })
            .then(async ({ok, message}) => {
                notifications.guess(ok, {message});
                if (ok)
                    await refetch()
            })
    }
    const onDelete = (client: ClientSchema) => {
        ClientService
            .deleteClient({
                requestBody: {
                    clientId: client.id
                }
            })
            .then(async ({ok, message}) => {
                notifications.guess(ok, {message});
                if (ok)
                    await refetch()
            })
    }
    const onCreateClick = () => {
        modals.openContextModal({
            modal: 'productFormModal',
            title: "Создание клиента",
            innerProps: {
                onCreate
            }
        })
    }

    return (
        <div className={styles['container']}>
            <PageBlock>
                <div className={styles['top-panel']}>
                    <Button
                        onClick={onCreateClick}
                        variant={"default"}
                    >
                        Создать клиента
                    </Button>
                </div>

            </PageBlock>
            <PageBlock>
                <ClientsTable
                    onChange={onChange}
                    onDelete={onDelete}
                    items={clients}
                />
            </PageBlock>
        </div>
    )
}
export default ClientsPage;