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

type ProductsStore = {
    products: productsSchema;

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

    // Event-level actions
    addEvent: (productId: string, event: EventsSchema) => void;
    removeEvent: (productId: string, modelUuid: string) => void;
    updateEvent: (productId: string, modelUuid: string, updates: Partial<EventsSchema>) => void;

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

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

    // Trigger-level actions
    addTrigger: (
        actionUuid: string,
        trigger: TriggerSchema
    ) => void;
    removeTrigger: (triggerUuid: string) => void;
    updateTrigger: (
        triggerUuid: string,
        updates: Partial<TriggerSchema>
    ) => void;

    // Renaming functions
    renameProduct: (productId: string, newName: string) => void;
    renameAction: (actionUuid: string, newName: string) => void;
    renameTrigger: (triggerUuid: string, newName: string) => void;

    // Helper functions
    getProductById: (productId: string) => { productName: string; productId: string; eventDatas: EventsSchema[] } | undefined;
    getEventByModelUuid: (productId: string, modelUuid: string) => EventsSchema | undefined;
    getPointByUuid: (productId: string, modelUuid: string, pointUuid: string) => ConveyorPointSchema | VehiclePointSchema | RoboticArmPointSchema | MachinePointSchema | StoragePointSchema | undefined;
    getActionByUuid: (productId: string, actionUuid: string) => (ConveyorPointSchema['action'] | VehiclePointSchema['action'] | RoboticArmPointSchema['actions'][0] | MachinePointSchema['action'] | StoragePointSchema['action']) | undefined;
    getTriggerByUuid: (productId: string, triggerUuid: string) => TriggerSchema | undefined;
    getIsEventInProduct: (productId: string, modelUuid: string) => boolean;
};

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

        // Product-level actions
        addProduct: (productName, productId) => {
            set((state) => {
                const newProduct = {
                    productName,
                    productId: productId,
                    eventDatas: []
                };
                state.products.push(newProduct);
            });
        },

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

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

        // Event-level actions
        addEvent: (productId, event) => {
            set((state) => {
                const product = state.products.find(p => p.productId === productId);
                if (product) {
                    product.eventDatas.push(event);
                }
            });
        },

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

        updateEvent: (productId, modelUuid, updates) => {
            set((state) => {
                const product = state.products.find(p => p.productId === productId);
                if (product) {
                    const event = product.eventDatas.find(e => 'modelUuid' in e && e.modelUuid === modelUuid);
                    if (event) {
                        Object.assign(event, updates);
                    }
                }
            });
        },

        // Point-level actions
        addPoint: (productId, modelUuid, point) => {
            set((state) => {
                const product = state.products.find(p => p.productId === productId);
                if (product) {
                    const event = product.eventDatas.find(e => 'modelUuid' in e && e.modelUuid === modelUuid);
                    if (event && 'points' in event) {
                        (event as ConveyorEventSchema).points.push(point as ConveyorPointSchema);
                    } else if (event && 'point' in event) {
                        (event as VehicleEventSchema | RoboticArmEventSchema | MachineEventSchema | StorageEventSchema).point = point as any;
                    }
                }
            });
        },

        removePoint: (productId, modelUuid, pointUuid) => {
            set((state) => {
                const product = state.products.find(p => p.productId === productId);
                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);
                    } 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
                    }
                }
            });
        },

        updatePoint: (productId, modelUuid, pointUuid, updates) => {
            set((state) => {
                const product = state.products.find(p => p.productId === productId);
                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);
                        }
                    } else if (event && 'point' in event && (event as any).point.uuid === pointUuid) {
                        Object.assign((event as any).point, updates);
                    }
                }
            });
        },

        // Action-level actions
        addAction: (productId, modelUuid, pointUuid, action) => {
            set((state) => {
                const product = state.products.find(p => p.productId === productId);
                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 = action as any;
                        }
                    } else if (event && 'point' in event && (event as any).point.uuid === pointUuid) {
                        if ('action' in (event as any).point) {
                            (event as any).point.action = action;
                        } else if ('actions' in (event as any).point) {
                            (event as any).point.actions.push(action);
                        }
                    }
                }
            });
        },

        removeAction: (actionUuid: string) => {
            set((state) => {
                for (const product of state.products) {
                    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") {
                                // Handle RoboticArmEventSchema
                                if ('actions' in point) {
                                    point.actions = point.actions.filter((a: any) => a.actionUuid !== actionUuid);
                                }
                            } else if ('action' in point && point.action?.actionUuid === actionUuid) {
                                // For other schemas with a single 'action'
                            }
                        }
                    }
                }
            });
        },

        updateAction: (actionUuid, updates) => {
            set((state) => {
                for (const product of state.products) {
                    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);
                                    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);
                                return;
                            } else if ('actions' in point) {
                                const action = point.actions.find((a: any) => a.actionUuid === actionUuid);
                                if (action) {
                                    Object.assign(action, updates);
                                    return;
                                }
                            }
                        }
                    }
                }
            });
        },

        // Trigger-level actions
        addTrigger: (actionUuid, trigger) => {
            set((state) => {
                for (const product of state.products) {
                    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.triggers.push(trigger);
                                    return;
                                }
                            }
                        } else if ('point' in event) {
                            const point = (event as any).point;
                            if ('action' in point && point.action.actionUuid === actionUuid) {
                                point.action.triggers.push(trigger);
                                return;
                            } else if ('actions' in point) {
                                const action = point.actions.find((a: any) => a.actionUuid === actionUuid);
                                if (action) {
                                    action.triggers.push(trigger);
                                    return;
                                }
                            }
                        }
                    }
                }
            });
        },

        removeTrigger: (triggerUuid) => {
            set((state) => {
                for (const product of state.products) {
                    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) {
                                    point.action.triggers = point.action.triggers.filter(t => t.triggerUuid !== triggerUuid);
                                }
                            }
                        } else if ('point' in event) {
                            const point = (event as any).point;
                            if ('action' in point && 'triggers' in point.action) {
                                point.action.triggers = point.action.triggers.filter((t: any) => t.triggerUuid !== triggerUuid);
                            } else if ('actions' in point) {
                                for (const action of point.actions) {
                                    if ('triggers' in action) {
                                        action.triggers = action.triggers.filter((t: any) => t.triggerUuid !== triggerUuid);
                                    }
                                }
                            }
                        }
                    }
                }
            });
        },

        updateTrigger: (triggerUuid, updates) => {
            set((state) => {
                for (const product of state.products) {
                    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);
                                        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);
                                    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);
                                            return;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            });
        },

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

        renameAction: (actionUuid, newName) => {
            set((state) => {
                for (const product of state.products) {
                    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;
                                    return;
                                }
                            }
                        } else if ('point' in event) {
                            const point = (event as any).point;
                            if ('action' in point && point.action.actionUuid === actionUuid) {
                                point.action.actionName = newName;
                                return;
                            } else if ('actions' in point) {
                                const action = point.actions.find((a: any) => a.actionUuid === actionUuid);
                                if (action) {
                                    action.actionName = newName;
                                    return;
                                }
                            }
                        }
                    }
                }
            });
        },

        renameTrigger: (triggerUuid, newName) => {
            set((state) => {
                for (const product of state.products) {
                    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;
                                        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;
                                    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;
                                            return;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            });
        },

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

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

        getPointByUuid: (productId, modelUuid, pointUuid) => {
            const event = get().getEventByModelUuid(productId, 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: (productId, actionUuid) => {
            const product = get().products.find(p => p.productId === productId);
            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;
        },

        getTriggerByUuid: (productId, triggerUuid) => {
            const product = get().products.find(p => p.productId === productId);
            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;
        },

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