import {CRUDTableProps} from "../../../../../../types/CRUDTable.tsx";
import {DealProductServiceSchema, UserSchema} from "../../../../../../client";
import {FC, useState} from "react";
import useProductServicesTableColumns from "./columns.tsx";
import {BaseTable} from "../../../../../../components/BaseTable/BaseTable.tsx";
import {MRT_TableOptions} from "mantine-react-table";
import {ActionIcon, Button, Flex, Modal, rem, Tooltip} from "@mantine/core";
import {IconEdit, IconTrash, IconUsersGroup} from "@tabler/icons-react";
import {modals} from "@mantine/modals";
import SimpleUsersTable from "../../../../components/SimpleUsersTable/SimpleUsersTable.tsx";
import {useSelector} from "react-redux";
import {RootState} from "../../../../../../redux/store.ts";
import useDealProductAndServiceTabState from "../../hooks/useProductAndServiceTabState.tsx";

type RestProps = {
    quantity: number;
    onCopyServices?: () => void;
    onKitAdd?: () => void;
}

type Props = CRUDTableProps<DealProductServiceSchema> & RestProps;
const ProductServicesTable: FC<Props> = ({
                                             items,
                                             quantity,
                                             onCreate,
                                             onDelete,
                                             onChange,
                                             onCopyServices,
                                             onKitAdd
                                         }) => {
    const {dealState} = useDealProductAndServiceTabState();
    const isLocked = Boolean(dealState.deal?.billRequest);
    const authState = useSelector((state: RootState) => state.auth);

    const columns = useProductServicesTableColumns({data: items, quantity});
    const serviceIds = items.map(service => service.service.id);

    const [currentService, setCurrentService] = useState<DealProductServiceSchema | undefined>();
    const [employeesModalVisible, setEmployeesModalVisible] = useState(false);

    const onCreateClick = () => {
        if (!onCreate) return;
        modals.openContextModal({
            modal: "productServiceForm",
            innerProps: {
                onCreate: onCreate,
                serviceIds,
                quantity
            },
            withCloseButton: false
        })
    }

    const onChangeClick = (item: DealProductServiceSchema) => {
        if (!onChange) return;
        modals.openContextModal({
            modal: "productServiceForm",
            innerProps: {
                element: item,
                onChange,
                serviceIds,
                quantity
            },
            withCloseButton: false
        })
    }
    const onEmployeeClick = (item: DealProductServiceSchema) => {
        if (!onChange) return;
        setCurrentService(item);
        setEmployeesModalVisible(true);
    }
    const onEmployeeModalClose = () => {
        setEmployeesModalVisible(false);
        setCurrentService(undefined);
    }
    const getCurrentEmployees = (): UserSchema[] => {
        if (!currentService) return [];
        const item = items.find(i => i.service.id === currentService.service.id)
        if (!item) return [];
        return item.employees;
    }
    const onEmployeesChange = (items: UserSchema[]) => {
        if (!currentService || !onChange) return;
        onChange({
            ...currentService,
            employees: items
        });
    }
    return (
        <>
            <Flex
                direction={"column"}
                gap={rem(10)}
            >
                <BaseTable
                    data={items}
                    columns={columns}
                    restProps={{
                        enableColumnActions: false,
                        enableSorting: false,
                        enableRowActions: true,
                        enableBottomToolbar: true,
                        renderBottomToolbar: (
                            <Flex justify={"flex-end"} gap={rem(10)} p={rem(10)}>
                                <Button
                                    disabled={isLocked}
                                    onClick={() => onKitAdd && onKitAdd()}
                                    variant={"default"}
                                >
                                    Добавить набор услуг
                                </Button>
                                <Button
                                    disabled={isLocked}
                                    onClick={() => onCopyServices && onCopyServices()}
                                    variant={"default"}
                                >
                                    Продублировать услуги
                                </Button>

                                <Button
                                    disabled={isLocked}
                                    onClick={onCreateClick}
                                    variant={"default"}
                                >
                                    Добавить услугу
                                </Button>

                            </Flex>
                        ),
                        renderRowActions: ({row}) => (
                            <Flex gap="md">
                                <Tooltip label="Удалить">
                                    <ActionIcon

                                        onClick={() => {
                                            if (onDelete) onDelete(row.original);
                                        }} variant={"default"}>
                                        <IconTrash/>
                                    </ActionIcon>
                                </Tooltip>
                                <Tooltip

                                    label="Редактировать">
                                    <ActionIcon

                                        onClick={() => onChangeClick(row.original)}
                                        variant={"default"}>
                                        <IconEdit/>
                                    </ActionIcon>
                                </Tooltip>
                                {!authState.isGuest &&
                                    <Tooltip label="Сотрудники">
                                        <ActionIcon onClick={() => onEmployeeClick(row.original)} variant={"default"}>
                                            <IconUsersGroup/>
                                        </ActionIcon>
                                    </Tooltip>
                                }
                            </Flex>
                        ),
                    } as MRT_TableOptions<DealProductServiceSchema>}
                />
            </Flex>
            <Modal
                title={"Добавление сотрудника к услуге"}
                opened={employeesModalVisible}
                onClose={onEmployeeModalClose}
                size={"xl"}
            >
                <Flex direction={"column"} gap={rem(10)}>
                    <SimpleUsersTable
                        items={getCurrentEmployees()}
                        onChange={onEmployeesChange}

                    />

                </Flex>
            </Modal>
        </>

    )
}
export default ProductServicesTable;