import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';

type ProductsStore = {
    products: productsSchema;

    // Product-level actions
    addProduct: (productName: string, productUuid: string) => void;
    setProducts: (products: productsSchema) => void;
    clearProducts: () => void;
    removeProduct: (productUuid: string) => void;
    updateProduct: (productUuid: string, updates: Partial<{ productName: string; eventDatas: EventsSchema[] }>) => void;

    // Event-level actions
    addEvent: (productUuid: string, event: EventsSchema) => void;
    removeEvent: (productUuid: string, modelUuid: string) => void;
    deleteEvent: (modelUuid: string) => EventsSchema[];
    updateEvent: (productUuid: string, modelUuid: string, updates: Partial<EventsSchema>) => EventsSchema | undefined;

    // Point-level actions
    addPoint: (productUuid: string, modelUuid: string, point: ConveyorPointSchema | VehiclePointSchema | RoboticArmPointSchema | MachinePointSchema | StoragePointSchema | HumanPointSchema) => EventsSchema | undefined;
    removePoint: (productUuid: string, modelUuid: string, pointUuid: string) => EventsSchema | undefined;
    updatePoint: (
        productUuid: string,
        modelUuid: string,
        pointUuid: string,
        updates: Partial<ConveyorPointSchema | VehiclePointSchema | RoboticArmPointSchema | MachinePointSchema | StoragePointSchema | HumanPointSchema>
    ) => EventsSchema | undefined;

    // Action-level actions
    addAction: (
        productUuid: string,
        modelUuid: string,
        pointUuid: string,
        action: ConveyorPointSchema['action'] | VehiclePointSchema['action'] | RoboticArmPointSchema['actions'][0] | MachinePointSchema['action'] | StoragePointSchema['action'] | HumanPointSchema['actions'][0]
    ) => EventsSchema | undefined;
    removeAction: (productUuid: string, actionUuid: string) => EventsSchema | undefined;
    updateAction: (
        productUuid: string,
        actionUuid: string,
        updates: Partial<ConveyorPointSchema['action'] | VehiclePointSchema['action'] | RoboticArmPointSchema['actions'][0] | MachinePointSchema['action'] | StoragePointSchema['action'] | HumanPointSchema['actions'][0]>
    ) => EventsSchema | undefined;

    // Trigger-level actionss
    addTrigger: (
        productUuid: string,
        actionUuid: string,
        trigger: TriggerSchema
    ) => EventsSchema | undefined;
    removeTrigger: (productUuid: string, triggerUuid: string) => EventsSchema | undefined;
    updateTrigger: (
        productUuid: string,
        triggerUuid: string,
        updates: Partial<TriggerSchema>
    ) => EventsSchema | undefined;

    // Renaming functions
    renameProduct: (productUuid: string, newName: string) => void;
    renameAction: (productUuid: string, actionUuid: string, newName: string) => EventsSchema | undefined;
    renameTrigger: (productUuid: string, triggerUuid: string, newName: string) => EventsSchema | undefined;

    // Helper functions
    getProductById: (productUuid: string) => { productName: string; productUuid: string; eventDatas: EventsSchema[] } | undefined;
    getEventByModelUuid: (productUuid: string, modelUuid: string) => EventsSchema | undefined;
    getEventByActionUuid: (productUuid: string, actionUuid: string) => EventsSchema | undefined;
    getEventByTriggerUuid: (productUuid: string, triggerUuid: string) => EventsSchema | undefined;
    getEventByPointUuid: (productUuid: string, pointUuid: string) => EventsSchema | undefined;
    getPointByUuid: (productUuid: string, modelUuid: string, pointUuid: string) => ConveyorPointSchema | VehiclePointSchema | RoboticArmPointSchema | MachinePointSchema | StoragePointSchema | HumanPointSchema | undefined;
    getActionByUuid: (productUuid: string, actionUuid: string) => (ConveyorPointSchema['action'] | VehiclePointSchema['action'] | RoboticArmPointSchema['actions'][0] | MachinePointSchema['action'] | StoragePointSchema['action'] | HumanPointSchema['actions'][0]) | undefined;
    getActionByPointUuid: (productUuid: string, pointUuid: string) => (ConveyorPointSchema['action'] | VehiclePointSchema['action'] | RoboticArmPointSchema['actions'][0] | MachinePointSchema['action'] | StoragePointSchema['action'] | HumanPointSchema['actions'][0]) | undefined;
    getModelUuidByPointUuid: (productUuid: string, actionUuid: string) => (string) | undefined;
    getModelUuidByActionUuid: (productUuid: string, actionUuid: string) => (string) | undefined;
    getPointUuidByActionUuid: (productUuid: string, actionUuid: string) => (string) | undefined;
    getTriggerByUuid: (productUuid: string, triggerUuid: string) => TriggerSchema | undefined;
    getTriggersByTriggeredPointUuid: (productUuid: string, triggeredPointUuid: string) => TriggerSchema[];
    getIsEventInProduct: (productUuid: string, modelUuid: string) => boolean;
};

