import {CRUDTableProps} from "../../../../../../types/CRUDTable.tsx";
import {DealServiceSchema, GetServiceKitSchema, UserSchema} from "../../../../../../client";
import {FC, useState} from "react";
import {ActionIcon, Button, Flex, Modal, NumberInput, rem, Text, Title, Tooltip} from "@mantine/core";
import {IconTrash, IconUsersGroup} from "@tabler/icons-react";
import {modals} from "@mantine/modals";
import {isNumber} from "lodash";
import SimpleUsersTable from "../../../../components/SimpleUsersTable/SimpleUsersTable.tsx";
import {ServiceType} from "../../../../../../shared/enums/ServiceType.ts";
import {useSelector} from "react-redux";
import {RootState} from "../../../../../../redux/store.ts";
import useDealProductAndServiceTabState from "../../hooks/useProductAndServiceTabState.tsx";

type RestProps = {
    onKitAdd?: (kit: GetServiceKitSchema) => void
};
type Props = CRUDTableProps<DealServiceSchema> & RestProps;
const DealServicesTable: FC<Props> = ({items, onDelete, onCreate, onChange, onKitAdd}) => {
    const authState = useSelector((state: RootState) => state.auth);

    const {dealState} = useDealProductAndServiceTabState();
    const isLocked = Boolean(dealState.deal?.billRequest);

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

    const onDeleteClick = (item: DealServiceSchema) => {
        if (!onDelete) return;
        onDelete(item);
    }
    const onCreateClick = () => {
        if (!onCreate) return;
        const serviceIds = items.map(service => service.service.id);
        modals.openContextModal({
            modal: "addDealService",
            innerProps: {
                onCreate: onCreate,
                serviceIds
            },
            withCloseButton: false
        })
    }
    const onQuantityChange = (item: DealServiceSchema, quantity: number) => {
        if (!onChange) return;
        onChange({
            ...item,
            quantity
        })
    }
    const onPriceChange = (item: DealServiceSchema, price: number) => {
        if (!onChange) return;
        onChange({
            ...item,
            price
        })
    }

    const onEmployeeClick = (item: DealServiceSchema) => {
        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
        });
    }
    const onAddKitClick = () => {
        if (!onKitAdd) return;
        modals.openContextModal({
            modal: "servicesKitSelectModal",
            innerProps: {
                onSelect: onKitAdd,
                serviceType: ServiceType.DEAL_SERVICE
            },
            withCloseButton: false

        })
    }
    return (
        <>
            <Flex
                direction={"column"}
                gap={rem(10)}
                h={"100%"}

            >
                <Flex
                    h={"100%"}
                    direction={"column"}>
                    <Title
                        order={3}
                        w={"100%"}
                        style={{textAlign: "center"}}
                        mb={rem(10)}
                    >Общие услуги</Title>

                    <Flex
                        direction={"column"}
                        gap={rem(10)}
                    >
                        {items.map(service => (
                            <Flex
                                key={service.service.id}
                                w={"100%"}
                                gap={rem(10)}
                                align={"center"}
                            >
                                <Tooltip

                                    onClick={() => onDeleteClick(service)}
                                    label="Удалить услугу">
                                    <ActionIcon
                                        disabled={isLocked}
                                        variant={"default"}>
                                        <IconTrash/>
                                    </ActionIcon>
                                </Tooltip>
                                {!authState.isGuest &&
                                    <Tooltip label="Сотрудники">
                                        <ActionIcon onClick={() => onEmployeeClick(service)} variant={"default"}>
                                            <IconUsersGroup/>
                                        </ActionIcon>
                                    </Tooltip>
                                }
                                <Text
                                    flex={1}
                                >{service.service.name}</Text>
                                <NumberInput
                                    disabled={isLocked}
                                    flex={1}
                                    suffix={" шт."}
                                    onChange={event => isNumber(event) && onQuantityChange(service, event)}
                                    value={service.quantity}
                                />
                                <NumberInput
                                    flex={1}
                                    onChange={event => isNumber(event) && onPriceChange(service, event)}
                                    suffix={"₽"}
                                    value={service.price}
                                    disabled={authState.isGuest || isLocked}
                                />
                            </Flex>
                        ))}
                    </Flex>

                    <Title
                        style={{textAlign: "end"}}
                        mt={rem(10)}
                        order={3}
                    >Итог: {items.reduce((acc, item) => acc + (item.price * item.quantity), 0)}₽</Title>
                </Flex>
                <Flex direction={"column"} gap={rem(10)} mt={"auto"}>
                    <Button
                        disabled={isLocked}
                        onClick={onCreateClick}
                        fullWidth
                        variant={"default"}
                    >Добавить услугу</Button>
                    <Button
                        disabled={isLocked}
                        onClick={onAddKitClick}
                        fullWidth
                        variant={"default"}
                    >
                        Добавить набор услуг
                    </Button>
                </Flex>
            </Flex>
            <Modal
                title={"Добавление сотрудника к услуге"}
                opened={employeesModalVisible}
                onClose={onEmployeeModalClose}
                size={"xl"}
            >
                <Flex direction={"column"} gap={rem(10)}>
                    <SimpleUsersTable
                        items={getCurrentEmployees()}
                        onChange={onEmployeesChange}

                    />

                </Flex>
            </Modal>
        </>

    )
}
export default DealServicesTable;