import {FC, useState} 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, Text} from "@mantine/core";
import {GetServiceKitSchema, ServiceCategorySchema, ServiceSchema, ServiceService} from "../../../client";
import {notifications} from "../../../shared/lib/notifications.ts";
import {modals} from "@mantine/modals";
import ServiceTypeSegmentedControl, {
    ServicesTab
} from "../components/ServiceTypeSegmentedControl/ServiceTypeSegmentedControl.tsx";
import useServicesKitsList from "../hooks/useServicesKitsList.tsx";
import ServicesKitsTable from "../components/ServicesKitsTable/ServicesKitsTable.tsx";
import {omit} from "lodash";


export const ServicesPage: FC = () => {
    const {services, refetch} = useServicesList();
    const {objects: servicesKits, refetch: refetchKits} = useServicesKitsList();
    const [serviceType, setServiceType] = useState(ServicesTab.DEAL_SERVICE)
    // region Service create
    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();
            })
    }
    // endregion

    // region Category create
    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}))
    }
    // endregion

    const onServiceDelete = (service: ServiceSchema) => {
        modals.openConfirmModal({
            title: 'Удаление услуги',
            children: (<Text>
                Вы уверены, что хотите удалить услугу "{service.name}"?
            </Text>),
            onConfirm: () => {
                ServiceService.deleteService({requestBody: {serviceId: service.id}})
                    .then(async ({ok, message}) => {
                        notifications.guess(ok, {message: message});
                        if (!ok) return;
                        await refetch();
                    })
            },
            labels: {
                confirm: 'Удалить',
                cancel: 'Отмена'
            }
        });
    }

    const onServiceUpdate = (service: ServiceSchema) => {
        ServiceService
            .updateService({
                requestBody: {
                    data: service
                }
            })
            .then(async ({ok, message}) => {
                notifications.guess(ok, {message: message});
                if (!ok) return;
                await refetch();
            })
    }

    const onKitCreate = (kit: GetServiceKitSchema) => {
        ServiceService.createServicesKit({
            requestBody: {
                data: {
                    ...omit(kit, ["services", "id"]),
                    servicesIds: kit.services.map(service => service.id)
                }
            }
        }).then(async ({ok, message}) => {
            notifications.guess(ok, {message: message});
            if (!ok) return;
            await refetchKits();
        })
    }

    const onKitCreateClick = () => {
        modals.openContextModal({
            modal: 'serviceKitModalForm',
            title: 'Создание набора услуг',
            withCloseButton: false,
            innerProps: {
                onCreate: onKitCreate
            }
        })
    }
    const onKitUpdate = (kit: GetServiceKitSchema) => {
        ServiceService.updateServicesKit({
            requestBody: {
                data: {
                    ...omit(kit, ["services"]),
                    servicesIds: kit.services.map(service => service.id)
                }
            }
        }).then(async ({ok, message}) => {
            notifications.guess(ok, {message: message});
            if (!ok) return;
            await refetchKits();
        })
    }
    return (
        <div className={styles['container']}>
            <PageBlock>
                <div className={styles['top-panel']}>
                    {
                        serviceType === ServicesTab.SERVICES_KITS ?
                            <Button onClick={onKitCreateClick} variant={"default"}>Создать набор</Button> :
                            <>
                                <Button onClick={onCreateClick} variant={"default"}>Создать услугу</Button>
                                <Button onClick={onCreateCategoryClick} variant={"default"}>Создать
                                    категорию</Button>
                            </>
                    }

                    <ServiceTypeSegmentedControl
                        className={styles['top-panel-last-item']}
                        value={serviceType.toString()}
                        onChange={(event) => setServiceType(parseInt(event))}
                    />
                </div>
            </PageBlock>
            <PageBlock>
                {
                    serviceType === ServicesTab.SERVICES_KITS ?
                        <ServicesKitsTable
                            items={servicesKits}
                            onChange={onKitUpdate}
                        />
                        :
                        <ServicesTable
                            onDelete={onServiceDelete}
                            onChange={onServiceUpdate}
                            items={services.filter(service => service.serviceType == serviceType)}
                        />
                }
            </PageBlock>
        </div>
    )
}