export const createProductStore = () => {
    return create<ProductsStore>()(
        immer((set, get) => ({
            products: [],

            // Product-level actions
            addProduct: (productName, productUuid) => {
                set((state) => {
                    const existingProduct = state.products.find(p => p.productUuid === productUuid);
                    if (!existingProduct) {
                        const newProduct = {
                            productName,
                            productUuid: productUuid,
                            eventDatas: []
                        };
                        state.products.push(newProduct);
                    }
                });
            },

            setProducts: (products) => {
                set((state) => {
                    state.products = products;
                });
            },

            clearProducts: () => {
                set((state) => {
                    state.products = [];
                });
            },

            removeProduct: (productUuid) => {
                set((state) => {
                    state.products = state.products.filter(p => p.productUuid !== productUuid);
                });
            },

            updateProduct: (productUuid, updates) => {
                set((state) => {
                    const product = state.products.find(p => p.productUuid === productUuid);
                    if (product) {
                        Object.assign(product, updates);
                    }
                });
            },

            // Event-level actions
            addEvent: (productUuid, event) => {
                set((state) => {
                    const product = state.products.find(p => p.productUuid === productUuid);
                    if (product) {
                        const existingEvent = product.eventDatas.find(e => 'modelUuid' in e && e.modelUuid === event.modelUuid);
                        if (!existingEvent) {
                            product.eventDatas.push(event);
                        }
                    }
                });
            },

            removeEvent: (productUuid, modelUuid) => {
                set((state) => {
                    const product = state.products.find(p => p.productUuid === productUuid);
                    if (product) {
                        product.eventDatas = product.eventDatas.filter(e => 'modelUuid' in e && e.modelUuid !== modelUuid);
                    }
                });
            },

            deleteEvent: (modelUuid) => {
                let updatedEvents: EventsSchema[] = [];
                set((state) => {
                    const actionsToDelete = new Set<string>();

                    for (const product of state.products) {
                        const eventIndex = product.eventDatas.findIndex(e => 'modelUuid' in e && e.modelUuid === modelUuid);
                        if (eventIndex !== -1) {
                            const event = product.eventDatas[eventIndex];

                            if ('points' in event) {
                                for (const point of (event as ConveyorEventSchema).points) {
                                    if (point.action) {
                                        actionsToDelete.add(point.action.actionUuid);
                                    }
                                }
                            } else if ('point' in event) {
                                const point = (event as any).point;
                                if ('action' in point && point.action) {
                                    actionsToDelete.add(point.action.actionUuid);
                                } else if ('actions' in point) {
                                    for (const action of point.actions) {
                                        actionsToDelete.add(action.actionUuid);
                                    }
                                }
                            }

                            product.eventDatas.splice(eventIndex, 1);
                        }
                    }

                    for (const product of state.products) {
                        for (const event of product.eventDatas) {
                            let eventModified = false;

                            if ('points' in event) {
                                for (const point of (event as ConveyorEventSchema).points) {
                                    if (point.action?.triggers) {
                                        const originalLength = point.action.triggers.length;
                                        point.action.triggers = point.action.triggers.filter(trigger => {
                                            return !(
                                                (trigger.triggeredAsset?.triggeredModel?.modelUuid === modelUuid) ||
                                                (actionsToDelete.has(trigger.triggeredAsset?.triggeredAction?.actionUuid || ''))
                                            );
                                        });
                                        if (point.action.triggers.length !== originalLength) {
                                            eventModified = true;
                                        }
                                    }
                                }
                            } else if ('point' in event) {
                                const point = (event as any).point;
                                if ('action' in point && point.action?.triggers) {
                                    const originalLength = point.action.triggers.length;
                                    point.action.triggers = point.action.triggers.filter((trigger: TriggerSchema) => {
                                        return !(
                                            (trigger.triggeredAsset?.triggeredModel?.modelUuid === modelUuid) ||
                                            (actionsToDelete.has(trigger.triggeredAsset?.triggeredAction?.actionUuid || ''))
                                        );
                                    });
                                    if (point.action.triggers.length !== originalLength) {
                                        eventModified = true;
                                    }
                                } else if ('actions' in point) {
                                    for (const action of point.actions) {
                                        if (action.triggers) {
                                            const originalLength = action.triggers.length;
                                            action.triggers = action.triggers.filter((trigger: TriggerSchema) => {
                                                return !(
                                                    (trigger.triggeredAsset?.triggeredModel?.modelUuid === modelUuid) ||
                                                    (actionsToDelete.has(trigger.triggeredAsset?.triggeredAction?.actionUuid || ''))
                                                );
                                            });
                                            if (action.triggers.length !== originalLength) {
                                                eventModified = true;
                                            }
                                        }
                                    }
                                }
                            }

                            if (eventModified) {
                                updatedEvents.push(JSON.parse(JSON.stringify(event)));
                            }
                        }
                    }
                });
                return updatedEvents;
            },

            updateEvent: (productUuid, modelUuid, updates) => {
                let updatedEvent: EventsSchema | undefined;
                set((state) => {
                    const product = state.products.find(p => p.productUuid === productUuid);
                    if (product) {
                        const event = product.eventDatas.find(e => 'modelUuid' in e && e.modelUuid === modelUuid);
                        if (event) {
                            Object.assign(event, updates);
                            updatedEvent = JSON.parse(JSON.stringify(event));
                        }
                    }
                });
                return updatedEvent;
            },

            // Point-level actions
            addPoint: (productUuid, modelUuid, point) => {
                let updatedEvent: EventsSchema | undefined = undefined;
                set((state) => {
                    const product = state.products.find(p => p.productUuid === productUuid);
                    if (product) {
                        const event = product.eventDatas.find(e => 'modelUuid' in e && e.modelUuid === modelUuid);
                        if (event && 'points' in event) {
                            const existingPoint = (event as ConveyorEventSchema).points.find(p => p.uuid === point.uuid);
                            if (!existingPoint) {
                                (event as ConveyorEventSchema).points.push(point as ConveyorPointSchema);
                                updatedEvent = JSON.parse(JSON.stringify(event));
                            }
                        } else if (event && 'point' in event) {
                            const existingPoint = (event as any).point?.uuid === point.uuid;
                            if (!existingPoint) {
                                (event as VehicleEventSchema | RoboticArmEventSchema | MachineEventSchema | StorageEventSchema).point = point as any;
                                updatedEvent = JSON.parse(JSON.stringify(event));
                            }
                        }
                    }
                });
                return updatedEvent;
            },

            removePoint: (productUuid, modelUuid, pointUuid) => {
                let updatedEvent: EventsSchema | undefined = undefined;
                set((state) => {
                    const product = state.products.find(p => p.productUuid === productUuid);
                    if (product) {
                        const event = product.eventDatas.find(e => 'modelUuid' in e && e.modelUuid === modelUuid);
                        if (event && 'points' in event) {
                            (event as ConveyorEventSchema).points = (event as ConveyorEventSchema).points.filter(p => p.uuid !== pointUuid);
                            updatedEvent = JSON.parse(JSON.stringify(event));
                        } else if (event && 'point' in event && (event as any).point.uuid === pointUuid) {
                            // For events with single point, we can't remove it, only reset to empty
                        }
                    }
                });
                return updatedEvent;
            },

            updatePoint: (productUuid, modelUuid, pointUuid, updates) => {
                let updatedEvent: EventsSchema | undefined;
                set((state) => {
                    const product = state.products.find(p => p.productUuid === productUuid);
                    if (product) {
                        const event = product.eventDatas.find(e => 'modelUuid' in e && e.modelUuid === modelUuid);
                        if (event && 'points' in event) {
                            const point = (event as ConveyorEventSchema).points.find(p => p.uuid === pointUuid);
                            if (point) {
                                Object.assign(point, updates);
                                updatedEvent = JSON.parse(JSON.stringify(event));
                            }
                        } else if (event && 'point' in event && (event as any).point.uuid === pointUuid) {
                            Object.assign((event as any).point, updates);
                            updatedEvent = JSON.parse(JSON.stringify(event));
                        }
                    }
                });
                return updatedEvent;
            },

            // Action-level actions
            addAction: (productUuid, modelUuid, pointUuid, action) => {
                let updatedEvent: EventsSchema | undefined;
                set((state) => {
                    const product = state.products.find(p => p.productUuid === productUuid);
                    if (product) {
                        const event = product.eventDatas.find(e => 'modelUuid' in e && e.modelUuid === modelUuid);
                        if (event && 'points' in event) {
                            const point = (event as ConveyorEventSchema).points.find(p => p.uuid === pointUuid);
                            if (point && (!point.action || point.action.actionUuid !== action.actionUuid)) {
                                point.action = action as any;
                                updatedEvent = JSON.parse(JSON.stringify(event));
                            }
                        } else if (event && 'point' in event && (event as any).point.uuid === pointUuid) {
                            if ('action' in (event as any).point) {
                                if (!(event as any).point.action || (event as any).point.action.actionUuid !== action.actionUuid) {
                                    (event as any).point.action = action;
                                    updatedEvent = JSON.parse(JSON.stringify(event));
                                }
                            } else if ('actions' in (event as any).point) {
                                const existingAction = (event as any).point.actions.find((a: any) => a.actionUuid === action.actionUuid);
                                if (!existingAction) {
                                    (event as any).point.actions.push(action);
                                    updatedEvent = JSON.parse(JSON.stringify(event));
                                }
                            }
                        }
                    }
                });
                return updatedEvent;
            },

            removeAction: (productUuid, actionUuid) => {
                let updatedEvent: EventsSchema | undefined;
                set((state) => {
                    const product = state.products.find(p => p.productUuid === productUuid);
                    if (product) {
                        for (const event of product.eventDatas) {
                            if ('points' in event) {
                                // Handle ConveyorEventSchema
                                for (const point of (event as ConveyorEventSchema).points) {
                                }
                            } else if ('point' in event) {
                                const point = (event as any).point;
                                if (event.type === "roboticArm") {
                                    if ('actions' in point) {
                                        const index = point.actions.findIndex((a: any) => a.actionUuid === actionUuid);
                                        if (index !== -1) {
                                            point.actions.splice(index, 1);
                                            updatedEvent = JSON.parse(JSON.stringify(event));
                                            return;
                                        }
                                    }
                                } else if (event.type === "human") {
                                    if ('actions' in point) {
                                        const index = point.actions.findIndex((a: any) => a.actionUuid === actionUuid);
                                        if (index !== -1) {
                                            point.actions.splice(index, 1);
                                            updatedEvent = JSON.parse(JSON.stringify(event));
                                            return;
                                        }
                                    }
                                } else if ('action' in point && point.action?.actionUuid === actionUuid) {
                                    point.action = undefined;
                                    updatedEvent = JSON.parse(JSON.stringify(event));
                                    return;
                                }
                            }
                        }
                    }
                });
                return updatedEvent;
            },

            updateAction: (productUuid, actionUuid, updates) => {
                let updatedEvent: EventsSchema | undefined;
                set((state) => {
                    const product = state.products.find(p => p.productUuid === productUuid);
                    if (product) {
                        for (const event of product.eventDatas) {
                            if ('points' in event) {
                                for (const point of (event as ConveyorEventSchema).points) {
                                    if (point.action && point.action.actionUuid === actionUuid) {
                                        Object.assign(point.action, updates);
                                        updatedEvent = JSON.parse(JSON.stringify(event));
                                        return;
                                    }
                                }
                            } else if ('point' in event) {
                                const point = (event as any).point;
                                if ('action' in point && point.action.actionUuid === actionUuid) {
                                    Object.assign(point.action, updates);
                                    updatedEvent = JSON.parse(JSON.stringify(event));
                                    return;
                                } else if ('actions' in point) {
                                    const action = point.actions.find((a: any) => a.actionUuid === actionUuid);
                                    if (action) {
                                        Object.assign(action, updates);
                                        updatedEvent = JSON.parse(JSON.stringify(event));
                                        return;
                                    }
                                }
                            }
                        }
                    }
                });
                return updatedEvent;
            },

            // Trigger-level actions
            addTrigger: (productUuid, actionUuid, trigger) => {
                let updatedEvent: EventsSchema | undefined;
                set((state) => {
                    const product = state.products.find(p => p.productUuid === productUuid);
                    if (product) {
                        for (const event of product.eventDatas) {
                            if ('points' in event) {
                                for (const point of (event as ConveyorEventSchema).points) {
                                    if (point.action && point.action.actionUuid === actionUuid) {
                                        const existingTrigger = point.action.triggers.find(t => t.triggerUuid === trigger.triggerUuid);
                                        if (!existingTrigger) {
                                            point.action.triggers.push(trigger);
                                            updatedEvent = JSON.parse(JSON.stringify(event));
                                        }
                                        return;
                                    }
                                }
                            } else if ('point' in event) {
                                const point = (event as any).point;
                                if ('action' in point && point.action.actionUuid === actionUuid) {
                                    const existingTrigger = point.action.triggers.find((t: any) => t.triggerUuid === trigger.triggerUuid);
                                    if (!existingTrigger) {
                                        point.action.triggers.push(trigger);
                                        updatedEvent = JSON.parse(JSON.stringify(event));
                                    }
                                    return;
                                } else if ('actions' in point) {
                                    const action = point.actions.find((a: any) => a.actionUuid === actionUuid);
                                    if (action) {
                                        const existingTrigger = action.triggers.find((t: any) => t.triggerUuid === trigger.triggerUuid);
                                        if (!existingTrigger) {
                                            action.triggers.push(trigger);
                                            updatedEvent = JSON.parse(JSON.stringify(event));
                                        }
                                        return;
                                    }
                                }
                            }
                        }
                    }
                });
                return updatedEvent;
            },

            removeTrigger: (productUuid, triggerUuid) => {
                let updatedEvent: EventsSchema | undefined;
                set((state) => {
                    const product = state.products.find(p => p.productUuid === productUuid);
                    if (product) {
                        for (const event of product.eventDatas) {
                            if ('points' in event) {
                                for (const point of (event as ConveyorEventSchema).points) {
                                    if (point.action && 'triggers' in point.action) {
                                        const Trigger = point.action.triggers.find(t => t.triggerUuid === triggerUuid);
                                        if (Trigger) {
                                            point.action.triggers = point.action.triggers.filter(t => t.triggerUuid !== triggerUuid);
                                            updatedEvent = JSON.parse(JSON.stringify(event));
                                        }
                                    }
                                }
                            } else if ('point' in event) {
                                const point = (event as any).point;
                                if ('action' in point && 'triggers' in point.action) {
                                    const Trigger = point.action.triggers.find((t: any) => t.triggerUuid === triggerUuid);
                                    if (Trigger) {
                                        point.action.triggers = point.action.triggers.filter((t: any) => t.triggerUuid !== triggerUuid);
                                        updatedEvent = JSON.parse(JSON.stringify(event));
                                    }
                                } else if ('actions' in point) {
                                    for (const action of point.actions) {
                                        if ('triggers' in action) {
                                            const Trigger = action.triggers.find((t: any) => t.triggerUuid === triggerUuid);
                                            if (Trigger) {
                                                action.triggers = action.triggers.filter((t: any) => t.triggerUuid !== triggerUuid);
                                                updatedEvent = JSON.parse(JSON.stringify(event));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                });
                return updatedEvent;
            },

            updateTrigger: (productUuid, triggerUuid, updates) => {
                let updatedEvent: EventsSchema | undefined;
                set((state) => {
                    const product = state.products.find(p => p.productUuid === productUuid);
                    if (product) {
                        for (const event of product.eventDatas) {
                            if ('points' in event) {
                                for (const point of (event as ConveyorEventSchema).points) {
                                    if (point.action && 'triggers' in point.action) {
                                        const trigger = point.action.triggers.find(t => t.triggerUuid === triggerUuid);
                                        if (trigger) {
                                            Object.assign(trigger, updates);
                                            updatedEvent = JSON.parse(JSON.stringify(event));
                                            return;
                                        }
                                    }
                                }
                            } else if ('point' in event) {
                                const point = (event as any).point;
                                if ('action' in point && 'triggers' in point.action) {
                                    const trigger = point.action.triggers.find((t: any) => t.triggerUuid === triggerUuid);
                                    if (trigger) {
                                        Object.assign(trigger, updates);
                                        updatedEvent = JSON.parse(JSON.stringify(event));
                                        return;
                                    }
                                } else if ('actions' in point) {
                                    for (const action of point.actions) {
                                        if ('triggers' in action) {
                                            const trigger = action.triggers.find((t: any) => t.triggerUuid === triggerUuid);
                                            if (trigger) {
                                                Object.assign(trigger, updates);
                                                updatedEvent = JSON.parse(JSON.stringify(event));
                                                return;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                });
                return updatedEvent;
            },

            // Renaming functions
            renameProduct: (productUuid, newName) => {
                set((state) => {
                    const product = state.products.find(p => p.productUuid === productUuid);
                    if (product) {
                        product.productName = newName;
                    }
                });
            },

            renameAction: (productUuid, actionUuid, newName) => {
                let updatedEvent: EventsSchema | undefined;
                set((state) => {
                    const product = state.products.find(p => p.productUuid === productUuid);
                    if (product) {
                        for (const event of product.eventDatas) {
                            if ('points' in event) {
                                for (const point of (event as ConveyorEventSchema).points) {
                                    if (point.action && point.action.actionUuid === actionUuid) {
                                        point.action.actionName = newName;
                                        updatedEvent = JSON.parse(JSON.stringify(event));
                                        return;
                                    }
                                }
                            } else if ('point' in event) {
                                const point = (event as any).point;
                                if ('action' in point && point.action.actionUuid === actionUuid) {
                                    point.action.actionName = newName;
                                    updatedEvent = JSON.parse(JSON.stringify(event));
                                    return;
                                } else if ('actions' in point) {
                                    const action = point.actions.find((a: any) => a.actionUuid === actionUuid);
                                    if (action) {
                                        action.actionName = newName;
                                        updatedEvent = JSON.parse(JSON.stringify(event));
                                        return;
                                    }
                                }
                            }
                        }
                    }
                });
                return updatedEvent;
            },

            renameTrigger: (productUuid, triggerUuid, newName) => {
                let updatedEvent: EventsSchema | undefined;
                set((state) => {
                    const product = state.products.find(p => p.productUuid === productUuid);
                    if (product) {
                        for (const event of product.eventDatas) {
                            if ('points' in event) {
                                for (const point of (event as ConveyorEventSchema).points) {
                                    if (point.action && 'triggers' in point.action) {
                                        const trigger = point.action.triggers.find(t => t.triggerUuid === triggerUuid);
                                        if (trigger) {
                                            trigger.triggerName = newName;
                                            updatedEvent = JSON.parse(JSON.stringify(event));
                                            return;
                                        }
                                    }
                                }
                            } else if ('point' in event) {
                                const point = (event as any).point;
                                if ('action' in point && 'triggers' in point.action) {
                                    const trigger = point.action.triggers.find((t: any) => t.triggerUuid === triggerUuid);
                                    if (trigger) {
                                        trigger.triggerName = newName;
                                        updatedEvent = JSON.parse(JSON.stringify(event));
                                        return;
                                    }
                                } else if ('actions' in point) {
                                    for (const action of point.actions) {
                                        if ('triggers' in action) {
                                            const trigger = action.triggers.find((t: any) => t.triggerUuid === triggerUuid);
                                            if (trigger) {
                                                trigger.triggerName = newName;
                                                updatedEvent = JSON.parse(JSON.stringify(event));
                                                return;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                });
                return updatedEvent;
            },

            // Helper functions
            getProductById: (productUuid) => {
                return get().products.find(p => p.productUuid === productUuid);
            },

            getEventByModelUuid: (productUuid, modelUuid) => {
                const product = get().getProductById(productUuid);
                if (!product) return undefined;
                return product.eventDatas.find(e => 'modelUuid' in e && e.modelUuid === modelUuid);
            },

            getEventByActionUuid: (productUuid, actionUuid) => {
                const product = get().getProductById(productUuid);
                if (!product) return undefined;

                for (const event of product.eventDatas) {
                    if ('points' in event) {
                        for (const point of (event as ConveyorEventSchema).points) {
                            if (point.action?.actionUuid === actionUuid) {
                                return event;
                            }
                        }
                    } else if ('point' in event) {
                        const point = (event as any).point;
                        if ('action' in point && point.action?.actionUuid === actionUuid) {
                            return event;
                        } else if ('actions' in point) {
                            const action = point.actions.find((a: any) => a.actionUuid === actionUuid);
                            if (action) {
                                return event;
                            }
                        }
                    }
                }
                return undefined;
            },

            getEventByTriggerUuid: (productUuid, triggerUuid) => {
                const product = get().getProductById(productUuid);
                if (!product) return undefined;

                for (const event of product.eventDatas) {
                    if ('points' in event) {
                        for (const point of (event as ConveyorEventSchema).points) {
                            if (point.action?.triggers?.some(t => t.triggerUuid === triggerUuid)) {
                                return event;
                            }
                        }
                    } else if ('point' in event) {
                        const point = (event as any).point;
                        if ('action' in point) {
                            if (point.action?.triggers?.some((t: any) => t.triggerUuid === triggerUuid)) {
                                return event;
                            }
                        } else if ('actions' in point) {
                            for (const action of point.actions) {
                                if (action.triggers?.some((t: any) => t.triggerUuid === triggerUuid)) {
                                    return event;
                                }
                            }
                        }
                    }
                }
                return undefined;
            },

            getEventByPointUuid: (productUuid, pointUuid) => {
                const product = get().getProductById(productUuid);
                if (!product) return undefined;

                for (const event of product.eventDatas) {
                    if ('points' in event) {
                        if ((event as ConveyorEventSchema).points.some(p => p.uuid === pointUuid)) {
                            return event;
                        }
                    } else if ('point' in event) {
                        if ((event as any).point?.uuid === pointUuid) {
                            return event;
                        }
                    }
                }
                return undefined;
            },

            getPointByUuid: (productUuid, modelUuid, pointUuid) => {
                const event = get().getEventByModelUuid(productUuid, modelUuid);
                if (!event) return undefined;

                if ('points' in event) {
                    return (event as ConveyorEventSchema).points.find(p => p.uuid === pointUuid);
                } else if ('point' in event && (event as any).point.uuid === pointUuid) {
                    return (event as VehicleEventSchema | RoboticArmEventSchema | MachineEventSchema | StorageEventSchema).point;
                }
                return undefined;
            },

            getActionByUuid: (productUuid, actionUuid) => {
                const product = get().products.find(p => p.productUuid === productUuid);
                if (!product) return undefined;

                for (const event of product.eventDatas) {
                    if ('points' in event) {
                        for (const point of (event as ConveyorEventSchema).points) {
                            if (point.action?.actionUuid === actionUuid) {
                                return point.action;
                            }
                        }
                    } else if ('point' in event) {
                        const point = (event as any).point;
                        if ('action' in point && point.action?.actionUuid === actionUuid) {
                            return point.action;
                        } else if ('actions' in point) {
                            const action = point.actions.find((a: any) => a.actionUuid === actionUuid);
                            if (action) return action;
                        }
                    }
                }
                return undefined;
            },

            getActionByPointUuid: (productUuid, pointUuid) => {
                const product = get().products.find(p => p.productUuid === productUuid);
                if (!product) return undefined;

                for (const event of product.eventDatas) {
                    if ('points' in event) {
                        for (const point of (event as ConveyorEventSchema).points) {
                            if (point.uuid === pointUuid) {
                                return point.action;
                            }
                        }
                    } else if ('point' in event) {
                        const point = (event as any).point;
                        if (point.uuid === pointUuid) {
                            return point.action;
                        }
                    }
                }
                return undefined;
            },

            getModelUuidByPointUuid: (productUuid, pointUuid) => {
                const product = get().products.find(p => p.productUuid === productUuid);
                if (!product) return undefined;

                for (const event of product.eventDatas) {
                    if ('points' in event) {
                        for (const point of (event as ConveyorEventSchema).points) {
                            if (point.uuid === pointUuid) {
                                return event.modelUuid;
                            }
                        }
                    } else if ('point' in event) {
                        const point = (event as any).point;
                        if (point.uuid === pointUuid) {
                            return event.modelUuid;
                        }
                    }
                }
                return undefined;
            },

            getModelUuidByActionUuid: (productUuid, actionUuid) => {
                const product = get().products.find(p => p.productUuid === productUuid);
                if (!product) return undefined;

                for (const event of product.eventDatas) {
                    if ('points' in event) {
                        for (const point of (event as ConveyorEventSchema).points) {
                            if (point.action?.actionUuid === actionUuid) {
                                return event.modelUuid;
                            }
                        }
                    } else if ('point' in event) {
                        const point = (event as any).point;
                        if ('action' in point && point.action?.actionUuid === actionUuid) {
                            return event.modelUuid;
                        } else if ('actions' in point) {
                            const action = point.actions.find((a: any) => a.actionUuid === actionUuid);
                            if (action) return event.modelUuid;
                        }
                    }
                }
                return undefined;
            },

            getPointUuidByActionUuid: (productUuid, actionUuid) => {
                const product = get().products.find(p => p.productUuid === productUuid);
                if (!product) return undefined;

                for (const event of product.eventDatas) {
                    if ('points' in event) {
                        for (const point of (event as ConveyorEventSchema).points) {
                            if (point.action?.actionUuid === actionUuid) {
                                return point.uuid;
                            }
                        }
                    } else if ('point' in event) {
                        const point = (event as any).point;
                        if ('action' in point && point.action?.actionUuid === actionUuid) {
                            return point.uuid;
                        } else if ('actions' in point) {
                            const action = point.actions.find((a: any) => a.actionUuid === actionUuid);
                            if (action) return point.uuid;
                        }
                    }
                }
                return undefined;
            },

            getTriggerByUuid: (productUuid, triggerUuid) => {
                const product = get().products.find(p => p.productUuid === productUuid);
                if (!product) return undefined;

                for (const event of product.eventDatas) {
                    if ('points' in event) {
                        for (const point of (event as ConveyorEventSchema).points) {
                            for (const trigger of point.action?.triggers || []) {
                                if (trigger.triggerUuid === triggerUuid) {
                                    return trigger;
                                }
                            }
                        }
                    } else if ('point' in event) {
                        const point = (event as any).point;
                        if ('action' in point) {
                            for (const trigger of point.action?.triggers || []) {
                                if (trigger.triggerUuid === triggerUuid) {
                                    return trigger;
                                }
                            }
                        } else if ('actions' in point) {
                            for (const action of point.actions) {
                                for (const trigger of action.triggers || []) {
                                    if (trigger.triggerUuid === triggerUuid) {
                                        return trigger;
                                    }
                                }
                            }
                        }
                    }
                }
                return undefined;
            },

            getTriggersByTriggeredPointUuid: (productUuid, triggeredPointUuid) => {
                const product = get().products.find(p => p.productUuid === productUuid);
                if (!product) return [];

                const triggers: TriggerSchema[] = [];

                for (const event of product.eventDatas) {
                    if ('points' in event) {
                        for (const point of (event as ConveyorEventSchema).points) {
                            if (point.action?.triggers) {
                                for (const trigger of point.action.triggers) {
                                    if (trigger.triggeredAsset?.triggeredPoint?.pointUuid === triggeredPointUuid) {
                                        triggers.push(trigger);
                                    }
                                }
                            }
                        }
                    } else if ('point' in event) {
                        const point = (event as any).point;
                        if ('action' in point && point.action?.triggers) {
                            for (const trigger of point.action.triggers) {
                                if (trigger.triggeredAsset?.triggeredPoint?.pointUuid === triggeredPointUuid) {
                                    triggers.push(trigger);
                                }
                            }
                        } else if ('actions' in point) {
                            for (const action of point.actions) {
                                if (action.triggers) {
                                    for (const trigger of action.triggers) {
                                        if (trigger.triggeredAsset?.triggeredPoint?.pointUuid === triggeredPointUuid) {
                                            triggers.push(trigger);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                return triggers;
            },

            getIsEventInProduct: (productUuid, modelUuid) => {
                const product = get().getProductById(productUuid);
                if (!product) return false;
                return product.eventDatas.some(e => 'modelUuid' in e && e.modelUuid === modelUuid);
            }
        }))
    )
}

export type ProductStoreType = ReturnType<typeof createProductStore>;