import { OSMWay } from "@repo/db";
import { create } from "zustand";

export interface MapStore {
	contextMenu: {
		lat: number;
		lng: number;
	} | null;
	map: {
		center: L.LatLngExpression;
		zoom: number;
	};
	setMap: (map: MapStore["map"]) => void;
	openMissionMarker: {
		id: number;
		tab: "home" | "details" | "patient" | "log";
	}[];
	setOpenMissionMarker: (mission: { open: MapStore["openMissionMarker"]; close: number[] }) => void;
	openAircraftMarker: {
		id: number;
		tab: "home" | "fms" | "aircraft" | "mission" | "chat";
	}[];
	setOpenAircraftMarker: (aircraft: {
		open: MapStore["openAircraftMarker"];
		close: number[];
	}) => void;
	searchElements: OSMWay[];
	setSearchElements: (elements: MapStore["searchElements"]) => void;
	toggleSearchElementSelection: (elementId: number) => void;
	setContextMenu: (popup: MapStore["contextMenu"]) => void;
	searchPopup: {
		lat: number;
		lng: number;
		elementId: number;
	} | null;
	setSearchPopup: (popup: MapStore["searchPopup"]) => void;
	aircraftTabs: {
		[aircraftId: string]: "home" | "fms" | "aircraft" | "mission" | "chat";
	};
	setAircraftTab: (aircraftId: number, tab: MapStore["aircraftTabs"][number]) => void;
}

export const useMapStore = create<MapStore>((set, get) => ({
	openMissionMarker: [],
	setOpenMissionMarker: ({ open, close }) => {
		const oldMarkers = get().openMissionMarker.filter(
			(m) => !close.includes(m.id) && !open.find((o) => o.id === m.id),
		);
		set(() => ({
			openMissionMarker: [...oldMarkers, ...open],
		}));
	},
	openAircraftMarker: [],
	setOpenAircraftMarker: ({ open, close }) => {
		const oldMarkers = get().openAircraftMarker.filter(
			(m) => !close.includes(m.id) && !open.find((o) => o.id === m.id),
		);
		set(() => ({
			openAircraftMarker: [...oldMarkers, ...open],
		}));
	},
	map: {
		center: [51.5, 10.5],
		zoom: 6,
	},
	setMap: (map) => {
		set(() => ({
			map,
		}));
	},
	searchPopup: null,
	searchElements: [],
	setSearchPopup: (popup) =>
		set(() => ({
			searchPopup: popup,
		})),
	contextMenu: null,
	setContextMenu: (contextMenu) =>
		set(() => ({
			contextMenu,
		})),
	setSearchElements: (elements) =>
		set(() => ({
			searchElements: elements,
		})),
	toggleSearchElementSelection: (elementId) => {
		const searchElements = get().searchElements;
		const element = searchElements.find((e) => e.wayID === elementId);
		if (!element) return;
		element.isSelected = !element.isSelected;
		set(() => ({
			searchElements: [...searchElements],
		}));
	},
	aircraftTabs: {},
	setAircraftTab: (aircraftId, tab) =>
		set((state) => ({
			aircraftTabs: {
				...state.aircraftTabs,
				[aircraftId]: tab,
			},
		})),
	missionTabs: {},
}));
