import {FC, useRef} from "react";
import ServicesTable from "../components/ServicesTable/ServicesTable.tsx";
import useServicesList from "../hooks/useServicesList.tsx";
import PageBlock from "../../../components/PageBlock/PageBlock.tsx";
import styles from './ServicesPage.module.css';
import {Button} from "@mantine/core";
import {BaseTableRef} from "../../../components/BaseTable/BaseTable.tsx";
import {ServiceCategorySchema, ServiceSchema, ServiceService} from "../../../client";
import {notifications} from "../../../shared/lib/notifications.ts";
import {modals} from "@mantine/modals";

export const ServicesPage: FC = () => {
    const {services, refetch} = useServicesList();

    const tableRef = useRef<BaseTableRef<ServiceSchema>>(null);

    const onCreateClick = () => {
        modals.openContextModal({
            modal: 'createService',
            title: 'Создание услуги',
            withCloseButton: false,
            innerProps: {
                onCreate
            }
        })
    }
    const onCreate = (values: ServiceSchema) => {
        ServiceService.createService({requestBody: {service: values}})
            .then(async ({ok, message}) => {
                notifications.guess(ok, {message: message});
                if (!ok) return;
                await refetch();
            })
    }
    const onCreateCategoryClick = () => {
        modals.openContextModal({
            modal: "createServiceCategory",
            title: 'Создание категории',
            withCloseButton: false,
            innerProps: {
                onCreate: onCategoryCreate
            }
        })
    }
    const onCategoryCreate = (category: ServiceCategorySchema) => {
        ServiceService.createServiceCategory({requestBody: {category: category}})
            .then(({ok, message}) =>
                notifications.guess(ok, {message: message}))
    }

    return (
        <div className={styles['container']}>
            <PageBlock>
                <div className={styles['top-panel']}>
                    <Button onClick={onCreateClick} variant={"default"}>Создать услугу</Button>
                    <Button onClick={onCreateCategoryClick} variant={"default"}>Создать категорию</Button>
                </div>
            </PageBlock>
            <PageBlock>
                <ServicesTable
                    tableRef={tableRef}
                    services={services}
                />
            </PageBlock>
        </div>
    )
}