import { SegmentedControl, SegmentedControlItem, SegmentedControlProps } from "@mantine/core";
import { FC, useEffect } from "react";
import { BoardSchema, ProjectSchema } from "../../../../../../client";

export enum GroupStatisticsTable {
    BY_DATES,
    BY_CLIENTS,
    BY_PROJECTS,
    BY_BOARDS,
    BY_STATUSES,
    BY_WAREHOUSES,
    BY_MARKETPLACES,
    BY_MANAGERS,
}

type ControlProps = Omit<SegmentedControlProps, "data">;

type OtherProps = {
    selectedBoard: BoardSchema | null;
    selectedProject: ProjectSchema | null;
}

type Props = ControlProps & OtherProps;

export const ProfitTableSegmentedControl: FC<Props> = props => {
    const data: (string | SegmentedControlItem)[] = [
        {
            label: "По датам",
            value: GroupStatisticsTable.BY_DATES.toString(),
        },
        {
            label: "По клиентам",
            value: GroupStatisticsTable.BY_CLIENTS.toString(),
        },
        {
            label: "По проектам",
            value: GroupStatisticsTable.BY_PROJECTS.toString(),
        },
        {
            label: "По доскам",
            value: GroupStatisticsTable.BY_BOARDS.toString(),
            disabled: !props.selectedProject,
        },
        {
            label: "По статусам",
            value: GroupStatisticsTable.BY_STATUSES.toString(),
            disabled: !props.selectedBoard,
        },
        {
            label: "По складам отгрузки",
            value: GroupStatisticsTable.BY_WAREHOUSES.toString(),
        },
        {
            label: "По маркетплейсам",
            value: GroupStatisticsTable.BY_MARKETPLACES.toString(),
        },
        {
            label: "По менеджерам",
            value: GroupStatisticsTable.BY_MANAGERS.toString(),
        },
    ];

    const setGrouping = (status: GroupStatisticsTable) => {
        if (!props.onChange) return;
        props.onChange(status.toString());
    };

    useEffect(() => {
        if (props.value === GroupStatisticsTable.BY_STATUSES.toString()) {
            if (!props.selectedProject) {
                setGrouping(GroupStatisticsTable.BY_PROJECTS);
            } else if (!props.selectedBoard) {
                setGrouping(GroupStatisticsTable.BY_BOARDS);
            }
        } else if (props.value === GroupStatisticsTable.BY_BOARDS.toString() && !props.selectedProject) {
            setGrouping(GroupStatisticsTable.BY_PROJECTS);
        }
    }, [props.selectedBoard, props.selectedProject]);

    return (
        <SegmentedControl
            data={data}
            {...props}
        />
    );
};