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

interface StorageUnitStore {
    storageUnits: StorageUnitStatus[];

    addStorageUnit: (productUuid: string, storageUnit: StorageEventSchema) => void;
    removeStorageUnit: (modelUuid: string) => void;
    updateStorageUnit: (
        modelUuid: string,
        updates: Partial<Omit<StorageUnitStatus, 'modelUuid' | 'productUuid'>>
    ) => void;
    clearStorageUnits: () => void;

    setStorageUnitActive: (modelUuid: string, isActive: boolean) => void;
    setStorageUnitState: (modelUuid: string, newState: StorageUnitStatus['state']) => void;

    updateCurrentLoad: (modelUuid: string, incrementBy: number) => void;

    incrementActiveTime: (modelUuid: string, incrementBy: number) => void;
    incrementIdleTime: (modelUuid: string, incrementBy: number) => void;

    addCurrentMaterial: (modelUuid: string, materialType: string, materialId: string) => void;
    setCurrentMaterials: (modelUuid: string, materials: { materialType: string; materialId: string; }[]) => void;
    getLastMaterial: (modelUuid: string) => { materialId: string; materialType: string; } | undefined;
    removeLastMaterial: (modelUuid: string) => { materialId: string; materialType: string; } | undefined;
    clearCurrentMaterials: (modelUuid: string) => void;

    getStorageUnitById: (modelUuid: string) => StorageUnitStatus | undefined;
    getStorageUnitsByProduct: (productUuid: string) => StorageUnitStatus[];
    getStorageUnitsBystate: (state: string) => StorageUnitStatus[];
    getActiveStorageUnits: () => StorageUnitStatus[];
    getIdleStorageUnits: () => StorageUnitStatus[];
    getFullStorageUnits: () => StorageUnitStatus[];
    getEmptyStorageUnits: () => StorageUnitStatus[];
}

export const createStorageUnitStore = () => {
    return create<StorageUnitStore>()(
        immer((set, get) => ({
            storageUnits: [],

            addStorageUnit: (productUuid, storageUnit) => {
                set((state) => {
                    const exists = state.storageUnits.some(s => s.modelUuid === storageUnit.modelUuid);
                    if (!exists) {
                        state.storageUnits.push({
                            ...storageUnit,
                            productUuid,
                            isActive: false,
                            idleTime: 0,
                            activeTime: 0,
                            currentLoad: 0,
                            currentMaterials: [],
                            state: 'idle'
                        });
                    }
                });
            },

            removeStorageUnit: (modelUuid) => {
                set((state) => {
                    state.storageUnits = state.storageUnits.filter(s => s.modelUuid !== modelUuid);
                });
            },

            updateStorageUnit: (modelUuid, updates) => {
                set((state) => {
                    const unit = state.storageUnits.find(s => s.modelUuid === modelUuid);
                    if (unit) {
                        Object.assign(unit, updates);
                    }
                });
            },

            clearStorageUnits: () => {
                set(() => ({
                    storageUnits: [],
                }));
            },

            setStorageUnitActive: (modelUuid, isActive) => {
                set((state) => {
                    const unit = state.storageUnits.find(s => s.modelUuid === modelUuid);
                    if (unit) {
                        unit.isActive = isActive;
                    }
                });
            },

            setStorageUnitState: (modelUuid, newState) => {
                set((state) => {
                    const unit = state.storageUnits.find(s => s.modelUuid === modelUuid);
                    if (unit) {
                        unit.state = newState;
                    }
                });
            },

            updateCurrentLoad: (modelUuid, incrementBy) => {
                set((state) => {
                    const unit = state.storageUnits.find(s => s.modelUuid === modelUuid);
                    if (unit) {
                        unit.currentLoad += incrementBy;
                    }
                });
            },

            incrementActiveTime: (modelUuid, incrementBy) => {
                set((state) => {
                    const unit = state.storageUnits.find(s => s.modelUuid === modelUuid);
                    if (unit) {
                        unit.activeTime += incrementBy;
                    }
                });
            },

            incrementIdleTime: (modelUuid, incrementBy) => {
                set((state) => {
                    const unit = state.storageUnits.find(s => s.modelUuid === modelUuid);
                    if (unit) {
                        unit.idleTime += incrementBy;
                    }
                });
            },

            addCurrentMaterial: (modelUuid, materialType, materialId) => {
                set((state) => {
                    const storage = state.storageUnits.find((s) => s.modelUuid === modelUuid);
                    if (storage) {
                        storage.currentMaterials.push({ materialType, materialId });
                    }
                });
            },

            setCurrentMaterials: (modelUuid, materials) => {
                set((state) => {
                    const storage = state.storageUnits.find((s) => s.modelUuid === modelUuid);
                    if (storage) {
                        storage.currentMaterials = materials;
                    }
                });
            },

            getLastMaterial: (modelUuid) => {
                let removedMaterial: { materialId: string; materialType: string; } | undefined;
                set((state) => {
                    const storage = state.storageUnits.find((s) => s.modelUuid === modelUuid);
                    if (storage) {
                        if (storage.currentMaterials.length > 0) {
                            const material = storage.currentMaterials[storage.currentMaterials.length - 1];
                            if (material) {
                                removedMaterial = { materialId: material.materialId, materialType: material.materialType };
                            }
                        }
                    }
                });
                return removedMaterial;
            },

            removeLastMaterial: (modelUuid) => {
                let removedMaterial: { materialId: string; materialType: string; } | undefined;
                set((state) => {
                    const storage = state.storageUnits.find((s) => s.modelUuid === modelUuid);
                    if (storage) {
                        if (storage.currentMaterials.length > 0) {
                            const material = storage.currentMaterials.pop();
                            if (material) {
                                removedMaterial = { materialId: material.materialId, materialType: material.materialType };
                            }
                        }
                    }
                });
                return removedMaterial;
            },

            clearCurrentMaterials: (modelUuid) => {
                set((state) => {
                    const storage = state.storageUnits.find((s) => s.modelUuid === modelUuid);
                    if (storage) {
                        storage.currentMaterials = [];
                    }
                });
            },

            getStorageUnitById: (modelUuid) => {
                return get().storageUnits.find(s => s.modelUuid === modelUuid);
            },

            getStorageUnitsByProduct: (productUuid) => {
                return get().storageUnits.filter(s => s.productUuid === productUuid);
            },

            getStorageUnitsBystate: (state) => {
                return get().storageUnits.filter(s => s.state === state);
            },

            getActiveStorageUnits: () => {
                return get().storageUnits.filter(s => s.isActive);
            },

            getIdleStorageUnits: () => {
                return get().storageUnits.filter(s => !s.isActive && s.state === 'idle');
            },

            getFullStorageUnits: () => {
                return get().storageUnits.filter(
                    s => s.currentLoad >= s.point.action.storageCapacity
                );
            },

            getEmptyStorageUnits: () => {
                return get().storageUnits.filter(s => s.currentLoad === 0);
            },
        }))
    )
}

export type StorageUnitStoreType = ReturnType<typeof createStorageUnitStore>;