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

interface AisleStore {
    aisles: Aisles;
    setAisles: (aisles: Aisles) => void;
    addAisle: (aisle: Aisle) => void;
    updateAisle: (uuid: string, updated: Partial<Aisle>) => void;
    removeAisle: (uuid: string) => void;
    setPosition: (pointUuid: string, position: [number, number, number]) => void;
    setLayer: (pointUuid: string, layer: number) => void;
    setColor: (aisleUuid: string, color: AisleColors) => void;
    setWidth: (aisleUuid: string, width: number) => void;
    getAisleById: (uuid: string) => Aisle | undefined;
}

export const useAisleStore = create<AisleStore>()(
    immer((set, get) => ({
        aisles: [],

        setAisles: (aisles) => set((state) => {
            state.aisles = aisles;
        }),

        addAisle: (aisle) => set((state) => {
            state.aisles.push(aisle);
        }),

        updateAisle: (uuid, updated) => set((state) => {
            const aisle = state.aisles.find((a) => a.uuid === uuid);
            if (aisle) {
                Object.assign(aisle, updated);
            }
        }),

        removeAisle: (uuid) => set((state) => {
            state.aisles = state.aisles.filter((a) => a.uuid !== uuid);
        }),

        setPosition: (pointUuid: string, position: [number, number, number]) => set((state) => {
            for (const aisle of state.aisles) {
                const point = aisle.points.find(p => p.uuid === pointUuid);
                if (point) {
                    point.position = position;
                    break;
                }
            }
        }),

        setLayer: (pointUuid: string, layer: number) => set((state) => {
            for (const aisle of state.aisles) {
                const point = aisle.points.find(p => p.uuid === pointUuid);
                if (point) {
                    point.layer = layer;
                    break;
                }
            }
        }),

        setColor: (aisleUuid: string, color: AisleColors) => set((state) => {
            const aisle = state.aisles.find(a => a.uuid === aisleUuid);
            if (aisle) {
                aisle.type.aisleColor = color;
            }
        }),

        setWidth: (aisleUuid: string, width: number) => set((state) => {
            const aisle = state.aisles.find(a => a.uuid === aisleUuid);
            if (aisle) {
                aisle.type.aisleWidth = width;
            }
        }),

        getAisleById: (uuid) => {
            return get().aisles.find((a) => a.uuid === uuid);
        },
    }))
);
