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;
    removePoint: (uuid: string) => Aisles;
    clearAisles: () => void;
    setPosition: (
        pointUuid: string,
        position: [number, number, number]
    ) => Aisle | undefined;
    setLayer: (pointUuid: string, layer: number) => void;
    setColor: (aisleUuid: string, color: AisleColors) => void;

    // Type-specific setters
    setSolidAisleWidth: (aisleUuid: string, width: number) => void;
    setDashedAisleProperties: (
        aisleUuid: string,
        props: { aisleWidth?: number; dashLength?: number; gapLength?: number }
    ) => void;
    setDottedAisleProperties: (
        aisleUuid: string,
        props: { dotRadius?: number; gapLength?: number }
    ) => void;
    setArrowAisleWidth: (aisleUuid: string, width: number) => void;
    setArrowsAisleProperties: (
        aisleUuid: string,
        props: { aisleWidth?: number; aisleLength?: number; gapLength?: number }
    ) => void;
    setArcAisleWidth: (
        aisleUuid: string,
        props: { aisleWidth?: number; isFlipped: boolean }
    ) => void;
    setCircleAisleWidth: (aisleUuid: string, width: number) => void;
    setJunctionAisleProperties: (
        aisleUuid: string,
        props: { aisleWidth?: number; isFlipped: boolean }
    ) => void;

    getAisleById: (uuid: string) => Aisle | undefined;
    getAislesByPointId: (uuid: string) => Aisle[] | [];
    getAislePointById: (uuid: string) => Point | undefined;
    getConnectedPoints: (uuid: string) => Point[] | [];
    getAisleType: <T extends AisleType>(uuid: string) => T | undefined;
}

export const createAisleStore = () => {
    return 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.aisleUuid === uuid);
                    if (aisle) {
                        Object.assign(aisle, updated);
                    }
                }),

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

            removePoint: (uuid) => {
                const removedAisles: Aisle[] = [];
                set((state) => {
                    state.aisles = state.aisles.filter((aisle) => {
                        const hasPoint = aisle.points.some(
                            (point) => point.pointUuid === uuid
                        );
                        if (hasPoint) {
                            removedAisles.push(JSON.parse(JSON.stringify(aisle)));
                            return false;
                        }
                        return true;
                    });
                });
                return removedAisles;
            },

            clearAisles: () => {
                set((state) => {
                    state.aisles = [];
                })
            },

            setPosition: (pointUuid, position) => {
                let updatedAisle: Aisle | undefined;
                set((state) => {
                    for (const aisle of state.aisles) {
                        const point = aisle.points.find((p) => p.pointUuid === pointUuid);
                        if (point) {
                            point.position = position;
                            updatedAisle = JSON.parse(JSON.stringify(aisle));
                        }
                    }
                });
                return updatedAisle;
            },

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

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

            // Type-specific property setters
            setSolidAisleWidth: (aisleUuid, width) =>
                set((state) => {
                    const aisle = state.aisles.find((a) => a.aisleUuid === aisleUuid);
                    if (aisle && aisle.type.aisleType === "solid-aisle") {
                        aisle.type.aisleWidth = width;
                    }
                }),

            setDashedAisleProperties: (aisleUuid, props) =>
                set((state) => {
                    const aisle = state.aisles.find((a) => a.aisleUuid === aisleUuid);
                    if (aisle && aisle.type.aisleType === "dashed-aisle") {
                        if (props.aisleWidth !== undefined)
                            aisle.type.aisleWidth = props.aisleWidth;
                        if (props.dashLength !== undefined)
                            aisle.type.dashLength = props.dashLength;
                        if (props.gapLength !== undefined)
                            aisle.type.gapLength = props.gapLength;
                    }
                }),

            setDottedAisleProperties: (aisleUuid, props) =>
                set((state) => {
                    const aisle = state.aisles.find((a) => a.aisleUuid === aisleUuid);
                    if (aisle && aisle.type.aisleType === "dotted-aisle") {
                        if (props.dotRadius !== undefined)
                            aisle.type.dotRadius = props.dotRadius;
                        if (props.gapLength !== undefined)
                            aisle.type.gapLength = props.gapLength;
                    }
                }),

            setArrowAisleWidth: (aisleUuid, width) =>
                set((state) => {
                    const aisle = state.aisles.find((a) => a.aisleUuid === aisleUuid);
                    if (aisle && aisle.type.aisleType === "arrow-aisle") {
                        aisle.type.aisleWidth = width;
                    }
                }),

            setArrowsAisleProperties: (aisleUuid, props) =>
                set((state) => {
                    const aisle = state.aisles.find((a) => a.aisleUuid === aisleUuid);
                    if (aisle && aisle.type.aisleType === "arrows-aisle") {
                        if (props.aisleWidth !== undefined)
                            aisle.type.aisleWidth = props.aisleWidth;
                        if (props.aisleLength !== undefined)
                            aisle.type.aisleLength = props.aisleLength;
                        if (props.gapLength !== undefined)
                            aisle.type.gapLength = props.gapLength;
                    }
                }),

            setArcAisleWidth: (aisleUuid, props) =>
                set((state) => {
                    const aisle = state.aisles.find((a) => a.aisleUuid === aisleUuid);
                    if (aisle && aisle.type.aisleType === "arc-aisle") {
                        if (props.aisleWidth !== undefined)
                            aisle.type.aisleWidth = props.aisleWidth;
                        if (props.isFlipped !== undefined)
                            aisle.type.isFlipped = props.isFlipped;
                    }
                }),

            setCircleAisleWidth: (aisleUuid, width) =>
                set((state) => {
                    const aisle = state.aisles.find((a) => a.aisleUuid === aisleUuid);
                    if (aisle && aisle.type.aisleType === "circle-aisle") {
                        aisle.type.aisleWidth = width;
                    }
                }),

            setJunctionAisleProperties: (aisleUuid, props) =>
                set((state) => {
                    const aisle = state.aisles.find((a) => a.aisleUuid === aisleUuid);
                    if (aisle && aisle.type.aisleType === "junction-aisle") {
                        if (props.aisleWidth !== undefined)
                            aisle.type.aisleWidth = props.aisleWidth;
                        if (props.isFlipped !== undefined)
                            aisle.type.isFlipped = props.isFlipped;
                    }
                }),

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

            getAislesByPointId: (uuid) => {
                return get().aisles.filter((a) => {
                    return a.points.some((p) => p.pointUuid === uuid);
                })
            },

            getAislePointById: (uuid) => {
                for (const aisle of get().aisles) {
                    const point = aisle.points.find((p) => p.pointUuid === uuid);
                    if (point) {
                        return point;
                    }
                }
                return undefined;
            },

            getConnectedPoints: (uuid) => {
                const connected: Point[] = [];
                for (const aisle of get().aisles) {
                    for (const point of aisle.points) {
                        if (point.pointUuid === uuid) {
                            connected.push(...aisle.points.filter((p) => p.pointUuid !== uuid));
                        }
                    }
                }
                return connected;
            },

            getAisleType: <T extends AisleType>(uuid: string) => {
                const aisle = get().aisles.find((a) => a.aisleUuid === uuid);
                return aisle?.type as T | undefined;
            },
        }))
    )
}

export type AisleStoreType = ReturnType<typeof createAisleStore>;