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

interface ZoneStore {
    zones: Zone[];
    setZones: (zones: Zone[]) => void;
    addZone: (zone: Zone) => void;
    updateZone: (uuid: string, updated: Partial<Zone>) => void;
    removeZone: (uuid: string) => void;
    removePointFromZones: (pointUuid: string) => void;
    clearZones: () => void;
    setViewPort: (uuid: string, position: [number, number, number], target: [number, number, number]) => void;
    setColor: (uuid: string, color: string) => void;

    getZoneById: (uuid: string) => Zone | undefined;
}

export const createZoneStore = () => {
    return create<ZoneStore>()(
        immer((set, get) => ({
            zones: [],

            setZones: (zones) => set(state => {
                state.zones = zones;
            }),

            addZone: (zone) => set(state => {
                state.zones.push(zone);
            }),

            updateZone: (uuid, updated) => set(state => {
                const zone = state.zones.find(z => z.zoneUuid === uuid);
                if (zone) {
                    Object.assign(zone, updated);
                }
            }),

            removeZone: (uuid) => set(state => {
                state.zones = state.zones.filter(z => z.zoneUuid !== uuid);
            }),

            removePointFromZones: (pointUuid) => set(state => {
                for (const zone of state.zones) {
                    zone.points = zone.points.filter(p => p.pointUuid !== pointUuid);
                }
            }),

            clearZones: () => set(state => {
                state.zones = [];
            }),

            setViewPort: (uuid, position, target) => set(state => {
                const zone = state.zones.find(z => z.zoneUuid === uuid);
                if (zone) {
                    zone.viewPortPosition = position;
                    zone.viewPortTarget = target;
                }
            }),

            setColor: (uuid, color) => set(state => {
                const zone = state.zones.find(z => z.zoneUuid === uuid);
                if (zone) {
                    zone.zoneColor = color;
                }
            }),

            getZoneById: (uuid) => {
                return get().zones.find(z => z.zoneUuid === uuid);
            },
        }))
    );
};

export type ZoneStoreType = ReturnType<typeof createZoneStore>;